问:
Angular 12 .Net 6 value null being passed to api as "null"
I have an angular 12 UI that is communicating with a .net 6 API. When a parameter in a query string is null or undefined the API is interpreting it as a string value of "null" or "undefined". Relevant code below

angular code:

```<code>getDummyUser(type: string, testId: string):
Observable<UserDto> {
var url = `api/users/get-dummy-user?type=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;
return this.httpClient.get<any>(url)
  .pipe(
    finalize(() =>
      this.hideLoadingIndicators()
    ),
    catchError(err => {
      return throwError(err);
    })
  );
</code>```

}

.net 6 api parameter signature

```<code>[HttpGet]
    [Route("get-dummy-user")]
    public async Task<IActionResult> GetDummyUser
        (
        string type,
        string testId
        )
</code>```

I have tried using the [FromQuery] attribute but the result is the same. I also cannot send '' from the angular app as the API will then throw a 400 error (bad request). Has anyone had any experience in this? Thanks in advance

答:
I don't know if this is something to do with new .net 6 or angular 12 but it appears that nowadays you have to send an empty string as the parameter AND make string nullable on the .net side. I'm not sure why string has to be declared as nullable now when it is... inherently nullable. Having issues with code formatting, apologies. Working solution below

```<code>getDummyUser(type) {
  this.userProvider.getDummyUser(type, '').subscribe(u => {
});

getDummyUser(type: string, testId: string):Observable<UserDto> {var url = `api/users/get-dummy-usertype=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;return this.httpClient.get<any>(url).pipe(
finalize(() =>
  this.hideLoadingIndicators()
),
catchError(err => {
  return throwError(err);
})
</code>```

);

```<code>  [HttpGet]
[Route("get-dummy-user")]
public async Task<IActionResult> GetDummyUser
    (
    [FromQuery] string type,
    [FromQuery] string? testId
    )
</code>```

Body:
I have an angular 12 UI that is communicating with a .net 6 API. When a parameter in a query string is null or undefined the API is interpreting it as a string value of "null" or "undefined". Relevant code below

angular code:

getDummyUser(type: string, testId: string):
Observable<UserDto> {
var url = `api/users/get-dummy-user?type=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;
return this.httpClient.get<any>(url)
  .pipe(
    finalize(() =>
      this.hideLoadingIndicators()
    ),
    catchError(err => {
      return throwError(err);
    })
  );

}

.net 6 api parameter signature

[HttpGet]
    [Route("get-dummy-user")]
    public async Task<IActionResult> GetDummyUser
        (
        string type,
        string testId
        )

I have tried using the [FromQuery] attribute but the result is the same. I also cannot send '' from the angular app as the API will then throw a 400 error (bad request). Has anyone had any experience in this? Thanks in advance

Body:
I don't know if this is something to do with new .net 6 or angular 12 but it appears that nowadays you have to send an empty string as the parameter AND make string nullable on the .net side. I'm not sure why string has to be declared as nullable now when it is... inherently nullable. Having issues with code formatting, apologies. Working solution below

getDummyUser(type) {
  this.userProvider.getDummyUser(type, '').subscribe(u => {
});

getDummyUser(type: string, testId: string):Observable<UserDto> {var url = `api/users/get-dummy-usertype=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;return this.httpClient.get<any>(url).pipe(
finalize(() =>
  this.hideLoadingIndicators()
),
catchError(err => {
  return throwError(err);
})

);

  [HttpGet]
[Route("get-dummy-user")]
public async Task<IActionResult> GetDummyUser
    (
    [FromQuery] string type,
    [FromQuery] string? testId
    )


来源: stackexchange

问:
How to add .NET 3.5 and .NET 4.0 assemblies to FxCop code analysis?
I want to analyze a solution that contains projects targeting .NET 3.5 SP1 and some other projects targeting .NET 4 with some dependencies to .NET 3.5 libraries.

When I try to add both assemblies, one for .NET 3.5 and another for .NET 4, FxCop throws an exception:

```<code>AssemblyLoadException
Conflicting target platforms
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' vs
'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
</code>```

Is there any way to tell FxCop to only use version 4.0.0.0?

答:
Is there any way to tell FxCop to only use version 4.0.0.0?

No, I don't think there is - you will need one FxCop project for the projects targeting .NET 3.5, and another for those targeting .NET 4.0.

ContentLicense: CC BY-SA 3.0

Body:
I want to analyze a solution that contains projects targeting .NET 3.5 SP1 and some other projects targeting .NET 4 with some dependencies to .NET 3.5 libraries.

When I try to add both assemblies, one for .NET 3.5 and another for .NET 4, FxCop throws an exception:

AssemblyLoadException
Conflicting target platforms
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' vs
'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Is there any way to tell FxCop to only use version 4.0.0.0?


问:
DAX Doesnt Support Comparison
I have a table of Employees. The Table has both current and budgeted employees. Each employees has a salary, start date and if applicable a term date associated with them.

I am attempting for project the salary spend for each month for the next year based on the following rules:

Hire_Date <= Projected_Month

Term_Date > Projected_Month

Measure:

```<code>CALCULATE(sum(INPUT_TECH[Salary_USD]),filter(INPUT_TECH,INPUT_TECH[Hire_Date]<=MEASURE_SWB_SPEND[MEASURE_SWB_SPEND_DATE]&&INPUT_TECH[Term_Date]>MEASURE_SWB_SPEND[MEASURE_SWB_SPEND_DATE]))
</code>```

The issue here is that if ther is no Term_date, the cell will be blank, and if the cell is blank, the term_date will always be less than the current projected month and therefore the answer will always be 0.

I attempted to fix this by changing the format of the termdate to always either have the number 100,000 formated to read "ACTIVE" or the date they were actually terminated
Format: [=100000]"ACTIVE";[<>100000]mm/dd/yyyy

However, I still receive the following error:

DAX comparison operations do not support comparing values of type Text with values of type Date. Consider using the VALUE or FORMAT function to convert one of the values.

答:
I would suggest not formatting the term date to the string "Active" and then using it for comparisons in your measures. This is why you may be getting that specific error. DAX is finding a data-type issue when making the comparisons. If you want the term to show up as "Active" where term dates are blank for visualization reasons, that may be okay. But I would establish a new calculated column that determines if a term date is blank and replaces it with a date type far into the future so that dates can be compared among dates—something like:

```<code>Term Date Blank Fix =
IF(
    ISBLANK( INPUT_TECH[Term_Date] ),
    // The third argument below could be replaced with a hard year, ex. 2099
    DATE( 12, 31, YEAR( TODAY() ) + 10 ),
    INPUT_TECH[Term_Date]
)
</code>```

Then you could use the above column to make your comparisons in your measures. Keep in mind that if you are using a date table with AUTOCALENDAR() that making a date with the year 2099 may wildly expand your date table.

ContentLicense: CC BY-SA 4.0

Title: DAX Doesnt Support Comparison

Body:
I have a table of Employees. The Table has both current and budgeted employees. Each employees has a salary, start date and if applicable a term date associated with them.

I am attempting for project the salary spend for each month for the next year based on the following rules:

Hire_Date <= Projected_Month

Term_Date > Projected_Month

Measure:

CALCULATE(sum(INPUT_TECH[Salary_USD]),filter(INPUT_TECH,INPUT_TECH[Hire_Date]<=MEASURE_SWB_SPEND[MEASURE_SWB_SPEND_DATE]&&INPUT_TECH[Term_Date]>MEASURE_SWB_SPEND[MEASURE_SWB_SPEND_DATE]))

The issue here is that if ther is no Term_date, the cell will be blank, and if the cell is blank, the term_date will always be less than the current projected month and therefore the answer will always be 0.

I attempted to fix this by changing the format of the termdate to always either have the number 100,000 formated to read "ACTIVE" or the date they were actually terminated
Format: [=100000]"ACTIVE";[<>100000]mm/dd/yyyy

However, I still receive the following error:

DAX comparison operations do not support comparing values of type Text with values of type Date. Consider using the VALUE or FORMAT function to convert one of the values.

Body:
I would suggest not formatting the term date to the string "Active" and then using it for comparisons in your measures. This is why you may be getting that specific error. DAX is finding a data-type issue when making the comparisons. If you want the term to show up as "Active" where term dates are blank for visualization reasons, that may be okay. But I would establish a new calculated column that determines if a term date is blank and replaces it with a date type far into the future so that dates can be compared among dates—something like:

Term Date Blank Fix =
IF(
    ISBLANK( INPUT_TECH[Term_Date] ),
    // The third argument below could be replaced with a hard year, ex. 2099
    DATE( 12, 31, YEAR( TODAY() ) + 10 ),
    INPUT_TECH[Term_Date]
)

Then you could use the above column to make your comparisons in your measures. Keep in mind that if you are using a date table with AUTOCALENDAR() that making a date with the year 2099 may wildly expand your date table.


问:
Selenium get only child elements from current parent
I'm trying to get data from an HTML like this:

...

...

 ...

```
<p>The goal is to get the <code><li></code> values from every <code><h4></code>. To get this I've tried something like this:</p>
<pre class="lang-py prettyprint-override"><code>divs = driver.find_elements_by_xpath("//div//h4[starts-with(@id,'id_')]")
for h4 in divs:
    title = h4.text
    # Get <li> from each div
    for value in h4._parent.find_elements_by_tag_name('li'): #<-- It gives me all <li> in the page
        # TODO ...
</code>```

Here I'm trying to get all
 tags and then go to the parent (the
) and find the
 tags existing only in that parent. But I retrieve all
 tags.

I've searched over the internet and I've found a couple of question in StackOverflow like Get child element using xpath selenium python or selenium find child's child elements where it says to set the context, so I've tried this:

for value in h4._parent.find_elements_by_xpath('.//li'):
                                                 ^
```

But it gives me the same numbers of elements.

So, I'm misunderstanding something?

Thanks in advance.

答:
Arendeep question is ok and it worked for me, but also I've noticed the problem I was having.

The element _parent seems to be the web page, not the parent element. And this is why the method find_element was getting all
 tags from the page.

I can use accepted answer or also:

parent = h4.find_element_by_xpath('..')
for value in parent.find_elements_by_tag_name('li'):
    # TODO
```

Where the xpath ('..') return the parent element.

This way gives me only child from the current element (maybe is an answer more accurate) but accepted answer also works on my scenario where I want all
 tags dependant from the
.

By the way I haven't found docs about _parent.

Body:
I'm trying to get data from an HTML like this:

...

...

 ...

The goal is to get the
 values from every
. To get this I've tried something like this:

divs = driver.find_elements_by_xpath("//div//h4[starts-with(@id,'id_')]")
for h4 in divs:
    title = h4.text
    # Get
 from each div
    for value in h4._parent.find_elements_by_tag_name('li'): #<-- It gives me all
 in the page
        # TODO ...

Here I'm trying to get all
 tags and then go to the parent (the
) and find the
 tags existing only in that parent. But I retrieve all
 tags.

I've searched over the internet and I've found a couple of question in StackOverflow like Get child element using xpath selenium python or selenium find child's child elements where it says to set the context, so I've tried this:

for value in h4._parent.find_elements_by_xpath('.//li'):
                                                 ^

But it gives me the same numbers of elements.

So, I'm misunderstanding something?

Thanks in advance.

Body:
Arendeep question is ok and it worked for me, but also I've noticed the problem I was having.

The element _parent seems to be the web page, not the parent element. And this is why the method find_element was getting all <li> tags from the page.

I can use accepted answer or also:

parent = h4.find_element_by_xpath('..')
for value in parent.find_elements_by_tag_name('li'):
    # TODO

Where the xpath ('..') return the parent element.

This way gives me only child from the current element (maybe is an answer more accurate) but accepted answer also works on my scenario where I want all <li> tags dependant from the <h4>.

By the way I haven't found docs about _parent.


问:
Trying to fix error on Google Sheets to Docs data merge
How can I fix this error?

The code was working well and then I added some more code for more functionality but now I can't get past this error.

Error: Too many changes applied before saving document. Please save changes in smaller batches using Document.saveAndClose(), then reopen the document with Document.openById().

Here is my code

```<code>function myFunction() {
  var docTemplateID = "1g87Ak-ms8Ctv1B4zAquGaBn55shBKFZi5VUoP0Fgfvg";
  var docFinalID = "19K9N2uuBV312FuW0dLQv0BD8wBZYvtJmJHsjbSlqgCc";
  var wsID = "12sS_0rZn5_OzOigB75gSkSR1i7NkW5bMqY99onIi3qY";

  var docTemplate = DocumentApp.openById(docTemplateID);
  var docFinal = DocumentApp.openById(docFinalID);
  var ws = SpreadsheetApp.openById(wsID).getSheetByName("SCRAPED22PROBATE7");

  var data = ws.getRange(2,1,3,4,5,6,7,ws.getLastRow()-1,7).getValues();

  var templateParagraphs = docTemplate.getBody().getParagraphs();

  docFinal.getBody().clear();

  data.forEach(function(r){
    createMailMerge(r[1],r[0],r[2],r[3],r[4],r[5],r[6],templateParagraphs,docFinal);
  });

}

function createMailMerge(first,decdname,last,address,city,state,zip,templateParagraphs,docFinal){
  templateParagraphs.forEach(function(p){
    var elType = p.getType();

    if(elType == "PARAGRAPH"){
    docFinal.getBody().appendParagraph(
      p
      .copy()
      .replaceText("{PRFirstName}",first)
      .replaceText("{DecdNamePulled}",decdname)
      .replaceText("{PRFirstMail}",first)
      .replaceText("{PRLastMail}",last)
      .replaceText("{PRAddressMail}",address)
      .replaceText("{PRCityMail}",city)
      .replaceText("{PRStateMail}",state)
      .replaceText("{PRZipMail}",zip)
    );
     docFinal.saveAndClose()
  } else if(elType == "LIST_ITEM"){
    docFinal.getBody().appendListItem(
      p
      .copy()
      .replaceText("{PRFirstName}",first)
      .replaceText("{DecdNamePulled}",decdname)
      .replaceText("{PRFirstMail}",first)
      .replaceText("{PRLastMail}",last)
      .replaceText("{PRAddressMail}",address)
      .replaceText("{PRCityMail}",city)
      .replaceText("{PRStateMail}",state)
      .replaceText("{PRZipMail}",zip)
    ).setGlyphType(DocumentApp.GlyphType.BULLET);
  }

  });

  docFinal.getBody().appendPageBreak();
}
</code>```

答:
Given the error I'd try to open and close the final doc inside the function createMailMerge():

```<code>function createMailMerge(first,decdname,last,address,city,state,zip,templateParagraphs,docFinal) {

  var docFinal = DocumentApp.openById('19K9N2uuBV312FuW0dLQv0BD8wBZYvtJmJHsjbSlqgCc');

  // . . .
  // the rest code of the function
  // . . .

  docFinal.getBody().appendPageBreak();

  docFinal.saveAndClose();
}
</code>```

Body:
How can I fix this error?

The code was working well and then I added some more code for more functionality but now I can't get past this error.

Error: Too many changes applied before saving document. Please save changes in smaller batches using Document.saveAndClose(), then reopen the document with Document.openById().

Here is my code

function myFunction() {
  var docTemplateID = "1g87Ak-ms8Ctv1B4zAquGaBn55shBKFZi5VUoP0Fgfvg";
  var docFinalID = "19K9N2uuBV312FuW0dLQv0BD8wBZYvtJmJHsjbSlqgCc";
  var wsID = "12sS_0rZn5_OzOigB75gSkSR1i7NkW5bMqY99onIi3qY";

  var docTemplate = DocumentApp.openById(docTemplateID);
  var docFinal = DocumentApp.openById(docFinalID);
  var ws = SpreadsheetApp.openById(wsID).getSheetByName("SCRAPED22PROBATE7");

  var data = ws.getRange(2,1,3,4,5,6,7,ws.getLastRow()-1,7).getValues();

  var templateParagraphs = docTemplate.getBody().getParagraphs();

  docFinal.getBody().clear();

  data.forEach(function(r){
    createMailMerge(r[1],r[0],r[2],r[3],r[4],r[5],r[6],templateParagraphs,docFinal);
  });

}

function createMailMerge(first,decdname,last,address,city,state,zip,templateParagraphs,docFinal){
  templateParagraphs.forEach(function(p){
    var elType = p.getType();

    if(elType == "PARAGRAPH"){
    docFinal.getBody().appendParagraph(
      p
      .copy()
      .replaceText("{PRFirstName}",first)
      .replaceText("{DecdNamePulled}",decdname)
      .replaceText("{PRFirstMail}",first)
      .replaceText("{PRLastMail}",last)
      .replaceText("{PRAddressMail}",address)
      .replaceText("{PRCityMail}",city)
      .replaceText("{PRStateMail}",state)
      .replaceText("{PRZipMail}",zip)
    );
     docFinal.saveAndClose()
  } else if(elType == "LIST_ITEM"){
    docFinal.getBody().appendListItem(
      p
      .copy()
      .replaceText("{PRFirstName}",first)
      .replaceText("{DecdNamePulled}",decdname)
      .replaceText("{PRFirstMail}",first)
      .replaceText("{PRLastMail}",last)
      .replaceText("{PRAddressMail}",address)
      .replaceText("{PRCityMail}",city)
      .replaceText("{PRStateMail}",state)
      .replaceText("{PRZipMail}",zip)
    ).setGlyphType(DocumentApp.GlyphType.BULLET);
  }

  });

  docFinal.getBody().appendPageBreak();
}

Body:
Given the error I'd try to open and close the final doc inside the function createMailMerge():

function createMailMerge(first,decdname,last,address,city,state,zip,templateParagraphs,docFinal) {

  var docFinal = DocumentApp.openById('19K9N2uuBV312FuW0dLQv0BD8wBZYvtJmJHsjbSlqgCc');

  // . . .
  // the rest code of the function
  // . . .

  docFinal.getBody().appendPageBreak();

  docFinal.saveAndClose();
}


问:
Firebase Realtime Database Timestamp
I'm trying to include a timestamp as I add messages to the Firebase Realtime Database. I have found many similar questions posted, but none of the proposed solutions are working. I'm wondering if I am doing something wrong before I attempt to add the timestamp, maybe my config or something.

Here is my configuration:

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getDatabase, ref, push, set, onValue, query, orderByChild } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-database.js";

const firebaseConfig = {
    ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
```
<p>And here is my code when I try to add a message to my <code>messages</code> collection:</p>
<pre class="lang-js prettyprint-override"><code>const messageListRef = ref(database, 'messages');
const newMessageRef = push(messageListRef);

set(newMessageRef, {
    'name': name.value,
    'message': message.value,
    'createdAt': firebase.database.ServerValue.TIMESTAMP
});
</code>```

The error I'm receiving it:

```<code>index.js:31 Uncaught ReferenceError: firebase is not defined
at HTMLButtonElement.<anonymous>
</code>```

I have also tried:

app.database.ServerValue.TIMESTAMP

database.ServerValue.TIMESTAMP

And many others that I can't remember.

Any help would be very much appreciated.

答:
In Firebase v9+, you need to use serverTimestamp():

import { getDatabase, ref, push, set, onValue, query, orderByChild, serverTimestamp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-database.js";

/* ... */

set(newMessageRef, {
    'name': name.value,
    'message': message.value,
    'createdAt': serverTimestamp()
});
```

Title: Firebase Realtime Database Timestamp

Body:
I'm trying to include a timestamp as I add messages to the Firebase Realtime Database. I have found many similar questions posted, but none of the proposed solutions are working. I'm wondering if I am doing something wrong before I attempt to add the timestamp, maybe my config or something.

Here is my configuration:

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getDatabase, ref, push, set, onValue, query, orderByChild } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-database.js";

const firebaseConfig = {
    ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);

And here is my code when I try to add a message to my messages collection:

const messageListRef = ref(database, 'messages');
const newMessageRef = push(messageListRef);

set(newMessageRef, {
    'name': name.value,
    'message': message.value,
    'createdAt': firebase.database.ServerValue.TIMESTAMP
});

The error I'm receiving it:

index.js:31 Uncaught ReferenceError: firebase is not defined
at HTMLButtonElement.<anonymous>

I have also tried:

app.database.ServerValue.TIMESTAMP

database.ServerValue.TIMESTAMP

And many others that I can't remember.

Any help would be very much appreciated.


问:
Can't use Selenium to find elements. Try to avoid deprecated commands warning, got result only one element. (on Colab)
As my title said. To avoid deprecated warning of Selenium.I try to use the new format as I found.
and somehow result return only 1 element. How can I fix it to return elements?
FYI I scraping website. I'm working on Colab so I can share with my workmates easier.

Here my code

```<code>#!pip install selenium
#!pip install IPython
#!pip install pandas
#!apt-get update
#!apt install chromium-chromedriver

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)

import pandas as pd
from IPython.display import display
from selenium.webdriver.common.by import By
website = 'https://www.bitkub.com/fee/cryptocurrency'
driver.get(website)

#pull_data
coins = driver.find_elements(By.TAG_NAME,'tr')
</code>```

checking what element it contains (which somehow got only 1)

```<code>print(coins)
[<selenium.webdriver.remote.webelement.WebElement (session="091bac0ea46529043f4d84786ebc705f", element="76396e66-6516-4dd0-9d85-bc66bfad4676")>]

</code>```

答:
Ideally coins should have been a list of elements.

However, to extract the name of the coins you need to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>driver.get('https://www.bitkub.com/fee/cryptocurrency')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "tbody tr td:nth-child(2) span")))])
</code>```

Using XPATH:

```<code>driver.get('https://www.bitkub.com/fee/cryptocurrency')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//tbody//tr//following::td[2]//span")))])
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
As my title said. To avoid deprecated warning of Selenium.I try to use the new format as I found.
and somehow result return only 1 element. How can I fix it to return elements?
FYI I scraping website. I'm working on Colab so I can share with my workmates easier.

Here my code

#!pip install selenium
#!pip install IPython
#!pip install pandas
#!apt-get update
#!apt install chromium-chromedriver

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)

import pandas as pd
from IPython.display import display
from selenium.webdriver.common.by import By
website = 'https://www.bitkub.com/fee/cryptocurrency'
driver.get(website)

#pull_data
coins = driver.find_elements(By.TAG_NAME,'tr')

checking what element it contains (which somehow got only 1)

print(coins)
[<selenium.webdriver.remote.webelement.WebElement (session="091bac0ea46529043f4d84786ebc705f", element="76396e66-6516-4dd0-9d85-bc66bfad4676")>]

Body:
Ideally coins should have been a list of elements.

However, to extract the name of the coins you need to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

driver.get('https://www.bitkub.com/fee/cryptocurrency')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "tbody tr td:nth-child(2) span")))])

Using XPATH:

driver.get('https://www.bitkub.com/fee/cryptocurrency')
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//tbody//tr//following::td[2]//span")))])

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
How can you disable Gutter Indicators in VS Code?
In VS Code, if there's version control in a folder you're working in, it will try and indicate what lines are new and what lines are changed with little color patches in the "gutter" section. Actually, both on the left side near the line numbers, and also on the right side in the scroll bar. Is there a way to turn that off?</p>

答:
If you arrived here, wanting to turn this feature off because you kept clicking on the SCM gutter bars by accident and accidentally opening the diff when you don't want to, this may be of value to you.

As an alternative to turning this useful feature off, consider setting the "SCM: Diff Decorations Gutter Action" instead.  This setting controls what happens when you click on the gutter bars; setting to "none" prevents them from being clickable.  This allows you to keep the visual information they provide while getting rid of the unwanted behavior.

```<code>    "scm.diffDecorationsGutterAction": "none", // suppress opening diffs in margin ("gutters")
</code>```

Body:
If you arrived here, wanting to turn this feature off because you kept clicking on the SCM gutter bars by accident and accidentally opening the diff when you don't want to, this may be of value to you.

As an alternative to turning this useful feature off, consider setting the "SCM: Diff Decorations Gutter Action" instead.  This setting controls what happens when you click on the gutter bars; setting to "none" prevents them from being clickable.  This allows you to keep the visual information they provide while getting rid of the unwanted behavior.

    "scm.diffDecorationsGutterAction": "none", // suppress opening diffs in margin ("gutters")


问:
How to trim the extra spaces or line breaks in the cognos reporting?
I have a data item where its values are  populating with some space after it.

For example the data item is State. In output the result is like ORISSA  . But after Orissa u have some space. How can I remove that space in cogons reporting for a specific data item?

答: Trim or some similar function, possibly one which is native to your DB vendor, might be helpful I think.


问:
Add legends to a Treemap with ggplot only when space inside blocks is too small
I'm working with ggplot and treemapify to generate a treemap.

The problem is that some blocks are too small so i can't put text inside of them. I've been trying to use scale_fill_manual in order to generate some legends outside the graph by breaks argument but it comes with two problems. If I only specify the labels that I want, the other ones turn green and I can't change their fill collor. On the other hand, when I use all the labels it shows them all.

How can I choose which legends I want to show in the graph?

This is the resulting treemap when I try to add the legends with all labels

This is the resulting treemap when I try to add the legends with the labels that I want

This is the code I'm currently working on:

```<code>ggplot(TM_df, aes(label = Labels, area = Values, fill = Labels)) +
  geom_treemap() +
  geom_treemap_text(fontface = "bold", colour = "white", place = "centre") +
  scale_fill_manual("", breaks = TM_df$Labels,
                    values = colores, drop = F) +
  theme(
    legend.title = element_blank(),
    legend.position = "bottom"
  )
</code>```

And this is my dataset:

```<code>TM_df <- data.frame( Labels = c("Servicios Personales\n10,643 mdp (-5.1%)",
"Materiales y Suministros\n1,597 mdp (+16.1%)", "Servicios Generales\n2,346 mdp (-25.0%)",
"Transferencias, Asignaciones,\nSubsidios y Otras Ayudas\n44,212 mdp (+8.8%)",
"Bienes Muebles, Inmuebles e Intangibles\n112 mdp (-55.8%)",
"Inversion Publica\n1,336 mdp (-29.3%)",
"Inversiones Financieras\ny Otras Provisiones\n48 mdp (-35.2%)",
"Deuda Publica\n8,977 mdp (+25.7%)"),
Values = c(10643.28124, 1596.93410, 2346.43756, 44211.92169, 112.46303,
1335.76290, 48.30434, 12080.91506, 8976.59709))
</code>```

答:
One option to prevent the fill colors to be removed when setting the breaks would be to make use of a named vector which assigns colors to category names:

library(treemapify)
library(ggplot2)

colores <- scales::brewer_pal(palette = "Dark2")(8)
ggplot(TM_df, aes(label = Labels, area = Values, fill = Labels)) +
  geom_treemap() +
  geom_treemap_text(fontface = "bold", colour = "white", place = "centre") +
  scale_fill_manual("",
    breaks = TM_df$Labels[c(5, 7)],
    values = setNames(colores, TM_df$Labels)
  ) +
  theme(
    legend.title = element_blank(),
    legend.position = "bottom"
  )
```

Body:
I'm working with ggplot and treemapify to generate a treemap.

The problem is that some blocks are too small so i can't put text inside of them. I've been trying to use scale_fill_manual in order to generate some legends outside the graph by breaks argument but it comes with two problems. If I only specify the labels that I want, the other ones turn green and I can't change their fill collor. On the other hand, when I use all the labels it shows them all.

How can I choose which legends I want to show in the graph?

This is the resulting treemap when I try to add the legends with all labels

This is the resulting treemap when I try to add the legends with the labels that I want

This is the code I'm currently working on:

ggplot(TM_df, aes(label = Labels, area = Values, fill = Labels)) +
  geom_treemap() +
  geom_treemap_text(fontface = "bold", colour = "white", place = "centre") +
  scale_fill_manual("", breaks = TM_df$Labels,
                    values = colores, drop = F) +
  theme(
    legend.title = element_blank(),
    legend.position = "bottom"
  )

And this is my dataset:

TM_df <- data.frame( Labels = c("Servicios Personales\n10,643 mdp (-5.1%)",
"Materiales y Suministros\n1,597 mdp (+16.1%)", "Servicios Generales\n2,346 mdp (-25.0%)",
"Transferencias, Asignaciones,\nSubsidios y Otras Ayudas\n44,212 mdp (+8.8%)",
"Bienes Muebles, Inmuebles e Intangibles\n112 mdp (-55.8%)",
"Inversion Publica\n1,336 mdp (-29.3%)",
"Inversiones Financieras\ny Otras Provisiones\n48 mdp (-35.2%)",
"Deuda Publica\n8,977 mdp (+25.7%)"),
Values = c(10643.28124, 1596.93410, 2346.43756, 44211.92169, 112.46303,
1335.76290, 48.30434, 12080.91506, 8976.59709))


问:
access linux system from windows using teamviewer?
i am trying to get the remote access from windows system to linux system using teamviewer but when the connection is established the windows system sees the black screen. so anyone can help me how to establish the fair connection.</p>

答: I had the same problem - for me with two solutions. On some systems, it just took about 30sec for the screen to build up (in that case, just be patient) and in the other case, there was a driver problem. Try to change the driver to the default ubuntu one and deactivate the proprietary hardware driver in that case.</p>


问:
composer.json script, returns 'event returned with error code 2', why?
I was studying composer, and when creating this script, it returns 'event returned with error code 2'. While the script is executed properly, the parsing is correct and the result is the expected, I still get a delay and an error code regarding the script. What could be causing it and how should I fix it?</p>
```<code> //src

 <?php

    echo 'hello world';

 ?>

</code>```
```<code>//composer.json
    "require-dev": {
        "phpunit/phpunit": "^9.5",
        "squizlabs/php_codesniffer": "^3.6",
        "phan/phan": "^5.3"
    },
    "scripts": {
        "cs" : "phpcs --standard=PSR12 src/"
    },

</code>```
```<code>//running

PS D:\xamp\htdocs\fonts\ambiente\buscador-cursos-alura> composer cs
> phpcs --standard=PSR12 src/

FILE: ...:\xamp\htdocs\fonts\ambiente\buscador-cursos-alura\src\teste.php
----------------------------------------------------------------------
FOUND 3 ERRORS AFFECTING 2 LINES
----------------------------------------------------------------------
 1 | ERROR | [x] End of line character is invalid; expected "\n" but
   |       |     found "\r\n"
 5 | ERROR | [x] Expected 1 newline at end of file; 0 found
 5 | ERROR | [x] A closing tag is not permitted at the end of a PHP
   |       |     file
----------------------------------------------------------------------
PHPCBF CAN FIX THE 3 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Time: 102ms; Memory: 8MB

Script phpcs --standard=PSR12 src/ handling the cs event returned with error code 2
</code>```

答:
First Warning

End of line character is invalid; expected "\n" but found "\r\n"

Your line endings need to be LF and not CRLF, here's an article which explains the difference. If you're using VSCode then you can change the line ending in the bottom right where it uses CRLF by default. If you're not using VSCode then you will need to Google how to change the line endings for your IDE.

Second Warning

Expected 1 newline at end of file; 0 found

PSR12 coding standards require an empty line at the end of your PHP files.

Third Warning

A closing tag is not permitted at the end of a PHP file

PSR12 coding standards state that closing PHP tags at the end of the file should be omitted.

<?php
    echo 'hello world';

```

Body:
I was studying composer, and when creating this script, it returns 'event returned with error code 2'. While the script is executed properly, the parsing is correct and the result is the expected, I still get a delay and an error code regarding the script. What could be causing it and how should I fix it?

 //src

 <?php

    echo 'hello world';

 ?>

//composer.json
    "require-dev": {
        "phpunit/phpunit": "^9.5",
        "squizlabs/php_codesniffer": "^3.6",
        "phan/phan": "^5.3"
    },
    "scripts": {
        "cs" : "phpcs --standard=PSR12 src/"
    },

//running

PS D:\xamp\htdocs\fonts\ambiente\buscador-cursos-alura> composer cs
> phpcs --standard=PSR12 src/

FILE: ...:\xamp\htdocs\fonts\ambiente\buscador-cursos-alura\src\teste.php
----------------------------------------------------------------------
FOUND 3 ERRORS AFFECTING 2 LINES
----------------------------------------------------------------------
 1 | ERROR | [x] End of line character is invalid; expected "\n" but
   |       |     found "\r\n"
 5 | ERROR | [x] Expected 1 newline at end of file; 0 found
 5 | ERROR | [x] A closing tag is not permitted at the end of a PHP
   |       |     file
----------------------------------------------------------------------
PHPCBF CAN FIX THE 3 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Time: 102ms; Memory: 8MB

Script phpcs --standard=PSR12 src/ handling the cs event returned with error code 2


问:
Fit a straight line ignoring data points having ceiling effect
I have a data like below and I would like to fit a straight line (like a Black line) ignoring the points following ceiling effect. Then I would like to predict Y values of these points using the slope and find the expected difference due to ceiling effect.

I tried using following code from other stackoverflow question but it does not do a good job at ignoring points with ceiling effect.

```<code>from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit
</code>```

Please feel free to provide any ideas or suggestions. Thank you.

答:
One option is to write a loop that ensures excludes data until the fit is good:

from scipy.stats import linregress

fit = linregress(x, y)
i=0
while fit.rvalue < 0.999:
     fit = linregress(x[:-i], y[:-i])
     i += 1
```

Note that this assumes your data is ordered and I prefer linregress for fitting lines as it gives an easy-to-access rvalue.

Body:
I have a data like below and I would like to fit a straight line (like a Black line) ignoring the points following ceiling effect. Then I would like to predict Y values of these points using the slope and find the expected difference due to ceiling effect.

I tried using following code from other stackoverflow question but it does not do a good job at ignoring points with ceiling effect.

from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit

Please feel free to provide any ideas or suggestions. Thank you.

Body:
One option is to write a loop that ensures excludes data until the fit is good:

from scipy.stats import linregress

fit = linregress(x, y)
i=0
while fit.rvalue < 0.999:
     fit = linregress(x[:-i], y[:-i])
     i += 1

Note that this assumes your data is ordered and I prefer linregress for fitting lines as it gives an easy-to-access rvalue.


问:
int issue in g++/mysql/redhat
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

```
int some_int;
printf("%i",some_int);
```

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

```
int some_int;
printf("%s",some_int);
```

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

```
int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);
```

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

答: Variable are not automatically initialized in c.</p>

OwnerDisplayName: hcmk

LastEditorDisplayName: FreeMemory

ContentLicense: CC BY-SA 2.5

Title: int issue in g++/mysql/redhat

Body:
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

int some_int;
printf("%i",some_int);

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

int some_int;
printf("%s",some_int);

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

OwnerDisplayName: MarkusQ


问:
Remove duplicates from a tuple
I tried to extract keywords from a text. By using "en_core_sci_lg" model, I got a tuple type of phrases/words with some duplicates which I tried to remove from it. I tried deduplicate function for list and tuple, I only got fail. Can anyone help? I really appreciate it.

```<code>text = """spaCy is an open-source software library for advanced natural language processing,
written in the programming languages Python and Cython. The MIT library is published under the MIT license and its main developers are Matthew Honnibal and Ines Honnibal, the founders of the software company Explosion."""
</code>```

one sets of codes I have tried:

```<code>import spacy
nlp = spacy.load("en_core_sci_lg")

doc = nlp(text)
my_tuple = list(set(doc.ents))
print('original tuple', doc.ents, len(doc.ents))
print('after set function', my_tuple, len(my_tuple))
</code>```

the output:

```<code>original tuple: (spaCy, open-source software library, programming languages, Python, Cython, MIT, library, published, MIT, license, developers, Matthew Honnibal, Ines, Honnibal, founders, software company Explosion) 16

after set function: [Honnibal, MIT, Ines, software company Explosion, founders, programming languages, library, Matthew Honnibal, license, Cython, Python, developers, MIT, published, open-source software library, spaCy] 16
</code>```

the desired output is(there should be one MIT, and the name Ines Honnibal should be together):

```<code>[Ines Honnibal, MIT, software company Explosion, founders, programming languages, library, Matthew Honnibal, license, Cython, Python, developers, published, open-source software library, spaCy]
</code>```

答:
doc.ents is not a list of strings.  It is a list of Span objects. When you print one, it prints its contents, but they are indeed individual objects, which is why set doesn't see they are duplicates.  The clue to that is there are no quote marks in your print statement.  If those were strings, you'd see quotation marks.

You should try using doc.words instead of doc.ents.  If that doesn't work for you, for some reason, you can do:

```<code>my_tuple = list(set(e.text for e in doc.ents))
</code>```

Title: Remove duplicates from a tuple

Body:
I tried to extract keywords from a text. By using "en_core_sci_lg" model, I got a tuple type of phrases/words with some duplicates which I tried to remove from it. I tried deduplicate function for list and tuple, I only got fail. Can anyone help? I really appreciate it.

text = """spaCy is an open-source software library for advanced natural language processing,
written in the programming languages Python and Cython. The MIT library is published under the MIT license and its main developers are Matthew Honnibal and Ines Honnibal, the founders of the software company Explosion."""

one sets of codes I have tried:

import spacy
nlp = spacy.load("en_core_sci_lg")

doc = nlp(text)
my_tuple = list(set(doc.ents))
print('original tuple', doc.ents, len(doc.ents))
print('after set function', my_tuple, len(my_tuple))

the output:

original tuple: (spaCy, open-source software library, programming languages, Python, Cython, MIT, library, published, MIT, license, developers, Matthew Honnibal, Ines, Honnibal, founders, software company Explosion) 16

after set function: [Honnibal, MIT, Ines, software company Explosion, founders, programming languages, library, Matthew Honnibal, license, Cython, Python, developers, MIT, published, open-source software library, spaCy] 16

the desired output is(there should be one MIT, and the name Ines Honnibal should be together):

[Ines Honnibal, MIT, software company Explosion, founders, programming languages, library, Matthew Honnibal, license, Cython, Python, developers, published, open-source software library, spaCy]

Body:
doc.ents is not a list of strings.  It is a list of Span objects. When you print one, it prints its contents, but they are indeed individual objects, which is why set doesn't see they are duplicates.  The clue to that is there are no quote marks in your print statement.  If those were strings, you'd see quotation marks.

You should try using doc.words instead of doc.ents.  If that doesn't work for you, for some reason, you can do:

my_tuple = list(set(e.text for e in doc.ents))


问:
OpenCL trying to use semaphore crashes drivers

 While writing simple OpenCL kernel I tried to use semaphores and it crushed my GPU Drivers (AMD 12.10). After checking out examples I found out, that crash happens only when local work size is not equal to 1.
This code taken from example:

```<code>    #pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics : enable
    #pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable
    #pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable
    #pragma OPENCL EXTENSION cl_khr_local_int32_extended_atomics : enable

    void GetSemaphor(__global int * semaphor)
    {
      int occupied = atom_xchg(semaphor, 1);
      while(occupied > 0)
      {
          occupied = atom_xchg(semaphor, 1);
      }
    }

    void ReleaseSemaphor(__global int * semaphor)
    {
       int prevVal = atom_xchg(semaphor, 0);
    }

    __kernel void kernelNoAtomInc(__global int * num,
                __global int * semaphor)
    {
      int i = get_global_id(0);
      GetSemaphor(&semaphor[0]);
      {
        num[0]++;
      }
      ReleaseSemaphor(&semaphor[0]);
    }
</code>```

In example author uses

```<code>CQ.Execute(kernelNoAtomInc, null, new long[1] { N }, new long[1] { 1 }, null);
</code>```

Where N = global_work_size and local_work_size = 1

Now if I change 1 to null or 2 or 4 or any other number i tried - AMD drivers will crush.

```<code>CQ.Execute(kernelNoAtomInc, null, new long[1] { N }, new long[1] { 2 }, null);
</code>```

I do not have other PC to test on it at the moment. However it seems strange that author deliberately left local_group_size = 1, that's why I think I missing something here. Can someone please explain this to me? Also, as far as I understand, leaving local_group_size at 1 will affect performance greatly or it won't?
Thanks.

Host: Win8 x64, HD6870

答:
Your problem is not reproducible and I can furthermore not find your source from the link, but here are a few ideas on why it could crash, which should be helpful (9 years in the past).

It propably crashes, because...

... the driver thinks you want the local version of that atom_xchg() function to be executed, when instead you want the global one.

... your loop slows down execution of that kernel so drastically on an old machine, that an internal limit of execution time got passed, causing the driver to terminate the kernel.

What I can suggest for a possible fix:

do not activate the local version of the atom function in your kernel

Try running it on CPU

There is no way to fix this, unless we could access your computer and debug on it.

You were also asking, why the author chose the local_group_size of one. This is because the global work size needs to be divisible by the local work size, such that the division results in a natural number. Dividing a natural number by one always results in a natural number, therefor this is perfect for experimenting. You are completely correct by saying that it will affect performance greatly. (Just maybe the maths didn't add up and it didn't crash, but not even start)

Different notes:

To make the incrementing be functionally correct, you should use an atom_inc() on your num buffer. I don't see how this could lead to a crash, but it definitely makes your program not work as intended

I would go and use the atomic functions from the 2.0 standard, since they already feature a semaphore-like functions: bool atomic_flag_test_and_set(volatile atomic_flag *object) and void atomic_flag_clear(volatile atomic_flag *object)

Body:
 While writing simple OpenCL kernel I tried to use semaphores and it crushed my GPU Drivers (AMD 12.10). After checking out examples I found out, that crash happens only when local work size is not equal to 1.
This code taken from example:

    #pragma OPENCL EXTENSION cl_khr_global_int32_base_atomics : enable
    #pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable
    #pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable
    #pragma OPENCL EXTENSION cl_khr_local_int32_extended_atomics : enable

    void GetSemaphor(__global int * semaphor)
    {
      int occupied = atom_xchg(semaphor, 1);
      while(occupied > 0)
      {
          occupied = atom_xchg(semaphor, 1);
      }
    }

    void ReleaseSemaphor(__global int * semaphor)
    {
       int prevVal = atom_xchg(semaphor, 0);
    }

    __kernel void kernelNoAtomInc(__global int * num,
                __global int * semaphor)
    {
      int i = get_global_id(0);
      GetSemaphor(&semaphor[0]);
      {
        num[0]++;
      }
      ReleaseSemaphor(&semaphor[0]);
    }

In example author uses

CQ.Execute(kernelNoAtomInc, null, new long[1] { N }, new long[1] { 1 }, null);

Where N = global_work_size and local_work_size = 1

Now if I change 1 to null or 2 or 4 or any other number i tried - AMD drivers will crush.

CQ.Execute(kernelNoAtomInc, null, new long[1] { N }, new long[1] { 2 }, null);

I do not have other PC to test on it at the moment. However it seems strange that author deliberately left local_group_size = 1, that's why I think I missing something here. Can someone please explain this to me? Also, as far as I understand, leaving local_group_size at 1 will affect performance greatly or it won't?
Thanks.

Host: Win8 x64, HD6870


问:
How can I backup nifi processes when restarting Kuberntes pod?
I have deployed Nifi on Kuberntes using cetic/helm-nifi helm chart. We are facing a problem, If nifi pod restarts we lost the all processes that we created. Is there any way to keep a backup of the process in nifi canvas.</p>

答:
Nifi keeps flow definitions in the /opt/nifi/nifi-current/conf/flow.xml.gz file in the docker image. It is strongly advised to have /conf folder persist .There are lots of kubernetes alternatives for this . check the official document

You can also find archives in the /conf folder for back-ups


问:
Returning the full object in response body using NET Core controller
What is the best way to return all details of complex objects in the body of a HTTP response?

I made some simple test classes:

```<code>public class Parent { }

public class Child : Parent
{
    public Child(string _name) { name = _name; }
    public string name { get; }
}
</code>```

I want to return a list as a response, which contains full detail about all the objects in it. My controller looks like this:

```<code>[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public List<Parent> Index()
    {
        Parent o1 = new Child("Alice");
        Parent o2 = new Child("Bob");
        return new List<Parent>() { o1, o2 };
    }
}
</code>```

This leads to an output of [{},{}]

If I replace the definitions to work with the List<Child> return type, it is able to recognise the details as
[{"name":"Alice"},{"name":"Bob"}], however I may have different child types in the list, so this would not work.

What function does NET Core use to convert the object into the JSON response body? Is the best way to tackle this problem to convert it to JSON myself and output the resulting string?

答:
The ControllerBase.Ok method will return JSON formatted data by default, so you can just call:

```<code>return Ok(new List<Parent>() { o1, o2 });
</code>```

Body:
What is the best way to return all details of complex objects in the body of a HTTP response?

I made some simple test classes:

public class Parent { }

public class Child : Parent
{
    public Child(string _name) { name = _name; }
    public string name { get; }
}

I want to return a list as a response, which contains full detail about all the objects in it. My controller looks like this:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public List<Parent> Index()
    {
        Parent o1 = new Child("Alice");
        Parent o2 = new Child("Bob");
        return new List<Parent>() { o1, o2 };
    }
}

This leads to an output of [{},{}]

If I replace the definitions to work with the List<Child> return type, it is able to recognise the details as
[{"name":"Alice"},{"name":"Bob"}], however I may have different child types in the list, so this would not work.

What function does NET Core use to convert the object into the JSON response body? Is the best way to tackle this problem to convert it to JSON myself and output the resulting string?

Body:
The ControllerBase.Ok method will return JSON formatted data by default, so you can just call:

return Ok(new List<Parent>() { o1, o2 });


问:
How to solve localstorage exeeded the quota error in Reactjs
Regarding redux-localstorage-simple in React.js/Typescript, exceeded the quota error occured when trying to store a huge amount of data(It's actually an array of objects related to tilemap coordinate data).
I'm sure it is because the local storage limit for a certain host has been exceeded.

Reloading the page initializes the redux storage, so I had to use the redux-localstorage-simple library to avoid data loss.

In this case, which alternative should I use to avoid exceeded the quota error?

答:
Depends a bit on your application.

First off, did you check the filesize from the JSON payload?
Especially in the context of tilemaps you may have huge polygon shapes with lots of details which exceed megabytes of data fast.

Do check the size of the JSON.stringify output which your localstorage library may use under the hood.

If storage is in fact a limitation, you could either upgrade to IndexedDB (which has a higher quota) or try to store only relevant keys and recreate missing properties when rehydrating the store.

I had a similar problem when storing big chunks of data and ended up using redux-offline which provides an IndexedDB adapter.


问:
Using List Comprehension for a number sequence (1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1 .....) in Python
I'm doing exercise questions from A Practical Introduction to Python Programming by Brian Heinold (pg 83) and there was a simpler question:

Using a for loop, create the list below, which consists of ones separated by increasingly many
zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

```<code># Question 11
L = [1]
for i in range(11):
  if i == 0:
    L.append(1)
  else:
    for j in range(i):
      L.append(0)
    L.append(1)
print(L)
</code>```

Use a list comprehension to create the list below, which consists of ones separated by increasingly many zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

I'm having difficulty with converting it into one line using list comprehension. Best I could do was

```<code># Question 15
L = [[1, [0]*i] for i in range(11)]
print(L)
L = [j for row in L for j in row]
print(L)
</code>```

Which would print:

```<code>[[1, []], [1, [0]], [1, [0, 0]], [1, [0, 0, 0]], [1, [0, 0, 0, 0]], [1, [0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]
[1, [], 1, [0], 1, [0, 0], 1, [0, 0, 0], 1, [0, 0, 0, 0], 1, [0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
</code>```

Flattening the list any further would result in a TypeError: 'int' object is not iterable and I would have to add another 1 at the end of the list using a seperate command which I guess would be fine. To add the code for flattening the list kinda goes over my head.

This is a second attempt using if/else statements, that gives the produces the same output and gives the same TypeError for when I try to flatten it completely.

```<code>L = [1 if i%2 == 0 else [0]*(i//2) for i in range(22)]
L = [j for row in L for j in row]
print(L)
</code>```

I just want this as output:

```<code>[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
</code>```

Thanks!

答:
You can solve it like this:

L = [j for i in range(11) for j in [1, *([0]*i)]]
```
<p>or</p>
```L = [j for i in range(11) for j in [1, *(0 for k in range(i))]]
```
<p><strong>Edit</strong><br />
I missed that it should end with a one. Here's a solution that does that:</p>
<pre class="lang-py prettyprint-override"><code>L = [1, *(j for i in range(11) for j in [*(0 for k in range(i)), 1])]
</code>```

or with list comprehension instead of generators:

L = [1, *[j for i in range(11) for j in [*[0 for k in range(i)], 1]]]
```

Body:
I'm doing exercise questions from A Practical Introduction to Python Programming by Brian Heinold (pg 83) and there was a simpler question:

Using a for loop, create the list below, which consists of ones separated by increasingly many
zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

# Question 11
L = [1]
for i in range(11):
  if i == 0:
    L.append(1)
  else:
    for j in range(i):
      L.append(0)
    L.append(1)
print(L)

Use a list comprehension to create the list below, which consists of ones separated by increasingly many zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

I'm having difficulty with converting it into one line using list comprehension. Best I could do was

# Question 15
L = [[1, [0]*i] for i in range(11)]
print(L)
L = [j for row in L for j in row]
print(L)

Which would print:

[[1, []], [1, [0]], [1, [0, 0]], [1, [0, 0, 0]], [1, [0, 0, 0, 0]], [1, [0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]
[1, [], 1, [0], 1, [0, 0], 1, [0, 0, 0], 1, [0, 0, 0, 0], 1, [0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Flattening the list any further would result in a TypeError: 'int' object is not iterable and I would have to add another 1 at the end of the list using a seperate command which I guess would be fine. To add the code for flattening the list kinda goes over my head.

This is a second attempt using if/else statements, that gives the produces the same output and gives the same TypeError for when I try to flatten it completely.

L = [1 if i%2 == 0 else [0]*(i//2) for i in range(22)]
L = [j for row in L for j in row]
print(L)

I just want this as output:

[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

Thanks!

Body:
You can solve it like this:

L = [j for i in range(11) for j in [1, *([0]*i)]]

or

L = [j for i in range(11) for j in [1, *(0 for k in range(i))]]

Edit

I missed that it should end with a one. Here's a solution that does that:

L = [1, *(j for i in range(11) for j in [*(0 for k in range(i)), 1])]

or with list comprehension instead of generators:

L = [1, *[j for i in range(11) for j in [*[0 for k in range(i)], 1]]]


问:
R with dplyr rename, avoid error if column doesn't exist AND create new column with NAs
We are looking to rename columns in a dataframe in R, however the columns may be missing and this throws an error:

```<code>my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
my_df %>% dplyr::rename(aa = a, bb = b, cc = c)

Error: Can't rename columns that don't exist.
x Column `c` doesn't exist.
</code>```

our desired output is this, which creates a new column with NA values if the original column does not exist:

```<code>> my_df
  aa bb  c
1  1  4 NA
2  2  5 NA
3  3  6 NA
</code>```

答:
A possible solution:

library(tidyverse)

my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))

cols <- c(a = NA_real_, b = NA_real_, c = NA_real_)

my_df %>% add_column(!!!cols[!names(cols) %in% names(.)]) %>%
  rename(aa = a, bb = b, cc = c)

#>   aa bb cc
#> 1  1  4 NA
#> 2  2  5 NA
#> 3  3  6 NA
```

Body:
We are looking to rename columns in a dataframe in R, however the columns may be missing and this throws an error:

my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
my_df %>% dplyr::rename(aa = a, bb = b, cc = c)

Error: Can't rename columns that don't exist.
x Column `c` doesn't exist.

our desired output is this, which creates a new column with NA values if the original column does not exist:

> my_df
  aa bb  c
1  1  4 NA
2  2  5 NA
3  3  6 NA


问:
How to export an Asp.net Pi chart graph into MS Excel?
How to export an Asp.net Pi chart graph into MS Excel?

I am using Asp.net,C#

Thank in advance
Rashed

答: The easiest option would be to share the data source between the Asp.Net application and the Excel sheet.  Then on the data tab of Excel you could link to the same data source and base your graph on the same data.


问:
How to tell if a website is static or dynamic?
My prof said that dynamic pages get created by the computer, while static pages are created by the user.

Thank you so much!

答:
My prof said that dynamic pages get created by the computer, while static pages are created by the user.

Well, actually also static pages can be generated by the computer, since there are a lot of static sites generators out there. Take for example https://astro.build or https://gohugo.io

Would www.tagpro.gg  be static or dynamic?

You are right, it is dynamic, since you can see a login/sign-up feature on the page. That's nothing you can achieve with a 100% static site.


问:
Email Table Layout - Overlapping text
I am using this template: https://mailbakery.com/template-store/product/basic-free-html-email-template/ for an email newsletter. I am having an issue with overlapping text in the testimonial on mobile. I have to have the quotation image which isn't in the jsfiddle but use your imagination lol. I've tried adding white-space: normal, a fixed-width, and word-break, but nothing. The tables have border-collapse: border.

Here is the jsFiddle: https://jsfiddle.net/z5jybrda/

 /* Linked Styles */
      body {
        padding: 0 !important;
        margin: 0 !important;
        display: block !important;
        min-width: 100% !important;
        width: 100% !important;
        background: #ffffff;
        -webkit-text-size-adjust: none;
      }
      a {
        color: #0000ee;
        text-decoration: none;
      }
      p {
        padding: 0 !important;
        margin: 0 !important;
      }

      /* Mobile styles */
      @media only screen and (max-device-width: 480px),
        only screen and (max-width: 480px) {
        .table_wrapper {
          width: 95%;
        }

        .mobile-full-width {
          width: 100% !important;
        }

        .mobile-shell {
          width: 100% !important;
          min-width: 100% !important;
        }

        .text-header,
        .m-center {
          text-align: center !important;
        }

        .m-font-15 {
          font-size: 15px !important;
        }

        .center {
          margin: 0 auto !important;
        }
        .container {
          padding: 20px 10px !important;
        }

        .td {
          width: 100% !important;
          min-width: 100% !important;
        }

        .m-br-15 {
          height: 15px !important;
        }
        .p30-15 {
          padding: 30px 15px !important;
        }
        .p0-15-30 {
          padding: 0px 15px 30px 15px !important;
        }
        .p0-15 {
          padding: 0px 15px !important;
        }
        .pb-30 {
          padding-bottom: 30px !important;
        }
        .mpb30 {
          padding-bottom: 30px !important;
        }
        .mpb15 {
          padding-bottom: 15px !important;
        }

        .m-td,
        .m-hide {
          display: none !important;
          width: 0 !important;
          height: 0 !important;
          font-size: 0 !important;
          line-height: 0 !important;
          min-height: 0 !important;
        }

        .column,
        .column-dir,
        .column-top,
        .column-empty,
        .column-empty2,
        .column-dir-top {
          float: left !important;
          width: 100% !important;
          display: block !important;
        }

        .column-empty {
          padding-bottom: 30px !important;
        }
        .column-empty2 {
          padding-bottom: 10px !important;
        }

        .content-spacing {
          width: 15px !important;
        }
      }

      @media only screen and (max-width: 310px) {
        .button {
          width: 195px !important;
        }

        img.quote {
          height: 22px;
          width: auto;
        }
        td.quote {
          width: 50px !important;
        }
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <!-- WRAPPER -->
    <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#ffffff">
      <tr>
        <td align="center" valign="top">
          <table width="100%" border="0" cellspacing="0" cellpadding="0" style="background: #f4f5f6">
            <tr>
              <td align="center">
                <table width="650" border="0" cellspacing="0" cellpadding="0" class="mobile-shell">
                  <tr>
                    <td class="td" style="
                        width: 650px;
                        min-width: 650px;
                        font-size: 0pt;
                        line-height: 0pt;
                        padding: 0;
                        margin: 0;
                        font-weight: normal;
                      ">

                      <!-- SPACER -->
                      <table width="100%" border="0" cellpadding="0" cellspacing="0">
                        <tr>
                          <td width="100%" height="30"></td>
                        </tr>
                      </table>

                      <!-- TESTIMONIAL -->
                      <table width="100%" border="0" cellpadding="0" cellspacing="0" style="background: #877454;">
                        <tr>
                          <td height="20"></td>
                        </tr>
                        <tr>
                          <td>
                            <table cellpadding="0" cellspacing="0" border="0" align="center" width="100%">
                              <tr>
                                <td width="20"></td>
                                <td>
                                  <table cellpadding="0" cellspacing="0" border="0" align="center" width="100%">
                                    <tr>
                                      <td valign="top" width="70" class="quote">
                                        <div><img src="./Newsletters/Images/colon.png" width="50" height="34" alt="quotation" style="display: block;" border="0" class="quote" />
                                        </div>
                                      </td>
                                      <td>
                                        <table cellpadding="0" cellspacing="0" border="0" align="center" width="100%">
                                          <tr>
                                            <td height="10"></td>
                                          </tr>
                                          <tr>
                                            <td style="font-size: 18px; color:#ffffff; font-family: 'Open Sans',Arial, sans-serif; font-style: italic; line-height: 1.5; " class="m-font-15">Thank you for your excellent leadership and support over the last year. We all greatly appreciate your efforts to steer us all in the right direction.
                                            </td>
                                          </tr>
                                          <tr>
                                            <td height="20"></td>
                                          </tr>
                                          <tr>
                                            <td style="font-size: 16px; color:#ffffff; font-family: 'Open Sans',Arial, sans-serif; ">
                                              <p>
                                                - John Doe recognizing <span style="text-decoration: underline;">John Doe</span>
                                              </p>
                                            </td>
                                          </tr>
                                        </table>
                                      </td>
                                    </tr>
                                  </table>
                                <td width="30"></td>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>
                  <tr>
                    <td height="40"></td>
                  </tr>
                </table>
                <!-- END TESTIMONIAL -->

              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
    </td>
    </tr>
    </table>
  </body></code>```

I appreciate any help

答:
Well this is one of my favorite problems with HTML tables, what is happening to you is due to lack of space in the , if you change td like this:

```<code><td style="font-size: 16px; color:#ffffff; font-family: 'Open Sans',Arial, sans-serif; line-height: 22px;">
</code>```

Solved ;)

Title: Email Table Layout - Overlapping text

Body:
I am using this template: https://mailbakery.com/template-store/product/basic-free-html-email-template/ for an email newsletter. I am having an issue with overlapping text in the testimonial on mobile. I have to have the quotation image which isn't in the jsfiddle but use your imagination lol. I've tried adding white-space: normal, a fixed-width, and word-break, but nothing. The tables have border-collapse: border.

Here is the jsFiddle: https://jsfiddle.net/z5jybrda/

 /* Linked Styles */
      body {
        padding: 0 !important;
        margin: 0 !important;
        display: block !important;
        min-width: 100% !important;
        width: 100% !important;
        background: #ffffff;
        -webkit-text-size-adjust: none;
      }
      a {
        color: #0000ee;
        text-decoration: none;
      }
      p {
        padding: 0 !important;
        margin: 0 !important;
      }

      /* Mobile styles */
      @media only screen and (max-device-width: 480px),
        only screen and (max-width: 480px) {
        .table_wrapper {
          width: 95%;
        }

        .mobile-full-width {
          width: 100% !important;
        }

        .mobile-shell {
          width: 100% !important;
          min-width: 100% !important;
        }

        .text-header,
        .m-center {
          text-align: center !important;
        }

        .m-font-15 {
          font-size: 15px !important;
        }

        .center {
          margin: 0 auto !important;
        }
        .container {
          padding: 20px 10px !important;
        }

        .td {
          width: 100% !important;
          min-width: 100% !important;
        }

        .m-br-15 {
          height: 15px !important;
        }
        .p30-15 {
          padding: 30px 15px !important;
        }
        .p0-15-30 {
          padding: 0px 15px 30px 15px !important;
        }
        .p0-15 {
          padding: 0px 15px !important;
        }
        .pb-30 {
          padding-bottom: 30px !important;
        }
        .mpb30 {
          padding-bottom: 30px !important;
        }
        .mpb15 {
          padding-bottom: 15px !important;
        }

        .m-td,
        .m-hide {
          display: none !important;
          width: 0 !important;
          height: 0 !important;
          font-size: 0 !important;
          line-height: 0 !important;
          min-height: 0 !important;
        }

        .column,
        .column-dir,
        .column-top,
        .column-empty,
        .column-empty2,
        .column-dir-top {
          float: left !important;
          width: 100% !important;
          display: block !important;
        }

        .column-empty {
          padding-bottom: 30px !important;
        }
        .column-empty2 {
          padding-bottom: 10px !important;
        }

        .content-spacing {
          width: 15px !important;
        }
      }

      @media only screen and (max-width: 310px) {
        .button {
          width: 195px !important;
        }

        img.quote {
          height: 22px;
          width: auto;
        }
        td.quote {
          width: 50px !important;
        }
      }

                                            Thank you for your excellent leadership and support over the last year. We all greatly appreciate your efforts to steer us all in the right direction.

                                                - John Doe recognizing John Doe

I appreciate any help

Body:
Well this is one of my favorite problems with HTML tables, what is happening to you is due to lack of space in the <td>, if you change td like this:

<td style="font-size: 16px; color:#ffffff; font-family: 'Open Sans',Arial, sans-serif; line-height: 22px;">

Solved ;)


问:
MERN format date to month, day, year with data from nodejs server
I have a nodejs server that is fetching some data from MongoDb for a react app. When I fetch this data my 'created' value is stored as 2022-02-08T03:27:17.318Z. My question is, How and where do I reformat this to the Month, day, year. Im pretty sure I need to keep my date as this format when storing in db, but I want my user to see 02/08/2022.

here is my Node.js function for listFiles, this has the created value that needs to be changed

```<code>const listFiles = async (req, res) => {
                try {
                    let files = await Files.find({_user: req.user.id}).select('file_name contacts duplicates failed created')

                    //console.log(created) ----> 2022-02-08T03:27:17.318Z
                    //I want 02/08/2022 do I do this in this function? or do I do this in React?

                   res.json(files)
                } catch (err) {
                    return res.status(400).json({
                        error: dbErrorHandler.getErrorMessage(err)
                    })
                }
            }

</code>```

Here is the React Action creator

```<code> export const listFiles = () => {
                return async function(dispatch) {
               await
               axios({
                url:"http://localhost:5000/files/create",
                method:"GET",
                withCredentials: true
                }).then( res => dispatch({type: LIST_FILES, payload: res.data}))
                }
        }

</code>```

Here is the reducer in frontend React app

```<code>import { LIST_FILES } from '../actions/types';

export default function (state = [], action) {
    switch (action.type) {
        case LIST_FILES:
            return action.payload
            default:
            return state;
    }
}

</code>```

答:
My Solution was install a library called react-moment. so npm install react-moment in frontend, and once I fetch data to frontend I can use something like this</p>
```<code>
import React from 'react'
import Moment from 'react-moment'

const Component = () => {

const createdFormatter = (rowData) => {
    const {created} = rowData.row.original // getting data from react-table

  return (
      <Media tag={Flex} align="center">
        <Media body className="ml-2">
// add this <Moment /> component and it formats date for me in React.
          <h5 className="mb-0 fs--1 mt-2"><Moment format="MM/DD/YYYY"
 date={created}/></h5>
        </Media>
      </Media>
  )};

};
</code>```

Body:
I have a nodejs server that is fetching some data from MongoDb for a react app. When I fetch this data my 'created' value is stored as 2022-02-08T03:27:17.318Z. My question is, How and where do I reformat this to the Month, day, year. Im pretty sure I need to keep my date as this format when storing in db, but I want my user to see 02/08/2022.

here is my Node.js function for listFiles, this has the created value that needs to be changed

const listFiles = async (req, res) => {
                try {
                    let files = await Files.find({_user: req.user.id}).select('file_name contacts duplicates failed created')

                    //console.log(created) ----> 2022-02-08T03:27:17.318Z
                    //I want 02/08/2022 do I do this in this function? or do I do this in React?

                   res.json(files)
                } catch (err) {
                    return res.status(400).json({
                        error: dbErrorHandler.getErrorMessage(err)
                    })
                }
            }

Here is the React Action creator

 export const listFiles = () => {
                return async function(dispatch) {
               await
               axios({
                url:"http://localhost:5000/files/create",
                method:"GET",
                withCredentials: true
                }).then( res => dispatch({type: LIST_FILES, payload: res.data}))
                }
        }

Here is the reducer in frontend React app

import { LIST_FILES } from '../actions/types';

export default function (state = [], action) {
    switch (action.type) {
        case LIST_FILES:
            return action.payload
            default:
            return state;
    }
}

Body:
My Solution was install a library called react-moment. so npm install react-moment in frontend, and once I fetch data to frontend I can use something like this

import React from 'react'
import Moment from 'react-moment'

const Component = () => {

const createdFormatter = (rowData) => {
    const {created} = rowData.row.original // getting data from react-table

  return (
      <Media tag={Flex} align="center">
        <Media body className="ml-2">
// add this <Moment /> component and it formats date for me in React.
          <h5 className="mb-0 fs--1 mt-2"><Moment format="MM/DD/YYYY"
 date={created}/></h5>
        </Media>
      </Media>
  )};

};


问:
Grid errors when compiling Sass

@media (min-width: 40em) {
  .article__grid {
    -ms-grid-columns: (1fr)[2];
        grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 64em) {
  .article__grid {
    -ms-grid-columns: (1fr)[4];
        grid-template-columns: repeat(4, 1fr);
  }
}```

When I start this project I didn't know how to use gulp, and instead I use the live SASS compiler;

but when I was trying to use the Grid layout on my project the vs code start telling me that the
CSS output has some problems , but even with that the result on my browser(chrome) was perfect. so my question here is " is there any problem with this code because when I checked the sass compiler I found out that the last update was in 2018."

enter image description here

答:
I am facing this same problem, but I use CSS specificity ( !important )  & its works in my case. But implementing it in your .scss file, hope it works for you.

```<code>@media (max-width: 1000px) {
   main {
     grid-template-columns: repeat(1, 1fr) !important;
   }
}
</code>```

Title: Grid errors when compiling Sass

Body:
@media (min-width: 40em) {
  .article__grid {
    -ms-grid-columns: (1fr)[2];
        grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 64em) {
  .article__grid {
    -ms-grid-columns: (1fr)[4];
        grid-template-columns: repeat(4, 1fr);
  }
}

When I start this project I didn't know how to use gulp, and instead I use the live SASS compiler;

but when I was trying to use the Grid layout on my project the vs code start telling me that the
CSS output has some problems , but even with that the result on my browser(chrome) was perfect. so my question here is " is there any problem with this code because when I checked the sass compiler I found out that the last update was in 2018."

enter image description here

Body:
I am facing this same problem, but I use CSS specificity ( !important )  & its works in my case. But implementing it in your .scss file, hope it works for you.

@media (max-width: 1000px) {
   main {
     grid-template-columns: repeat(1, 1fr) !important;
   }
}


问:
How to load fonts from LESS file with Webpack 5?
I am using Webpack 5 and loading fonts and other styles from a .less file. However, the fonts/styles do not seem to be loading, and I'm trying to figure out why.

bootstrap.less

```<code>@import (less) '~bootstrap/dist/css/bootstrap.css';

@font-face {
  font-family: 'Gibson';
  src: url('~fonts/gibson/gibson-semibold.otf') format('opentype');
  font-weight: bold;
}

@font-face {
  font-family: 'Gibson';
  src: url('~fonts/gibson/gibson-regular.otf') format('opentype');
  font-weight: normal;
}
</code>```

Config

```<code>{
  module: {
    rules: [
      {
        test: /\.otf$/,
        include: path.resolve(__dirname, './src/fonts'),
        use: {
            loader: 'file-loader',
            options: {
                name: '[name].[ext]',
                outputPath: 'fonts/',
                esModule: false
            },
        },
    },
      {
        test: /\.less$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              url: false,
            },
          },
          { loader: 'less-loader' },
        ],
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              url: false,
            },
          },
        ],
      },
    ],
  },
};
</code>```

I'm using React on Rails with Webpacker, and bootstrap.css is located under node_modules/bootstrap/dist/css.
the two .otf font files are located under public/packs/assets/fonts/gibson and also under app/assets/fonts/gibson.

What am I missing?
I can see that webpack is recognizing the font files at least:

```<code>...
odules by path ./app/assets/ 579 KiB
    modules by path ./app/assets/stylesheets/application/*.less 76.7 KiB 62 modules
    modules by path ./app/assets/stylesheets/*.less 502 KiB 4 modules
    modules by path ./app/assets/images/ 362 bytes 4 modules
    modules by path ./app/assets/fonts/gibson/*.otf 173 bytes 2 modules
webpack 5.68.0 compiled successfully in 7608 ms

</code>```

However, I do not see the fonts loaded on the site itself.
In my main application.jsx I have imported like so:
import 'stylesheets/bootstrap.less';

答:
I was able to fix this issue by adding:

*{font-family:Gibson;}

to my bootstrap.less file.
I'm really uncertain this is the best way to do this, but it does work.

Body:
I am using Webpack 5 and loading fonts and other styles from a .less file. However, the fonts/styles do not seem to be loading, and I'm trying to figure out why.

bootstrap.less

@import (less) '~bootstrap/dist/css/bootstrap.css';

@font-face {
  font-family: 'Gibson';
  src: url('~fonts/gibson/gibson-semibold.otf') format('opentype');
  font-weight: bold;
}

@font-face {
  font-family: 'Gibson';
  src: url('~fonts/gibson/gibson-regular.otf') format('opentype');
  font-weight: normal;
}

Config

{
  module: {
    rules: [
      {
        test: /\.otf$/,
        include: path.resolve(__dirname, './src/fonts'),
        use: {
            loader: 'file-loader',
            options: {
                name: '[name].[ext]',
                outputPath: 'fonts/',
                esModule: false
            },
        },
    },
      {
        test: /\.less$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              url: false,
            },
          },
          { loader: 'less-loader' },
        ],
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              url: false,
            },
          },
        ],
      },
    ],
  },
};

I'm using React on Rails with Webpacker, and bootstrap.css is located under node_modules/bootstrap/dist/css.
the two .otf font files are located under public/packs/assets/fonts/gibson and also under app/assets/fonts/gibson.

What am I missing?
I can see that webpack is recognizing the font files at least:

...
odules by path ./app/assets/ 579 KiB
    modules by path ./app/assets/stylesheets/application/*.less 76.7 KiB 62 modules
    modules by path ./app/assets/stylesheets/*.less 502 KiB 4 modules
    modules by path ./app/assets/images/ 362 bytes 4 modules
    modules by path ./app/assets/fonts/gibson/*.otf 173 bytes 2 modules
webpack 5.68.0 compiled successfully in 7608 ms

However, I do not see the fonts loaded on the site itself.
In my main application.jsx I have imported like so:
import 'stylesheets/bootstrap.less';


问:
Dictionary of custom objects, how best to sort and display in a SwiftUI view using List and ForEach?
I have a customObject which I store in Firebase's realtime database:

```<code>struct CustomObject: Codable {
    var id: UUID?
    var name: String?
    var status: String?
}
</code>```

The customObjects are stored in a Dictionary with UUID being the key:

I am able to load the data into a [String: CustomObject] Dictionary in my iOS application, but I am unsure if my approach to sort and display the customObjects using  a List() ForEach(...) {  is a best practice.

my current solution is to build an Array when the Dictionary is loaded

I use didSet everytime the database updates to recreate an Array which I can use on the list():

```<code>class AppManager: ObservableObject {

   @Published var customObjectArray: [CustomObject] = []

   @Published var customObjectDictionary: [String:CustomObject]? {
      didSet {
         if customObjectDictionary != nil {
            customObjectArray = []

            for (key, value) in customObjectDictionary! {
               var tempObject: CustomObject = value
               tempObject.id = UUID(uuidString: key)
               customObjectArray.append(tempObject)
            }

            customObjectArraySort()
         }
      }
   }
}
</code>```

This is my View:

```<code>struct MainView: View {
    @EnvironmentObject var app: AppManager

    var body: some View {
        List {
            ForEach(app.customObjectArray.indices, id: \.self) { index in
                HStack{
                    Text(app.customObjectArray[index].name ?? "")
                    Spacer()
                    Text(app.customObjectArray[index].status ?? "")
                }
            }
        }
    }
}
</code>```

I am aware that a Dictionary is a unordered collection and that attempting to sort based on customObject.name in a list with a Dictionary is unsuitable.

According to Apple's documentation

A dictionary stores associations between keys of the same type and
values of the same type in a collection with no defined ordering. Each
value is associated with a unique key, which acts as an identifier for
that value within the dictionary. Unlike items in an array, items in a
dictionary do not have a specified order. You use a dictionary when
you need to look up values based on their identifier, in much the same
way that a real-world dictionary is used to look up the definition for
a particular word.

Is using didSet and making an Array from the Dictionary of customObjects considered a best practice?

Is there a better approach for sorting and listing customObjects from a Dictionary?

答:
Turning a Dictionary into a RandomAccessCollection, to which an Array conforms,  is necessary if your want to run it through a ForEach, so this is fine.

Regardless of whether you have a Dictionary that you convert to an Array as your data source, you shouldn't use .indices in this way, especially for something that is easily made Identifiable.

```<code>struct MainView: View {
    @EnvironmentObject var app: AppManager

    var body: some View {
        List {
            ForEach(app.customObjectArray) { object in
                HStack{
                    Text(object.name ?? "")
                    Spacer()
                    Text(object.status ?? "")
                }
            }
        }
    }
}

struct CustomObject: Codable, Identifiable {
    var id: UUID // Make this non-optional
    var name: String?
    var status: String?
}
</code>```

The way you set it up, if any element is added to, or removed from, the array, you can cause a crash. This means you can't use .onDelete, etc. Also, .onMove won't work properly either.

Body:
I have a customObject which I store in Firebase's realtime database:

struct CustomObject: Codable {
    var id: UUID?
    var name: String?
    var status: String?
}

The customObjects are stored in a Dictionary with UUID being the key:

I am able to load the data into a [String: CustomObject] Dictionary in my iOS application, but I am unsure if my approach to sort and display the customObjects using  a List() ForEach(...) {  is a best practice.

my current solution is to build an Array when the Dictionary is loaded

I use didSet everytime the database updates to recreate an Array which I can use on the list():

class AppManager: ObservableObject {

   @Published var customObjectArray: [CustomObject] = []

   @Published var customObjectDictionary: [String:CustomObject]? {
      didSet {
         if customObjectDictionary != nil {
            customObjectArray = []

            for (key, value) in customObjectDictionary! {
               var tempObject: CustomObject = value
               tempObject.id = UUID(uuidString: key)
               customObjectArray.append(tempObject)
            }

            customObjectArraySort()
         }
      }
   }
}

This is my View:

struct MainView: View {
    @EnvironmentObject var app: AppManager

    var body: some View {
        List {
            ForEach(app.customObjectArray.indices, id: \.self) { index in
                HStack{
                    Text(app.customObjectArray[index].name ?? "")
                    Spacer()
                    Text(app.customObjectArray[index].status ?? "")
                }
            }
        }
    }
}

I am aware that a Dictionary is a unordered collection and that attempting to sort based on customObject.name in a list with a Dictionary is unsuitable.

According to Apple's documentation

A dictionary stores associations between keys of the same type and
values of the same type in a collection with no defined ordering. Each
value is associated with a unique key, which acts as an identifier for
that value within the dictionary. Unlike items in an array, items in a
dictionary do not have a specified order. You use a dictionary when
you need to look up values based on their identifier, in much the same
way that a real-world dictionary is used to look up the definition for
a particular word.

Is using didSet and making an Array from the Dictionary of customObjects considered a best practice?

Is there a better approach for sorting and listing customObjects from a Dictionary?

Body:
Turning a Dictionary into a RandomAccessCollection, to which an Array conforms,  is necessary if your want to run it through a ForEach, so this is fine.

Regardless of whether you have a Dictionary that you convert to an Array as your data source, you shouldn't use .indices in this way, especially for something that is easily made Identifiable.

struct MainView: View {
    @EnvironmentObject var app: AppManager

    var body: some View {
        List {
            ForEach(app.customObjectArray) { object in
                HStack{
                    Text(object.name ?? "")
                    Spacer()
                    Text(object.status ?? "")
                }
            }
        }
    }
}

struct CustomObject: Codable, Identifiable {
    var id: UUID // Make this non-optional
    var name: String?
    var status: String?
}

The way you set it up, if any element is added to, or removed from, the array, you can cause a crash. This means you can't use .onDelete, etc. Also, .onMove won't work properly either.


问:
Get the date of the weeks monday for a date in BigQuery
I have a set of dates, and I need to get the date of the monday for the same week of the date in BigQuery. Example:

```<code>2021-02-07  -->  2021-02-07
2021-02-08  -->  2021-02-07
2021-02-09  -->  2021-02-07
2021-02-10  -->  2021-02-07
...
</code>```

How can I get this?
So far I've been able to get the Weeknumber, but not the date, with the following sql:
EXTRACT(WEEK(MONDAY) FROM Fecha)

答:
Consider below simple approach

```<code>select date,
  date_trunc(date, week(sunday)) date_monday,
  date_trunc(date, week(tuesday)) date_wednesday
from your_table
</code>```

if apply to sample data in your question as

```<code>with your_table as (
  select date '2021-02-07' date union all
  select '2021-02-08' union all
  select '2021-02-09' union all
  select '2021-02-10'
)
</code>```

the output is

Body:
I have a set of dates, and I need to get the date of the monday for the same week of the date in BigQuery. Example:

2021-02-07  -->  2021-02-07
2021-02-08  -->  2021-02-07
2021-02-09  -->  2021-02-07
2021-02-10  -->  2021-02-07
...

How can I get this?
So far I've been able to get the Weeknumber, but not the date, with the following sql:
EXTRACT(WEEK(MONDAY) FROM Fecha)

Body:
Consider below simple approach

select date,
  date_trunc(date, week(sunday)) date_monday,
  date_trunc(date, week(tuesday)) date_wednesday
from your_table

if apply to sample data in your question as

with your_table as (
  select date '2021-02-07' date union all
  select '2021-02-08' union all
  select '2021-02-09' union all
  select '2021-02-10'
)

the output is