问:
Excel file not being downloaded when function is called via ajax method
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />
```

<p>This is the code which downloads the file. It was a simple button I added.</p>

<pre class="lang-js prettyprint-override"><code>function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}
</code>```

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}
```

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

答:
The data will be transformed to a query string on an AJAX GET request; just do that yourself using the jQuery param function:</p>

```<code>$('#excel').on('click',function(){
    var query = {
        location: $('#location').val(),
        area: $('#area').val(),
        booth: $('#booth').val()
    }

   var url = "{{URL::to('downloadExcel_location_details')}}?" + $.param(query)

   window.location = url;
});
</code>```

Body:
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />

This is the code which downloads the file. It was a simple button I added.

function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

Body:
The data will be transformed to a query string on an AJAX GET request; just do that yourself using the jQuery param function:

$('#excel').on('click',function(){
    var query = {
        location: $('#location').val(),
        area: $('#area').val(),
        booth: $('#booth').val()
    }

   var url = "{{URL::to('downloadExcel_location_details')}}?" + $.param(query)

   window.location = url;
});


来源: stackexchange

问:
What is the practice for loading native libraries in Websphere Liberty?
I am installing multiple applications under Websphere Liberty in Linux.  Each application needs to reference the same shared library, which loads a native driver; the library must be loaded into its own classloader.

In prior Websphere (8+) versions, it was very simple to use the UI to configure a library in this fashion: set the scope, give it a name, identify the jars on the classpath, provide the native library path, then check off "use an isolated class loader".  It is different for Liberty.

What is the practice for doing similar under Websphere Liberty?

Assume the following:

classpaths:

```<code>/usr/acc/lib/jars/firstjar-1.0.jar
/usr/acc/lib/jars/secondjar-1.0.jar
/usr/acc/lib/3rdparty/thirdjar-1.0.jar
</code>```

native driver:

```<code>/usr/acc/lib/3rdparty/driver.so
</code>```

According to IBM:

for a native driver, I just list it alongside the JAR files in a file tag

for a contained classloader, I need to reference it as a "commonLibraryRef".

This means the following should be correct:

```<code><library id="MyLibrary">
    <file name="/usr/acc/lib/jars/firstjar-1.0.jar"/>
    <file name="/usr/acc/lib/jars/secondjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/thirdjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/driver.so"/>
</library>

<application id="applicationWAR" location="application.war" name="applicationName" type=”war” autoStart="true">
    <classloader commonLibraryRef="MyLibrary"/>
<application/>
</code>```

Is that valid, or do I need to add -Djava.library.path=/usr/acc/lib/3rdparty to the jvm.options file?

At the time this is being asked, access to the Liberty instance is restricted, so design of the apps.xml is through speculation, requiring this question.

答:
The above is correct; the library declaration in apps.xml should be maintained above any application declarations.  Updating jvm.options is not necessary.  A short-hand is also acceptable using fileset, and an application can reference multiple libraries, comma-delimited; demonstrated as follows:

```<code><!-- library from above question -->
<library id="MyLibrary">
    <file name="/usr/acc/lib/jars/firstjar-1.0.jar"/>
    <file name="/usr/acc/lib/jars/secondjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/thirdjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/driver.so"/>
</library>

<!-- short-hand using fileset -->
<library id="AnotherLib">
    <fileset dir="/usr/acc/lib/2ndparty/" includes="*.jar" />
    <file name="/usr/acc/lib/2ndparty/driver.so" />
</library>

<!-- short-hand using fileset and no .so file; includes can be *.* -->
<library id="ThirdLib">
    <fileset dir="/usr/acc/lib/3/" includes="*.jar" />
</library>

<application id="applicationWAR" location="application.war" name="applicationName" type=”war” autoStart="true">
    <classloader commonLibraryRef="MyLibrary,AnotherLib,ThirdLib"/>
<application/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am installing multiple applications under Websphere Liberty in Linux.  Each application needs to reference the same shared library, which loads a native driver; the library must be loaded into its own classloader.

In prior Websphere (8+) versions, it was very simple to use the UI to configure a library in this fashion: set the scope, give it a name, identify the jars on the classpath, provide the native library path, then check off "use an isolated class loader".  It is different for Liberty.

What is the practice for doing similar under Websphere Liberty?

Assume the following:

classpaths:

/usr/acc/lib/jars/firstjar-1.0.jar
/usr/acc/lib/jars/secondjar-1.0.jar
/usr/acc/lib/3rdparty/thirdjar-1.0.jar

native driver:

/usr/acc/lib/3rdparty/driver.so

According to IBM:

for a native driver, I just list it alongside the JAR files in a file tag

for a contained classloader, I need to reference it as a "commonLibraryRef".

This means the following should be correct:

<library id="MyLibrary">
    <file name="/usr/acc/lib/jars/firstjar-1.0.jar"/>
    <file name="/usr/acc/lib/jars/secondjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/thirdjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/driver.so"/>
</library>

<application id="applicationWAR" location="application.war" name="applicationName" type=”war” autoStart="true">
    <classloader commonLibraryRef="MyLibrary"/>
<application/>

Is that valid, or do I need to add -Djava.library.path=/usr/acc/lib/3rdparty to the jvm.options file?

At the time this is being asked, access to the Liberty instance is restricted, so design of the apps.xml is through speculation, requiring this question.

Body:
The above is correct; the library declaration in apps.xml should be maintained above any application declarations.  Updating jvm.options is not necessary.  A short-hand is also acceptable using fileset, and an application can reference multiple libraries, comma-delimited; demonstrated as follows:

<!-- library from above question -->
<library id="MyLibrary">
    <file name="/usr/acc/lib/jars/firstjar-1.0.jar"/>
    <file name="/usr/acc/lib/jars/secondjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/thirdjar-1.0.jar"/>
    <file name="/usr/acc/lib/3rdparty/driver.so"/>
</library>

<!-- short-hand using fileset -->
<library id="AnotherLib">
    <fileset dir="/usr/acc/lib/2ndparty/" includes="*.jar" />
    <file name="/usr/acc/lib/2ndparty/driver.so" />
</library>

<!-- short-hand using fileset and no .so file; includes can be *.* -->
<library id="ThirdLib">
    <fileset dir="/usr/acc/lib/3/" includes="*.jar" />
</library>

<application id="applicationWAR" location="application.war" name="applicationName" type=”war” autoStart="true">
    <classloader commonLibraryRef="MyLibrary,AnotherLib,ThirdLib"/>
<application/>


问:
How to check if Azure Blob file Exists or Not
I want to check a particular file exist in Azure Blob Storage. Is it possible to check by specifying it's file name? Each time i got File Not Found Error.</p>

答:
Using the new package Azure.Storage.Blobs

```<code>BlobServiceClient blobServiceClient = new BlobServiceClient("YourStorageConnectionString");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("YourContainerName");
BlobClient blobClient = containerClient.GetBlobClient("YourFileName");
</code>```

then check if exists

```<code>if (blobClient.Exists()){
 //your code
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using the new package Azure.Storage.Blobs

BlobServiceClient blobServiceClient = new BlobServiceClient("YourStorageConnectionString");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("YourContainerName");
BlobClient blobClient = containerClient.GetBlobClient("YourFileName");

then check if exists

if (blobClient.Exists()){
 //your code
}


问:
Handling an element without click attribute
I want to click this element called "Select File", it is a button but i am unable to click it using selenium command. The the element I am about to click is as follows:

```<code><label for="file" class="pb default" style="display: inline-block;margin: 5px 10px;">Select File</label>
</code>```

the script I am using to click for that element is:

```<code>_test_=browser.find_elements_by_class_name("pb default")
_test_.click()
</code>```

It gives an exception like this:

```<code>Traceback (most recent call last):
  File "z:\test_selenium_impossible_click.py", line 58, in
<module>
    _test_.click()
AttributeError: 'list' object has no attribute 'click'
</code>```

I am using latest firefox version with latest webdriver for firefox

UPDATE :
i have edited the code to become like this :

```<code>_test_=browser.find_element_by_class_name("pb default")
_test_.click()
</code>```

but now it gives output like this :

```<code>  Traceback (most recent call last):
  File "z:\automator-python\test_selenium_impossible_click.py", line 57, in <module>
    _test_=browser.find_element_by_class_name("pb default")
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .pb default
</code>```

i have tried the other ways like what has been suggested to me but it still gives output like what i mentioned above...do you know how to solve this??

答:
This error message...

```<code>AttributeError: 'list' object has no attribute 'click'
</code>```

...implies that AttributeError was raised when you tried to invoke click() on a List element.

click() method can be invoked only on a WebElement but not on a List.

In your code trials you have used find_elements_by_class_name() (note the s in elements) which returns a List. So when you try to invoke click() on the List, AttributeError is raised. So first of all you need to replace find_elements_by_class_name() with find_element_by_class_name().

Additionally, you can't pass multiple classes as arguments to find_element_by_class_name() which will result in invalid selector: Compound class names not permitted error. To pass multiple classes you have to use either css-selectors or xpath as a Locator Strategy and you can use either of the following solutions:

Using css_selector:

```<code>_test_ = browser.find_elements_by_css_selector(".pb.default")
_test_.click()
</code>```

Using xpath:

```<code>_test_ = browser.find_element_by_xpath("//*[@class='pb default']")
_test_.click()
</code>```

However, as per best practices, I would suggest to use a granular locator adding the tag_name as follows:

Using css_selector:

```<code>_test_ = browser.find_elements_by_css_selector("label.pb.default[for='file']")
_test_.click()
</code>```

Using xpath:

```<code>_test_ = browser.find_element_by_xpath("//label[@class='pb default' and @for='file']")
_test_.click()
</code>```

Update

Ideally, while invoking click() you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using css_selector:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label.pb.default[for='file']"))).click()
</code>```

Using xpath:

```<code>WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//label[@class='pb default' and @for='file']"))).click()
</code>```

Reference

You can find a relevant detailed discussion in:

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

Body:
I want to click this element called "Select File", it is a button but i am unable to click it using selenium command. The the element I am about to click is as follows:

Select File

the script I am using to click for that element is:

_test_=browser.find_elements_by_class_name("pb default")
_test_.click()

It gives an exception like this:

Traceback (most recent call last):
  File "z:\test_selenium_impossible_click.py", line 58, in
<module>
    _test_.click()
AttributeError: 'list' object has no attribute 'click'

I am using latest firefox version with latest webdriver for firefox

UPDATE :
i have edited the code to become like this :

_test_=browser.find_element_by_class_name("pb default")
_test_.click()

but now it gives output like this :

  Traceback (most recent call last):
  File "z:\automator-python\test_selenium_impossible_click.py", line 57, in <module>
    _test_=browser.find_element_by_class_name("pb default")
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .pb default

i have tried the other ways like what has been suggested to me but it still gives output like what i mentioned above...do you know how to solve this??

Body:
This error message...

AttributeError: 'list' object has no attribute 'click'

...implies that AttributeError was raised when you tried to invoke click() on a List element.

click() method can be invoked only on a WebElement but not on a List.

In your code trials you have used find_elements_by_class_name() (note the s in elements) which returns a List. So when you try to invoke click() on the List, AttributeError is raised. So first of all you need to replace find_elements_by_class_name() with find_element_by_class_name().

Additionally, you can't pass multiple classes as arguments to find_element_by_class_name() which will result in invalid selector: Compound class names not permitted error. To pass multiple classes you have to use either css-selectors or xpath as a Locator Strategy and you can use either of the following solutions:

Using css_selector:

_test_ = browser.find_elements_by_css_selector(".pb.default")
_test_.click()

Using xpath:

_test_ = browser.find_element_by_xpath("//*[@class='pb default']")
_test_.click()

However, as per best practices, I would suggest to use a granular locator adding the tag_name as follows:

Using css_selector:

_test_ = browser.find_elements_by_css_selector("label.pb.default[for='file']")
_test_.click()

Using xpath:

_test_ = browser.find_element_by_xpath("//label[@class='pb default' and @for='file']")
_test_.click()

Update

Ideally, while invoking click() you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using css_selector:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label.pb.default[for='file']"))).click()

Using xpath:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//label[@class='pb default' and @for='file']"))).click()

Reference

You can find a relevant detailed discussion in:

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome


问:
how to pass encrypted query string in asp.net
I need to pass values between asp.net pages. How do i encrypt those values in the URL?
Example : Response.Redirect("customerAdd.aspx?customerId=" + custId);</p>

答: You mean something like this https://web.archive.org/web/20211020203100/https://www.4guysfromrolla.com/webtech/012000-1.shtml ?</p>

OwnerDisplayName: Ksmps

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Alex Reitbort


问:
Height not setting to the actual height of the div
I have a DIV that slides open to the height of the content, but for some reason on divs that have no content it's calculating the height wrong.

The 2nd blog entry down (Thoma) is a good example when expanded.

http://dririser.co.uk/index.php

The 'data-height' is 108px but it's setting the height of the DIV to 360px. The DIVs with content in work fine, it sets the correct height but seems to come to the wrong calculation on DIVs with no content in.

This is basically the jist of the code.

Set the hight as a value on the div.

```<code>$(".articleSlide").each(function () {
    var current = $(this);
    current.attr("data-height", current.height());
});
</code>```

Set a variable then apply the height.

```<code>$(".showTeamList").toggle(function() {
    var open_height = $(".articleSlide").attr("data-height") + "px";
    $(this).parent().parent().animate({"height": open_height}, "slow" );
 }, function() {
    $(this).parent().parent().animate({"height": "35"}, "slow" );
});
</code>```

答:
Your problem is that this line:

```<code>$(".articleSlide").attr("data-height")
</code>```

Will only ever find the first element with class .articleSlide then use the data-height of that. You want it to find the data-height of the element that is specific for that button., just like you did with:

```<code> $(this).parent().parent().animate({"height": open_height}, "slow" );
</code>```

Try:

```<code>$(this).parents(".articleSlide").attr("data-height");
</code>```

Body:
I have a DIV that slides open to the height of the content, but for some reason on divs that have no content it's calculating the height wrong.

The 2nd blog entry down (Thoma) is a good example when expanded.

http://dririser.co.uk/index.php

The 'data-height' is 108px but it's setting the height of the DIV to 360px. The DIVs with content in work fine, it sets the correct height but seems to come to the wrong calculation on DIVs with no content in.

This is basically the jist of the code.

Set the hight as a value on the div.

$(".articleSlide").each(function () {
    var current = $(this);
    current.attr("data-height", current.height());
});

Set a variable then apply the height.

$(".showTeamList").toggle(function() {
    var open_height = $(".articleSlide").attr("data-height") + "px";
    $(this).parent().parent().animate({"height": open_height}, "slow" );
 }, function() {
    $(this).parent().parent().animate({"height": "35"}, "slow" );
});

Body:
Your problem is that this line:

$(".articleSlide").attr("data-height")

Will only ever find the first element with class .articleSlide then use the data-height of that. You want it to find the data-height of the element that is specific for that button., just like you did with:

 $(this).parent().parent().animate({"height": open_height}, "slow" );

Try:

$(this).parents(".articleSlide").attr("data-height");


问:
p:selectOneMenu not refreshing properly when pressing F5
So before anything just to make it clear this is an issue that happens with firefox even in the showcase https://www.primefaces.org/showcase/ui/input/oneMenu.xhtml to replicate just select any value and hit f5 and the value will remain. Also check forum.primefaces.org/viewtopic.php?t=17525 for the details also check how to do autocomplete="off" at form level in JSF other solutions that didn't work for me

I have a little problem when hitting f5 to refresh page for some reason my selectOneMenu its keeping the previously selected value,I need him to have the default value or first one on the array again... any idea how can I fix this? or why does that happen? every other element of the page is succesfully reseting its value, this is the code of my selectOneMenu:

```<code><p:panel styleClass="cds-panel-reset">
                    <p:selectOneMenu id="somOrigenConsulta" tabindex="1"
                        binding="#{consultaPagoPremiosMB.somOrigenConsulta}"
                        label="Origen" widgetVar="wvSomOrigenconsulta"
                        style="width: 140px !important;">
                        <p:ajax event="change" process="somOrigenConsulta"
                            update=":accordion:tbwPagarPremio:frmConsultapagopremioscod:pnlGrdDatosConsulta
                :accordion:tbwPagarPremio:frmConsultapagopremioscod:dtbPagopremios"
                            listener="#{consultaPagoPremiosMB.mostrarDialogoOrigen()}" />
                        <f:selectItems
                            value="#{consultaPagoPremiosMB.aOrigenConsulta}" />
                        <p:ajax process="@this"
                            render=":accordion:tbwPagarPremio:frmConsultapagopremioscod:pnlGrdDatosConsulta" />
                    </p:selectOneMenu>
                </p:panel>
</code>```

Also it refreshes succesfully if I refresh by using CTRL+SHIFT+R, any idea why F5 doesn't???

could it be cache? https://www.saicharanreddy.com/whats-the-difference-between-f5-ctrlr-ctrlshiftr-ctrlf5-and-shiftf5-in-google-chrome-browser/

how can I deal with that in a selectonemenu holy..

I did some searching the problem seems to be mozilla, https://forum.primefaces.org/viewtopic.php?t=17525

But im not able to implement the autocomplete=off because it just doesn't appear to be an attribute of my selectonemenu (primefaces 7.0) please help another way to implement this

答: You can use dynamic="true" attribute. I got the same problem solved using this attribute.

Body:
So before anything just to make it clear this is an issue that happens with firefox even in the showcase https://www.primefaces.org/showcase/ui/input/oneMenu.xhtml to replicate just select any value and hit f5 and the value will remain. Also check forum.primefaces.org/viewtopic.php?t=17525 for the details also check how to do autocomplete="off" at form level in JSF other solutions that didn't work for me

I have a little problem when hitting f5 to refresh page for some reason my selectOneMenu its keeping the previously selected value,I need him to have the default value or first one on the array again... any idea how can I fix this? or why does that happen? every other element of the page is succesfully reseting its value, this is the code of my selectOneMenu:

                        <f:selectItems
                            value="#{consultaPagoPremiosMB.aOrigenConsulta}" />

Also it refreshes succesfully if I refresh by using CTRL+SHIFT+R, any idea why F5 doesn't???

could it be cache? https://www.saicharanreddy.com/whats-the-difference-between-f5-ctrlr-ctrlshiftr-ctrlf5-and-shiftf5-in-google-chrome-browser/

how can I deal with that in a selectonemenu holy..

I did some searching the problem seems to be mozilla, https://forum.primefaces.org/viewtopic.php?t=17525

But im not able to implement the autocomplete=off because it just doesn't appear to be an attribute of my selectonemenu (primefaces 7.0) please help another way to implement this


问:
React Jest setInterval test coverage
I am trying to get some test coverage on a functional component.  I have have in useEffect a setInterval to change a message every few seconds. For my test It seems like I am not testing whatever is in useEffect. I've tried jest.useFakeTimers();

Also I am setting useState.

component :

```<code>import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import styled from "styled-components";
// Array of strings
import { messages } from "./messages";

export const Wrapper = styled.div`
  font-family: 'Lato', sans-serif !important;
  box-sizing: border-box;
  width: 100%;
  display: block;
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
  height: 100vh;
  h1 {
    font-size: 2rem;
    color: rgb(100, 100, 100);
  }
};
`;

const loadMessage = () => {
  // this is the line that is not being tested.
  return messages[Math.floor(Math.random() * messages.length)];
};

export const Loader = () => {
  const [message, setMessage] = useState("Loading...");

  useEffect(() => {
    const id = setInterval(() => {
      // this is the line that is not being tested.
      setMessage(loadMessage());
    }, 3000);
    return () => clearInterval(id);
  }, [message]);

  return (
    <Wrapper id="login-content">
      <Row className="align-items-center h-100">
        <Col className="col-md-12 mx-auto">
          <div className="container text-center">
            <h1 className="loader" data-testid="loader" aria-live="polite">
              {message}
            </h1>
          </div>
        </Col>
      </Row>
    </Wrapper>
  );
};
</code>```

test :

```<code>import React from "react";
import { shallow } from "enzyme";
import { Loader } from "./Loader";

const doAsync = c => {
  setTimeout(() => {
    c(true);
  }, 3000);
};

jest.useFakeTimers();

describe("Loader component", () => {
  it("tests state", () => {
    const wrapper = shallow(<Loader />);
    const message = wrapper.find(".loader").text();

    jest.advanceTimersByTime(3000);

    const callback1 = () => {
      expect(wrapper.find(".loader").text()).not.toMatch(message);
    };

    doAsync(callback1);

    jest.useRealTimers();
  });
});
</code>```

答:
I have stumpled upon in Enzymes issues: https://github.com/airbnb/enzyme/issues/2086

useEffect function does not seem to be executed when the component is
  rendered with shallow.

given that, what I had to do is mock UseEffect.

```<code>const doAsync = c => {
  setTimeout(() => {
    c(true);
  }, 3000);
};

jest.useFakeTimers();

describe("Loader component", () => {
  beforeEach(() => {
    const useEffect = jest
      .spyOn(React, "useEffect")
      .mockImplementation(f => f());
  });

  it("tests state", done => {
    const wrapper = shallow(<Loader />);
    const message = wrapper.find(".loader").text();

    jest.advanceTimersByTime(3000);

    const callback1 = () => {
      expect(wrapper.find(".loader").text()).not.toMatch(message);
    };

    doAsync(callback1);

    jest.useRealTimers();
    done();
  });
});
</code>```

this makes my test pass and I get 100% coverage.

Title: React Jest setInterval test coverage

Body:
I am trying to get some test coverage on a functional component.  I have have in useEffect a setInterval to change a message every few seconds. For my test It seems like I am not testing whatever is in useEffect. I've tried jest.useFakeTimers();

Also I am setting useState.

component :

import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import styled from "styled-components";
// Array of strings
import { messages } from "./messages";

export const Wrapper = styled.div`
  font-family: 'Lato', sans-serif !important;
  box-sizing: border-box;
  width: 100%;
  display: block;
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
  height: 100vh;
  h1 {
    font-size: 2rem;
    color: rgb(100, 100, 100);
  }
};
`;

const loadMessage = () => {
  // this is the line that is not being tested.
  return messages[Math.floor(Math.random() * messages.length)];
};

export const Loader = () => {
  const [message, setMessage] = useState("Loading...");

  useEffect(() => {
    const id = setInterval(() => {
      // this is the line that is not being tested.
      setMessage(loadMessage());
    }, 3000);
    return () => clearInterval(id);
  }, [message]);

  return (
    <Wrapper id="login-content">
      <Row className="align-items-center h-100">
        <Col className="col-md-12 mx-auto">

              {message}

        </Col>
      </Row>
    </Wrapper>
  );
};

test :

import React from "react";
import { shallow } from "enzyme";
import { Loader } from "./Loader";

const doAsync = c => {
  setTimeout(() => {
    c(true);
  }, 3000);
};

jest.useFakeTimers();

describe("Loader component", () => {
  it("tests state", () => {
    const wrapper = shallow(<Loader />);
    const message = wrapper.find(".loader").text();

    jest.advanceTimersByTime(3000);

    const callback1 = () => {
      expect(wrapper.find(".loader").text()).not.toMatch(message);
    };

    doAsync(callback1);

    jest.useRealTimers();
  });
});

Body:
I have stumpled upon in Enzymes issues: https://github.com/airbnb/enzyme/issues/2086

useEffect function does not seem to be executed when the component is
  rendered with shallow.

given that, what I had to do is mock UseEffect.

const doAsync = c => {
  setTimeout(() => {
    c(true);
  }, 3000);
};

jest.useFakeTimers();

describe("Loader component", () => {
  beforeEach(() => {
    const useEffect = jest
      .spyOn(React, "useEffect")
      .mockImplementation(f => f());
  });

  it("tests state", done => {
    const wrapper = shallow(<Loader />);
    const message = wrapper.find(".loader").text();

    jest.advanceTimersByTime(3000);

    const callback1 = () => {
      expect(wrapper.find(".loader").text()).not.toMatch(message);
    };

    doAsync(callback1);

    jest.useRealTimers();
    done();
  });
});

this makes my test pass and I get 100% coverage.


问:
What does "The APR based Apache Tomcat Native library was not found" mean?
I am using Tomcat 7 in Eclipse on Windows. When starting Tomcat, I am getting the following info message:

The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path

What does this mean and how can I provide the APR library?

答:
My problem was in add some library from tomcat to eclipse class path i just going to
eclipse click right to project and going to debug configuration -> classpath -> Add External JARs add all jars files from apache-tomcat-7.0.35\bin this was my problem and it's worked for me .


问:
SQL group data taking date sequence into account
I am trying to group separate rows which might be broken by a different group. If they are broken I want them to group separately.

So I have:

```<code>Col1 | Col2
---------------------
| Y  |01/JAN/2012
| Y  |01/FEB/2012
| N  |01/MAR/2012
| Y  |01/APR/2012
| Y  |01/MAY/2012
</code>```

I want to get the result:

```<code>|col1|col2       |GRP
---------------------
| Y  |01/JAN/2012|1
| Y  |01/FEB/2012|1
| N  |01/MAR/2012|2
| Y  |01/APR/2012|3
| Y  |01/MAY/2012|3
</code>```

How can I achieve this?

My current attempt is this:

```<code>select
    Col1,
    Col2,
    dense_rank() over (partition by Col1 order by Col2 asc) as grp
from
    myTABLE
;
</code>```

but that groups all the 'Y's together and gives me a sequential number like this:

```<code>|col1|col2       |GRP
---------------------
| Y  |01/JAN/2012|1
| Y  |01/FEB/2012|2
| N  |01/MAR/2012|1
| Y  |01/APR/2012|3
| Y  |01/MAY/2012|4
</code>```

答:
This is a form of gaps-and-islands problem.  I would recommend using the difference of row numbers to identify the "island"s and then row_number():

```<code>select t.*, dense_rank() over (order by grp) as grp
from (select t.*,
             min(col2) over (partition by col1, seqnum - seqnum_2) as grp
      from (select t.*,
                   row_number() over (order by col2) as seqnum,
                   row_number() over (partition by col1 order by col2) as seqnum_2
            from t
           ) t
     ) t
order by col2;
</code>```

Actually, an easier way is to use lag() and a cumulative sum:

```<code>select t.*,
       sum(case when col1 = prev_col1 then 0 else 1 end) over (order by col2) as grp
from (select t.*, lag(col1) over (partition by col2) as prev_col1
      from t
     ) t
</code>```

Body:
I am trying to group separate rows which might be broken by a different group. If they are broken I want them to group separately.

So I have:

Col1 | Col2
---------------------
| Y  |01/JAN/2012
| Y  |01/FEB/2012
| N  |01/MAR/2012
| Y  |01/APR/2012
| Y  |01/MAY/2012

I want to get the result:

|col1|col2       |GRP
---------------------
| Y  |01/JAN/2012|1
| Y  |01/FEB/2012|1
| N  |01/MAR/2012|2
| Y  |01/APR/2012|3
| Y  |01/MAY/2012|3

How can I achieve this?

My current attempt is this:

select
    Col1,
    Col2,
    dense_rank() over (partition by Col1 order by Col2 asc) as grp
from
    myTABLE
;

but that groups all the 'Y's together and gives me a sequential number like this:

|col1|col2       |GRP
---------------------
| Y  |01/JAN/2012|1
| Y  |01/FEB/2012|2
| N  |01/MAR/2012|1
| Y  |01/APR/2012|3
| Y  |01/MAY/2012|4

Body:
This is a form of gaps-and-islands problem.  I would recommend using the difference of row numbers to identify the "island"s and then row_number():

select t.*, dense_rank() over (order by grp) as grp
from (select t.*,
             min(col2) over (partition by col1, seqnum - seqnum_2) as grp
      from (select t.*,
                   row_number() over (order by col2) as seqnum,
                   row_number() over (partition by col1 order by col2) as seqnum_2
            from t
           ) t
     ) t
order by col2;

Actually, an easier way is to use lag() and a cumulative sum:

select t.*,
       sum(case when col1 = prev_col1 then 0 else 1 end) over (order by col2) as grp
from (select t.*, lag(col1) over (partition by col2) as prev_col1
      from t
     ) t


问:
How to deploy Angular app under container of nginx?
I'm trying to deploy Angular app under docker Nginx. My config is next:

./Dockerfile

```<code>FROM node:12-alpine AS builder
ENV NODE_ENV production
WORKDIR /usr/src/app
COPY ["package.json", "yarn.lock", "./"]
RUN yarn install --production=false
COPY . .
RUN yarn build

FROM nginx:alpine
COPY --from=builder /usr/src/app/dist/angular-nginx/* /usr/share/nginx/html/
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
</code>```

./nginx.conf

```<code>server {
  listen 80;
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}
</code>```

The app works, but its assets like images doesn't load (On development assets works).

And if I try to access directly to http://localhost:4000/assets/img/logo.png always go to http://localhost:4000/

What is my mistake?, thank you very much for the help.

答:
the problem is probabably in this command

```<code>COPY --from=builder /usr/src/app/dist/angular-nginx/* /usr/share/nginx/html/
</code>```

should be

```<code>COPY --from=builder /usr/src/app/dist/angular-nginx/ /usr/share/nginx/html/
</code>```

with your variant you are copying just the first layer of the directory and just COPY dir/ should do the thing

Body:
I'm trying to deploy Angular app under docker Nginx. My config is next:

./Dockerfile

FROM node:12-alpine AS builder
ENV NODE_ENV production
WORKDIR /usr/src/app
COPY ["package.json", "yarn.lock", "./"]
RUN yarn install --production=false
COPY . .
RUN yarn build

FROM nginx:alpine
COPY --from=builder /usr/src/app/dist/angular-nginx/* /usr/share/nginx/html/
COPY ./nginx.conf /etc/nginx/conf.d/default.conf

./nginx.conf

server {
  listen 80;
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}

The app works, but its assets like images doesn't load (On development assets works).

And if I try to access directly to http://localhost:4000/assets/img/logo.png always go to http://localhost:4000/

What is my mistake?, thank you very much for the help.

Body:
the problem is probabably in this command

COPY --from=builder /usr/src/app/dist/angular-nginx/* /usr/share/nginx/html/

should be

COPY --from=builder /usr/src/app/dist/angular-nginx/ /usr/share/nginx/html/

with your variant you are copying just the first layer of the directory and just COPY dir/ should do the thing


问:
Control access to files based on DB values with PHP/Apache

What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

```<code>//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}
</code>```

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.

答: "mod_rewrite" all attempts to access image via a fake path name to PHP file with the image file name as a query param and then do your magic there. Storing the images outside of the public folder should prevent any unwanted public access. Alternatively store the actual image in the DB itself.</p>

Body:
What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.


问:
using spread syntax with ternary operator inside object literal
Consider following code, where one object is composed from two parts: values and their corresponding descriptions:

let flagConfigObj = {};

const features = {
  f1: {
    value: 1,
    type: 'type1'
  },
  f2: {
    value: 2,
    type: 'type2'
  }
};

let featuresDescription = {
  f1: {
    description: 'desc 1'
  },
  f2: {
    description: 'desc 2'
  }
};

Object.keys(features).forEach(key => {
  flagConfigObj[key] = {
    ...features[key],
    ...(featuresDescription[key] || { some: 'backup' })
  };
});

console.log(flagConfigObj);

```

<p>As you might notice, when composite is constructed, there is <code>||</code> operator preventing form spreading non-existing object and replacing it with some default templates. And so, output for this code will be:</p>

```{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', description: 'desc 2' }
}
```

<p>But when corresponding description field in <code>featuresDescription</code> is missing, it's replaced to:</p>

```{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', some: 'backup' }
}
```

<p><strong>The question</strong></p>

<p>How to replace <code>||</code> syntax with ternary operator <code>?:</code>?
I've tried some funny combinations like </p>

```featuresDescription[key] ? ...featuresDescription[key] : {some: 'backup'}
{featuresDescription[key]} ? ...featuresDescription[key] : {some: 'backup'}
```

But all of them gives syntax error, and I'm feeling now like just blindly randomizing positions of [,],},{,... instead of truly understanding it...

Any help as always is appreciated!

答:
The spread syntax is part of the object initializer grammar but not part of the general expression grammar, so your entire ? : has to be to the right:

```<code> ... featuresDescription[key] ? featuresDescription[key] : { some: "backup" }
</code>```

In this particular case, there's not any effective difference between this and the original with the simple ||. The expression

```<code>expr1 ? expr1 : expr2
</code>```

means, "if expr1 evaluates to a "truthy" value, use its value; otherwise use the value of expr2".  That is precisely the same as what

```<code>expr1 || expr2
</code>```

means. (Well, ignoring possible side-effects of expr1, which would be an even stronger incentive to using the simpler || form unless you're laying booby-traps for some future programmer.)

Body:
Consider following code, where one object is composed from two parts: values and their corresponding descriptions:

let flagConfigObj = {};

const features = {
  f1: {
    value: 1,
    type: 'type1'
  },
  f2: {
    value: 2,
    type: 'type2'
  }
};

let featuresDescription = {
  f1: {
    description: 'desc 1'
  },
  f2: {
    description: 'desc 2'
  }
};

Object.keys(features).forEach(key => {
  flagConfigObj[key] = {
    ...features[key],
    ...(featuresDescription[key] || { some: 'backup' })
  };
});

console.log(flagConfigObj);

As you might notice, when composite is constructed, there is || operator preventing form spreading non-existing object and replacing it with some default templates. And so, output for this code will be:

{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', description: 'desc 2' }
}

But when corresponding description field in featuresDescription is missing, it's replaced to:

{
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', some: 'backup' }
}

The question

How to replace || syntax with ternary operator ?:?
I've tried some funny combinations like

featuresDescription[key] ? ...featuresDescription[key] : {some: 'backup'}
{featuresDescription[key]} ? ...featuresDescription[key] : {some: 'backup'}

But all of them gives syntax error, and I'm feeling now like just blindly randomizing positions of [,],},{,... instead of truly understanding it...

Any help as always is appreciated!

Body:
The spread syntax is part of the object initializer grammar but not part of the general expression grammar, so your entire ? : has to be to the right:

 ... featuresDescription[key] ? featuresDescription[key] : { some: "backup" }

In this particular case, there's not any effective difference between this and the original with the simple ||. The expression

expr1 ? expr1 : expr2

means, "if expr1 evaluates to a "truthy" value, use its value; otherwise use the value of expr2".  That is precisely the same as what

expr1 || expr2

means. (Well, ignoring possible side-effects of expr1, which would be an even stronger incentive to using the simpler || form unless you're laying booby-traps for some future programmer.)


问:
How do I use the `--directory` flag of KRun
I've compiled a K definition using kompile foo.k.

However, when I run krun --directory foo-kompiled/ my-program.foo I see the following error:

```<code>[Error] Critical: Could not find a compiled definition. Use --directory to specify one.
</code>```

How do I correctly use this option?

答: For historical reasons, kompile --directory . foo.k creates a directory foo-kompiled underneath . rather than using . as the output directory itself. Similarly, krun and other tools that use a compiled k definition look for a directory matching the glob *-kompiled within the directory passed by --directory. Thus, if you run kompile foo.k the correct invocation for krun (since the default value of --directory is the current working directory) is krun my-program.foo --directory ., or simply krun my-program.foo

Body:
I've compiled a K definition using kompile foo.k.

However, when I run krun --directory foo-kompiled/ my-program.foo I see the following error:

[Error] Critical: Could not find a compiled definition. Use --directory to specify one.

How do I correctly use this option?


问:
'dotnet quit unexpectedly' after installing hangfire
I installed HangFire packages and made several changes in Startup.cs
After building the code, I get this error: "dotnet quit unexpectedly".

Startup.cs

```<code> public void ConfigureServices (IServiceCollection services) {

        services.AddHangfire(configuration=>{
            configuration.UseSqlServerStorage("ConnectionStrings:DefaultConnection");
        });

        services.AddMvc();
        // Add framework services.
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure (IApplicationBuilder app, IHostingEnvironment env) {

        app.UseHangfireServer();
        app.UseHangfireDashboard();

    }
</code>```

Problem is with 2 lines in Configure().
app.UseHangFireServer() and app.UseHangfireDashboard();

When I remove these two, it runs fine.

I tried:
deleting nuget cache and restore.
checked dotnet --version in terminal and in project and they both are the same(2.2.106)

UPDATE:
I fixed the part where I had trouble building the code. The problem was that I was using UseSqlServerStorage instead of UsePostgreSqlServerStorage.

I have another problem now: I can not access dashboard. http://localhost:5000/hangfire page doesn't exist.

答: got the same error because I missed a connection string of the second database</p>

Body:
I installed HangFire packages and made several changes in Startup.cs
After building the code, I get this error: "dotnet quit unexpectedly".

Startup.cs

 public void ConfigureServices (IServiceCollection services) {

        services.AddHangfire(configuration=>{
            configuration.UseSqlServerStorage("ConnectionStrings:DefaultConnection");
        });

        services.AddMvc();
        // Add framework services.
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure (IApplicationBuilder app, IHostingEnvironment env) {

        app.UseHangfireServer();
        app.UseHangfireDashboard();

    }

Problem is with 2 lines in Configure().
app.UseHangFireServer() and app.UseHangfireDashboard();

When I remove these two, it runs fine.

I tried:
deleting nuget cache and restore.
checked dotnet --version in terminal and in project and they both are the same(2.2.106)

UPDATE:
I fixed the part where I had trouble building the code. The problem was that I was using UseSqlServerStorage instead of UsePostgreSqlServerStorage.

I have another problem now: I can not access dashboard. http://localhost:5000/hangfire page doesn't exist.


问:
Simple Stacked Barchart using VegaLite with Text Labels
I'm having an issue labeling my barchart.  I would like the total number of backers to be labeled at the right handside of each bar. Not the sum of "US Backers" and "Backers from Other Countries" individually as shown.

The dataset I'm using shows the most popular categories on the Kickstarter project website, and I have highlighted projects launched in the USA to show the popularity of the website in the States as compared to worldwide.

enter image description here

```<code>{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {
    "url": "https://raw.githubusercontent.com/taramcgirl/InfoVisProject/master/graphone.csv",
    "format": {
      "type": "csv"
    }
  },

  "title": {
    "text": "Total Backers per Category",
    "anchor": "middle",
    "fontSize":24
  },
   "width":400,
    "height":400,
    "mark": {
      "type": "bar",
      "cornerRadiusEnd": 4
      },
    "encoding": {
      "x": {
         "axis": {
          "title": "Number of Backers",
          "labelFontSize":10,
          "titleFontSize":15
          },
          "field" : "Backers",
          "type" :  "quantitative",
          "aggregate": "sum"
        },
      "y": {
        "axis": {
        "title": "Category",
        "labelFontSize":10,
        "titleFontSize":15
        },
        "field":"Main_Category",
        "type" : "nominal",
        "sort": "-x"
      },
      "color": {
        "field": "USA or ELSEWHERE",
        "type": "nominal",
        "scale": {
          "domain":["US","Other"],
          "range": ["#8101FA", "#00C7A9"]
          }
        },
      "opacity": {
          "value" : 0.5
      }
    },
    "layer": [{
    "mark": "bar"
    }, {
      "mark": {
        "type": "text",
        "align": "left",
        "baseline": "bottom",
        "stroke":"black",
        "dx": 3,
        "fontSize": 9,
        "fontWeight": "normal",
        "stack":"false"
      },
      "encoding": {
        "text": {
          "field": "Backers",
          "type": "quantitative",
          "aggregate": "sum",
          "stack": "true"
        }

    }
    }]
}
</code>```

答:
If you make it such that the color encoding only applies to the bar layer, you'll get the desired outcome. With a bit of cleanup of redundant & invalid parameters, the result looks like this: (vega editor):

```<code>{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {
    "url": "https://raw.githubusercontent.com/taramcgirl/InfoVisProject/master/graph1.csv"
  },
  "title": {
    "text": "Total Backers per Category",
    "anchor": "middle",
    "fontSize": 24
  },
  "width": 400,
  "height": 400,
  "encoding": {
    "x": {
      "axis": {
        "title": "Number of Backers",
        "labelFontSize": 10,
        "titleFontSize": 15
      },
      "scale": {"domain": [0, 10000000]},
      "field": "Backers",
      "type": "quantitative",
      "aggregate": "sum"
    },
    "y": {
      "axis": {"title": "Category", "labelFontSize": 10, "titleFontSize": 15},
      "field": "Main_Category",
      "type": "nominal",
      "sort": "-x"
    }
  },
  "layer": [
    {
      "mark": {"type": "bar", "cornerRadiusEnd": 4},
      "encoding": {
        "color": {
          "field": "USA or ELSEWHERE",
          "type": "nominal",
          "scale": {"domain": ["US", "Other"], "range": ["#8101FA", "#00C7A9"]}
        },
        "opacity": {"value": 0.5}
      }
    },
    {
      "mark": {
        "type": "text",
        "align": "left",
        "baseline": "middle",
        "stroke": "black",
        "dx": 3,
        "fontSize": 9
      },
      "encoding": {
        "text": {"field": "Backers", "type": "quantitative", "aggregate": "sum"}
      }
    }
  ]
}
</code>```

Body:
I'm having an issue labeling my barchart.  I would like the total number of backers to be labeled at the right handside of each bar. Not the sum of "US Backers" and "Backers from Other Countries" individually as shown.

The dataset I'm using shows the most popular categories on the Kickstarter project website, and I have highlighted projects launched in the USA to show the popularity of the website in the States as compared to worldwide.

enter image description here

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {
    "url": "https://raw.githubusercontent.com/taramcgirl/InfoVisProject/master/graphone.csv",
    "format": {
      "type": "csv"
    }
  },

  "title": {
    "text": "Total Backers per Category",
    "anchor": "middle",
    "fontSize":24
  },
   "width":400,
    "height":400,
    "mark": {
      "type": "bar",
      "cornerRadiusEnd": 4
      },
    "encoding": {
      "x": {
         "axis": {
          "title": "Number of Backers",
          "labelFontSize":10,
          "titleFontSize":15
          },
          "field" : "Backers",
          "type" :  "quantitative",
          "aggregate": "sum"
        },
      "y": {
        "axis": {
        "title": "Category",
        "labelFontSize":10,
        "titleFontSize":15
        },
        "field":"Main_Category",
        "type" : "nominal",
        "sort": "-x"
      },
      "color": {
        "field": "USA or ELSEWHERE",
        "type": "nominal",
        "scale": {
          "domain":["US","Other"],
          "range": ["#8101FA", "#00C7A9"]
          }
        },
      "opacity": {
          "value" : 0.5
      }
    },
    "layer": [{
    "mark": "bar"
    }, {
      "mark": {
        "type": "text",
        "align": "left",
        "baseline": "bottom",
        "stroke":"black",
        "dx": 3,
        "fontSize": 9,
        "fontWeight": "normal",
        "stack":"false"
      },
      "encoding": {
        "text": {
          "field": "Backers",
          "type": "quantitative",
          "aggregate": "sum",
          "stack": "true"
        }

    }
    }]
}

Body:
If you make it such that the color encoding only applies to the bar layer, you'll get the desired outcome. With a bit of cleanup of redundant & invalid parameters, the result looks like this: (<a href="https://vega.github.io/editor/#/url/vega-lite/N4KABGBEAkDODGALApgWwIaQFxUQFzwAdYsB6UgN2QHN0A6agSz0QFcAjOxge1IRQyUa6ALQAbZskoAWOgCtY3AHaQANOCgATdHkw5QECJFYAnMdlwFiZUifQB3BszbtWsZCfjK8yJXjpeqKS6dqjwTGakAJJKAGbcAGqMsAAKJtxyyPB4pBiwPiak1HaEiACMAbAUkBoAvupGeMxiyBYGhpA+AB54FpAAKty6YmAAQujwANYesGCEHmAAwjo03CYAnmoaRuhKSGt9qIyami1bhlDxfgDKjABerTgATNJ1DVD2xywW0gAMv+9IChGNR8D9-oDfF5NIwlNQ2tsoF0ERcdl1kijUY1mo8oAA5ViodgLbixMYTaYmWDnLFQMToYliABi3luDwsZQBiIunRxLJu91xZQArNywPUxZAEOgzvpIJpuBhYRYANoAsCc-5a34AXQlWMgsUYyDEmj64ymMxpPLw63mfQAjqxdk1dE0qNaOuhqMVhD4+rBCTULvqOpt9JL0OjqXLXbKoMsfNQ1ptVHSGSb+Xg2UL1by8C0szmOcLQzyjSazThIABZdCwgD6idWG09jTtuMgSkVsJlbagihMvWrImRiNqbw0kHp6w8qsR7R5GBMkzanQ7fXY6BMaigXhMSg8ACV0DC3ABRJRVsDSMsdKHcGFwzEGrxiA4R2kdCumvoAVWuABBMA1jAc8ABlrnPAB1AAJc8j3PfsbQ3atuyOJQ+3eL8pXgGVcWAeVFXrFQcBVSAAN3SAAHkWDnHU00gOw4VxciAGIAA5OTKJlAKotj-kWAB2QCAE5ID1MUIDvHluEICZmHDMBCIoGVWFxX46FLMUJxDbDlMlZdV0-Wl13tatul6fSeRlEFSLpZBYisqSoC3dwJEPQ5jlOVprI6fJ0mmTd6SmZCtGRHAAGY-KMK5s0FCxRJ0vzIAfJ94RMg1LLXH9r0gC1KWpRjbXMqAnRdZgdEYD1GO9X1aH9atA1QSBdNRNrpI0HUQFqIA" rel="nofollow noreferrer">vega editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {
    "url": "https://raw.githubusercontent.com/taramcgirl/InfoVisProject/master/graph1.csv"
  },
  "title": {
    "text": "Total Backers per Category",
    "anchor": "middle",
    "fontSize": 24
  },
  "width": 400,
  "height": 400,
  "encoding": {
    "x": {
      "axis": {
        "title": "Number of Backers",
        "labelFontSize": 10,
        "titleFontSize": 15
      },
      "scale": {"domain": [0, 10000000]},
      "field": "Backers",
      "type": "quantitative",
      "aggregate": "sum"
    },
    "y": {
      "axis": {"title": "Category", "labelFontSize": 10, "titleFontSize": 15},
      "field": "Main_Category",
      "type": "nominal",
      "sort": "-x"
    }
  },
  "layer": [
    {
      "mark": {"type": "bar", "cornerRadiusEnd": 4},
      "encoding": {
        "color": {
          "field": "USA or ELSEWHERE",
          "type": "nominal",
          "scale": {"domain": ["US", "Other"], "range": ["#8101FA", "#00C7A9"]}
        },
        "opacity": {"value": 0.5}
      }
    },
    {
      "mark": {
        "type": "text",
        "align": "left",
        "baseline": "middle",
        "stroke": "black",
        "dx": 3,
        "fontSize": 9
      },
      "encoding": {
        "text": {"field": "Backers", "type": "quantitative", "aggregate": "sum"}
      }
    }
  ]
}


问:
React-reveal Image Slide
I am using react reveal and doing an image slide up transition but the image is not showing, I have given the code below as well as the output image. I have added a picture which shows whats happening. the link in the picture was supposed to be an image but it's showing just Link

```<code>import React from 'react';
import { Link } from 'react-router-dom';
import Reveal from 'react-reveal';
import 'animate.css/animate.css';

const generateBlocks = ({blocks}) =>{
    if(blocks){
        return blocks.map((item)=>{

            const styles = {
                background:`url('/images/blocks/${item.image}') no-repeat `
            }

            return(
                <Reveal key={item.id} effect="animated fadeInUp"
                className={`item ${item.type}`}>

                 <div className="veil"></div>
                    <div
                        className="image"
                        style={styles} >

                        </div>
                        <div className="title">
                            <Link to={item.link}>{item.title}</Link>
                        </div>
                 </Reveal>
            )
        })
    }

}

const Blocks = (props) =>{
    return(
        <div className ="home_blocks">
            {generateBlocks(props)}
        </div>
    )
}
export default Blocks;][1]
</code>```

答:
Heve you tried to import the right component from Reveal:

import Reveal from 'react-reveal/Reveal';
```

Have a look into the Documentation: https://www.react-reveal.com/examples/common/custom/

Title: React-reveal Image Slide

Body:
I am using react reveal and doing an image slide up transition but the image is not showing, I have given the code below as well as the output image. I have added a picture which shows whats happening. the link in the picture was supposed to be an image but it's showing just Link

import React from 'react';
import { Link } from 'react-router-dom';
import Reveal from 'react-reveal';
import 'animate.css/animate.css';

const generateBlocks = ({blocks}) =>{
    if(blocks){
        return blocks.map((item)=>{

            const styles = {
                background:`url('/images/blocks/${item.image}') no-repeat `
            }

            return(
                <Reveal key={item.id} effect="animated fadeInUp"
                className={`item ${item.type}`}>

                            <Link to={item.link}>{item.title}</Link>

                 </Reveal>
            )
        })
    }

}

const Blocks = (props) =>{
    return(

            {generateBlocks(props)}

    )
}
export default Blocks;][1]

Body:
Heve you tried to import the right component from Reveal:

import Reveal from 'react-reveal/Reveal';

Have a look into the Documentation: https://www.react-reveal.com/examples/common/custom/


问:
EF Core 3.1 is overwriting all of the fields with null values from DTO when I send an HTTP PUT update request to my API

Context

I have an API set up with CRUD operations - I am having trouble with the HTTP PUT endpoint that I use for updating an entity. I only want the API to be able to update some fields for the entity, so I use a Data transfer object (DTO), and use AutoMapper to map it to the domain model for Entity Framework Core (EF Core) to update the entity in the database. When using AutoMapper to map from the DTO to the domain model, null values will be added, and then overwrite these values in the database. How can I prevent this from happening?

Code

PlayerController.cs

[HttpPut("{id}")]
public async Task<IActionResult> PutPlayer(Guid id, PlayerUpdateDto playerUpdateDto)
{
    Player player = _mapper.Map<Player>(playerUpdateDto);

    _context.Entry(player).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!PlayerExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return Ok(player);
}
```

<p><strong>Player.cs</strong></p>

<pre class="lang-c# prettyprint-override"><code>public class Player
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    public double Rating { get; set; }

    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    public ICollection<Match> MatchesOne { get; set; }
    public ICollection<Match> MatchesTwo { get; set; }
    public ICollection<Match> MatchesThree { get; set; }
    public ICollection<Match> MatchesFour { get; set; }
}
</code>```

PlayerUpdateDto.cs

public class PlayerUpdateDto
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
```

The Player rating, created, and updated properties all get set to null values, but I want them to remain the same since they're not in the DTO. Any and all help would be greatly appreciated!

答:
This

```<code> _context.Entry(player).State = EntityState.Modified;
</code>```

Marks all the properties as modified.  Instead mark only the ones you want to update.  Eg

```<code> _context.Entry(player).Property(p => p.Name).IsModified = true;
</code>```

Body:
Context

I have an API set up with CRUD operations - I am having trouble with the HTTP PUT endpoint that I use for updating an entity. I only want the API to be able to update some fields for the entity, so I use a Data transfer object (DTO), and use AutoMapper to map it to the domain model for Entity Framework Core (EF Core) to update the entity in the database. When using AutoMapper to map from the DTO to the domain model, null values will be added, and then overwrite these values in the database. How can I prevent this from happening?

Code

PlayerController.cs

[HttpPut("{id}")]
public async Task<IActionResult> PutPlayer(Guid id, PlayerUpdateDto playerUpdateDto)
{
    Player player = _mapper.Map<Player>(playerUpdateDto);

    _context.Entry(player).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!PlayerExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return Ok(player);
}

Player.cs

public class Player
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    public double Rating { get; set; }

    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    public ICollection<Match> MatchesOne { get; set; }
    public ICollection<Match> MatchesTwo { get; set; }
    public ICollection<Match> MatchesThree { get; set; }
    public ICollection<Match> MatchesFour { get; set; }
}

PlayerUpdateDto.cs

public class PlayerUpdateDto
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

The Player rating, created, and updated properties all get set to null values, but I want them to remain the same since they're not in the DTO. Any and all help would be greatly appreciated!

Body:
This

 _context.Entry(player).State = EntityState.Modified;

Marks all the properties as modified.  Instead mark only the ones you want to update.  Eg

 _context.Entry(player).Property(p => p.Name).IsModified = true;


问:
Unable to send an email using PHPmailer in Drupal 7
My website https://www.smcin.com/ created in drupal 7 and hosted in google cloud console. I am using PHPmailer smtp module to send email through website using port 25. But not mail has been triggered and give error

"test e-mail has NOT been sent to xxxxxxxx@yahoo.com. You should check
  the logs for error messages."

On logs only this message has been shown:

```<code>MESSAGE:    Error sending e-mail (from xxxxxxxx@xxxxxxx.xxx to xxxxxxxx@yahoo.com).
SEVERITY:   error.
</code>```

I also tried other ports (80, 465, 2525 ) and server (gmail, my official webmail) but nothing work.
I wasted lots of time but no solution found.

答:
Your question is unclear as to which Google Cloud Platform service you are using.

Assuming that you're using Compute Engine, please see Sending email from an instance.

NB "Port 25 is always blocked and can't be used"

You should be able to configure it to use e.g. 465.

You may continue to have challenges in showing a good reputation for your instances' IP addresses.

Body:
My website https://www.smcin.com/ created in drupal 7 and hosted in google cloud console. I am using PHPmailer smtp module to send email through website using port 25. But not mail has been triggered and give error

"test e-mail has NOT been sent to xxxxxxxx@yahoo.com. You should check
  the logs for error messages."

On logs only this message has been shown:

MESSAGE:    Error sending e-mail (from xxxxxxxx@xxxxxxx.xxx to xxxxxxxx@yahoo.com).
SEVERITY:   error.

I also tried other ports (80, 465, 2525 ) and server (gmail, my official webmail) but nothing work.
I wasted lots of time but no solution found.


问:
How would I process loop index separately
would like to process different index ranges differently. </p>

```<code>for i in range(0,10):
        [0,3]:
           print('hello')
        [3,5]:
          print('hi')
        [5,10]:
          print('end')```
</code>```

答:
You could reuse the range function

```<code>
  for i in range(0,10):
      if i in range(0,3):
           print('hello')
      if i in range(3,5):
          print('hi')
      if i in range(5,10):
          print('end')

</code>```

However, 0 <= i < 3 performs better, for example

Body:
would like to process different index ranges differently.

for i in range(0,10):
        [0,3]:
           print('hello')
        [3,5]:
          print('hi')
        [5,10]:
          print('end')```

Body:
You could reuse the range function

  for i in range(0,10):
      if i in range(0,3):
           print('hello')
      if i in range(3,5):
          print('hi')
      if i in range(5,10):
          print('end')

However, 0 <= i < 3 performs better, for example


问:
Merging Dataframes With Some Matching Columns Names Results in Duplicate Columns
I have two data frames with some overlapping columns that I am trying to merge for a given Symbol and Date. But when I do, rather than fill the missing data, new columns with suffixes are being added.

df1

```<code>  Investor     Date   Name Symbol  Price  Amount  Income
0     Mike  2019 Q4  A Inc    AAA    NaN     100     NaN
1     Bill  2019 Q4  C Inc    CCC    NaN     200     NaN
2     John  2018 Q4  A Inc    AAA    NaN     200     NaN
3     Faye  2018 Q4  D Inc    DDD    NaN     300     NaN
4      Joe  2019 Q2  A Inc    AAA    NaN     300     NaN
5     Hank  2019 Q2  S Inc    SSS    NaN     100     NaN
</code>```

df2

```<code>      Date   Name Symbol  Price  Income
0  2019 Q4  A Inc    AAA      5      10
1  2019 Q4  B Inc    BBB      3      20
2  2019 Q4  C Inc    CCC     33      30
3  2019 Q4  D Inc    DDD     30      40
4  2018 Q4  A Inc    AAA     23      20
5  2018 Q4  B Inc    BBB      4      30
6  2018 Q4  C Inc    CCC    136      40
7  2018 Q4  D Inc    DDD      6      50
8  2018 Q4  E Inc    EEE      1      90
</code>```

I want my output to look like:

```<code>  Investor     Date   Name Symbol  Price  Amount  Income
0     Mike  2019 Q4  A Inc    AAA    5.0     100    10.0
1     Bill  2019 Q4  C Inc    CCC   33.0     200    30.0
2     John  2018 Q4  A Inc    AAA   23.0     200    20.0
3     Faye  2018 Q4  D Inc    DDD    6.0     300    50.0
4      Joe  2019 Q2  A Inc    AAA    NaN     300     NaN
5     Hank  2019 Q2  S Inc    SSS    NaN     100     NaN
</code>```

But when I do df3 = pd.merge(df1, df2, on=['Date', 'Symbol'], how='left'), I get:

```<code>  Investor     Date Name_x Symbol  ...  Income_x  Name_y  Price_y Income_y
0     Mike  2019 Q4  A Inc    AAA  ...       NaN   A Inc      5.0     10.0
1     Bill  2019 Q4  C Inc    CCC  ...       NaN   C Inc     33.0     30.0
2     John  2018 Q4  A Inc    AAA  ...       NaN   A Inc     23.0     20.0
3     Faye  2018 Q4  D Inc    DDD  ...       NaN   D Inc      6.0     50.0
4      Joe  2019 Q2  A Inc    AAA  ...       NaN     NaN      NaN      NaN
5     Hank  2019 Q2  S Inc    SSS  ...       NaN     NaN      NaN      NaN
</code>```

What am I doing wrong?

```<code>df1 = `df1 = {'Investor': {0: 'Mike', 1: 'Bill', 2: 'John', 3: 'Faye', 4: 'Joe', 5: 'Hank'}, 'Date': {0: '2019 Q4', 1: '2019 Q4', 2: '2018 Q4', 3: '2018 Q4', 4: '2019 Q2', 5: '2019 Q2'}, 'Name': {0: 'A Inc', 1: 'C Inc', 2: 'A Inc', 3: 'D Inc', 4: 'A Inc', 5: 'S Inc'}, 'Symbol': {0: 'AAA', 1: 'CCC', 2: 'AAA', 3: 'DDD', 4: 'AAA', 5: 'SSS'}, 'Price': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan}, 'Amount': {0: 100, 1: 200, 2: 200, 3: 300, 4: 300, 5: 100}, 'Income': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan}}`
df2 = {'Date': {0: '2019 Q4', 1: '2019 Q4', 2: '2019 Q4', 3: '2019 Q4', 4: '2018 Q4', 5: '2018 Q4', 6: '2018 Q4', 7: '2018 Q4', 8: '2018 Q4'}, 'Name': {0: 'A Inc', 1: 'B Inc', 2: 'C Inc', 3: 'D Inc', 4: 'A Inc', 5: 'B Inc', 6: 'C Inc', 7: 'D Inc', 8: 'E Inc'}, 'Symbol': {0: 'AAA', 1: 'BBB', 2: 'CCC', 3: 'DDD', 4: 'AAA', 5: 'BBB', 6: 'CCC', 7: 'DDD', 8: 'EEE'}, 'Price': {0: 5, 1: 3, 2: 33, 3: 30, 4: 23, 5: 4, 6: 136, 7: 6, 8: 1}, 'Income': {0: 10, 1: 20, 2: 30, 3: 40, 4: 20, 5: 30, 6: 40, 7: 50, 8: 90}}
df3 = pd.merge(df1, df2, on=['Date', 'Symbol'], how='left')
</code>```

答:
That's because you have Name, Income, Price on both dataframes. If you don't want the duplicates, you should then select those columns you want:

```<code>(df1[['Investor', 'Name', 'Date','Symbol','Amount']]
   .merge(df2.drop('Name', axis=1),
          on=['Date','Symbol'],
          how='left')
)
</code>```

Output:

```<code>  Investor   Name     Date Symbol  Amount  Price  Income
0     Mike  A Inc  2019 Q4    AAA     100    5.0    10.0
1     Bill  C Inc  2019 Q4    CCC     200   33.0    30.0
2     John  A Inc  2018 Q4    AAA     200   23.0    20.0
3     Faye  D Inc  2018 Q4    DDD     300    6.0    50.0
4      Joe  A Inc  2019 Q2    AAA     300    NaN     NaN
5     Hank  S Inc  2019 Q2    SSS     100    NaN     NaN
</code>```

Body:
I have two data frames with some overlapping columns that I am trying to merge for a given Symbol and Date. But when I do, rather than fill the missing data, new columns with suffixes are being added.

df1

  Investor     Date   Name Symbol  Price  Amount  Income
0     Mike  2019 Q4  A Inc    AAA    NaN     100     NaN
1     Bill  2019 Q4  C Inc    CCC    NaN     200     NaN
2     John  2018 Q4  A Inc    AAA    NaN     200     NaN
3     Faye  2018 Q4  D Inc    DDD    NaN     300     NaN
4      Joe  2019 Q2  A Inc    AAA    NaN     300     NaN
5     Hank  2019 Q2  S Inc    SSS    NaN     100     NaN

df2

      Date   Name Symbol  Price  Income
0  2019 Q4  A Inc    AAA      5      10
1  2019 Q4  B Inc    BBB      3      20
2  2019 Q4  C Inc    CCC     33      30
3  2019 Q4  D Inc    DDD     30      40
4  2018 Q4  A Inc    AAA     23      20
5  2018 Q4  B Inc    BBB      4      30
6  2018 Q4  C Inc    CCC    136      40
7  2018 Q4  D Inc    DDD      6      50
8  2018 Q4  E Inc    EEE      1      90

I want my output to look like:

  Investor     Date   Name Symbol  Price  Amount  Income
0     Mike  2019 Q4  A Inc    AAA    5.0     100    10.0
1     Bill  2019 Q4  C Inc    CCC   33.0     200    30.0
2     John  2018 Q4  A Inc    AAA   23.0     200    20.0
3     Faye  2018 Q4  D Inc    DDD    6.0     300    50.0
4      Joe  2019 Q2  A Inc    AAA    NaN     300     NaN
5     Hank  2019 Q2  S Inc    SSS    NaN     100     NaN

But when I do df3 = pd.merge(df1, df2, on=['Date', 'Symbol'], how='left'), I get:

  Investor     Date Name_x Symbol  ...  Income_x  Name_y  Price_y Income_y
0     Mike  2019 Q4  A Inc    AAA  ...       NaN   A Inc      5.0     10.0
1     Bill  2019 Q4  C Inc    CCC  ...       NaN   C Inc     33.0     30.0
2     John  2018 Q4  A Inc    AAA  ...       NaN   A Inc     23.0     20.0
3     Faye  2018 Q4  D Inc    DDD  ...       NaN   D Inc      6.0     50.0
4      Joe  2019 Q2  A Inc    AAA  ...       NaN     NaN      NaN      NaN
5     Hank  2019 Q2  S Inc    SSS  ...       NaN     NaN      NaN      NaN

What am I doing wrong?

df1 = `df1 = {'Investor': {0: 'Mike', 1: 'Bill', 2: 'John', 3: 'Faye', 4: 'Joe', 5: 'Hank'}, 'Date': {0: '2019 Q4', 1: '2019 Q4', 2: '2018 Q4', 3: '2018 Q4', 4: '2019 Q2', 5: '2019 Q2'}, 'Name': {0: 'A Inc', 1: 'C Inc', 2: 'A Inc', 3: 'D Inc', 4: 'A Inc', 5: 'S Inc'}, 'Symbol': {0: 'AAA', 1: 'CCC', 2: 'AAA', 3: 'DDD', 4: 'AAA', 5: 'SSS'}, 'Price': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan}, 'Amount': {0: 100, 1: 200, 2: 200, 3: 300, 4: 300, 5: 100}, 'Income': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: nan}}`
df2 = {'Date': {0: '2019 Q4', 1: '2019 Q4', 2: '2019 Q4', 3: '2019 Q4', 4: '2018 Q4', 5: '2018 Q4', 6: '2018 Q4', 7: '2018 Q4', 8: '2018 Q4'}, 'Name': {0: 'A Inc', 1: 'B Inc', 2: 'C Inc', 3: 'D Inc', 4: 'A Inc', 5: 'B Inc', 6: 'C Inc', 7: 'D Inc', 8: 'E Inc'}, 'Symbol': {0: 'AAA', 1: 'BBB', 2: 'CCC', 3: 'DDD', 4: 'AAA', 5: 'BBB', 6: 'CCC', 7: 'DDD', 8: 'EEE'}, 'Price': {0: 5, 1: 3, 2: 33, 3: 30, 4: 23, 5: 4, 6: 136, 7: 6, 8: 1}, 'Income': {0: 10, 1: 20, 2: 30, 3: 40, 4: 20, 5: 30, 6: 40, 7: 50, 8: 90}}
df3 = pd.merge(df1, df2, on=['Date', 'Symbol'], how='left')

Body:
That's because you have Name, Income, Price on both dataframes. If you don't want the duplicates, you should then select those columns you want:

(df1[['Investor', 'Name', 'Date','Symbol','Amount']]
   .merge(df2.drop('Name', axis=1),
          on=['Date','Symbol'],
          how='left')
)

Output:

  Investor   Name     Date Symbol  Amount  Price  Income
0     Mike  A Inc  2019 Q4    AAA     100    5.0    10.0
1     Bill  C Inc  2019 Q4    CCC     200   33.0    30.0
2     John  A Inc  2018 Q4    AAA     200   23.0    20.0
3     Faye  D Inc  2018 Q4    DDD     300    6.0    50.0
4      Joe  A Inc  2019 Q2    AAA     300    NaN     NaN
5     Hank  S Inc  2019 Q2    SSS     100    NaN     NaN


问:
SqlDataAdapter.SelectCommand not returning the right result
I am just facing a problem with my code.

I want to select some data from a database using the SqlDataAdapter SelectCommand property.

My code looks like:

```<code>static SqlConnection sqlConnection;
static SqlDataAdapter daDBData = new SqlDataAdapter();
static SqlCommand command = new SqlCommand();
static DataSet dsDBData = new DataSet("DBData");
static DataTable tblDBData;
static DataRow drCurrent;

public static DataTable dbDataGet(string tabname, string where)
{
    sqlConnection = dbConnect();    //sqlConnection setup working fine, defined in another method
    string helper = "SELECT * FROM " + tabname + where;
    command = new SqlCommand(helper, sqlConnection);
    daDBData.SelectCommand = command;

    daDBData.MissingSchemaAction = MissingSchemaAction.AddWithKey;
    daDBData.Fill(dsDBData, tabname);

    tblDBData = dsDBData.Tables[tabname];
    return tblDBData;
}
</code>```

My problem is, that in tblDBData all existing rows of my database table will be returned.
What I miss here?

答:
As far as blocks of code go, it's probably fair to say that that one needs a lot of work. Nearly every line has something that could use some improvement but the whole concept that it embodies is fairly objectionable because it is inherently a massive security risk. Here's a minorly improved version:

```<code>//Don't need any of those static variables. Stop making everything static..
//In a properly structured C# program almost NOTHING should be declared as static

        //Method names in C# use PascalCase convention, not camelCase
        public DataTable DbDataGet(string tableName, string whereClause)
        {

            //this could be a massive security risk if there is any way at all that the
            //user can influence the contents of the whereClause. DON'T DO IT if they can
            SqlDataAdapter da = new SqlDataAdapter(
              $"SELECT * FROM {tableName} WHERE {whereClause}",
              GetConnectionString() //in this simplistic context, get a string, not a SqlConnection, then you don't handle disposal
            );

            DataTable dt = new DataTable();

            da.Fill(dt);

            return dt;
        }

</code>```

Yep; all that code you wrote boils down to just 4 lines. It's still a massive problem that you're just tossing a string with a where clause around. The only way you could get away from that with this approach is to start breaking your where string into a set of predicate classes, sql injection protected at the column and operator level, and adding the values to a SqlParameterCollection - it's essentially rolling your own data access library and isn't worth the bother given that many tens of people have already done it (including microsoft)

Consider instead getting away from this awful rabbithole by NOT doing your data access this way at all. Toss it all in the trash and use Dapper instead. It's not a huge learning curve from where you are now, and will do everything in a safer, more secure and easier to use fashion

As a note on the WHERE clause you're saying in the comments that you're using:

```<code>WHERE DATEDIFF(day, sale_date, GetDate()) >= 365 AND available=1
</code>```

Don't do this either. Here you carry out a function operation on an entry of data in the table. If your table has a million dates in, that function will need to be called a million times. It's slow as heck, uses a huge amount of resources and cripples the use of indexes. And it's completely unnecessary. You're looking for all products sold more than a year ago? Calculate ONE DATE of what date it was a year ago and use the SALE_DATE from th tale without any alteration in comparison to it:

```<code>-- in your sql
WHERE sale_date < @someDate and available = 1

//in your c#
mySqlCommand.Parameters.AddWithValue("@someDate", DateTime.UtcNow.AddYears(-1));
</code>```

See the difference? Here the c# calculates the date once, and provides it as a constant value parameter to the query. In a table of a million dates, only one simple compare is performed. We dont' caluclate how many days ago a million different dates were and then select only those diffs > 365

Body:
I am just facing a problem with my code.

I want to select some data from a database using the SqlDataAdapter SelectCommand property.

My code looks like:

static SqlConnection sqlConnection;
static SqlDataAdapter daDBData = new SqlDataAdapter();
static SqlCommand command = new SqlCommand();
static DataSet dsDBData = new DataSet("DBData");
static DataTable tblDBData;
static DataRow drCurrent;

public static DataTable dbDataGet(string tabname, string where)
{
    sqlConnection = dbConnect();    //sqlConnection setup working fine, defined in another method
    string helper = "SELECT * FROM " + tabname + where;
    command = new SqlCommand(helper, sqlConnection);
    daDBData.SelectCommand = command;

    daDBData.MissingSchemaAction = MissingSchemaAction.AddWithKey;
    daDBData.Fill(dsDBData, tabname);

    tblDBData = dsDBData.Tables[tabname];
    return tblDBData;
}

My problem is, that in tblDBData all existing rows of my database table will be returned.
What I miss here?

Body:
As far as blocks of code go, it's probably fair to say that that one needs a lot of work. Nearly every line has something that could use some improvement but the whole concept that it embodies is fairly objectionable because it is inherently a massive security risk. Here's a minorly improved version:

//Don't need any of those static variables. Stop making everything static..
//In a properly structured C# program almost NOTHING should be declared as static

        //Method names in C# use PascalCase convention, not camelCase
        public DataTable DbDataGet(string tableName, string whereClause)
        {

            //this could be a massive security risk if there is any way at all that the
            //user can influence the contents of the whereClause. DON'T DO IT if they can
            SqlDataAdapter da = new SqlDataAdapter(
              $"SELECT * FROM {tableName} WHERE {whereClause}",
              GetConnectionString() //in this simplistic context, get a string, not a SqlConnection, then you don't handle disposal
            );

            DataTable dt = new DataTable();

            da.Fill(dt);

            return dt;
        }

Yep; all that code you wrote boils down to just 4 lines. It's still a massive problem that you're just tossing a string with a where clause around. The only way you could get away from that with this approach is to start breaking your where string into a set of predicate classes, sql injection protected at the column and operator level, and adding the values to a SqlParameterCollection - it's essentially rolling your own data access library and isn't worth the bother given that many tens of people have already done it (including microsoft)

Consider instead getting away from this awful rabbithole by NOT doing your data access this way at all. Toss it all in the trash and use Dapper instead. It's not a huge learning curve from where you are now, and will do everything in a safer, more secure and easier to use fashion

As a note on the WHERE clause you're saying in the comments that you're using:

WHERE DATEDIFF(day, sale_date, GetDate()) >= 365 AND available=1

Don't do this either. Here you carry out a function operation on an entry of data in the table. If your table has a million dates in, that function will need to be called a million times. It's slow as heck, uses a huge amount of resources and cripples the use of indexes. And it's completely unnecessary. You're looking for all products sold more than a year ago? Calculate ONE DATE of what date it was a year ago and use the SALE_DATE from th tale without any alteration in comparison to it:

-- in your sql
WHERE sale_date < @someDate and available = 1

//in your c#
mySqlCommand.Parameters.AddWithValue("@someDate", DateTime.UtcNow.AddYears(-1));

See the difference? Here the c# calculates the date once, and provides it as a constant value parameter to the query. In a table of a million dates, only one simple compare is performed. We dont' caluclate how many days ago a million different dates were and then select only those diffs > 365


问:
Fetching SKProduct Price into UICollectionView Cell Label
I'm facing a issue where when I fetch SKProduct locale price on to the label.text of my UICollectionView, Its displaying correctly, however the prices jump around in different labels depending on how fast the page is being loaded.

TopUpViewController (UICollectionView) -> TopUpMoneyCell (MoneyLabel)

Any idea how to solve this? Currently I'm calling SKProduct in TopUpMoneyCell. I have a array of 4 in app product to be called, each with different value.

Should I call it from TopUpViewController instead? If so, how should I pull the data I got from TopUpViewController to TopUpMoneyCell?

Edit 1: Added UI Mockup, once again thanks for commenting.

View of UI Mockup

答: Take a look at overriding the prepareForReuse() function in your TopUpMoneyCell. In that function, cancel any asynchronous calls that you may have started to load the price.


问:
(Mac) jshell cannot find runtime environment
I am trying to use jshell to learn basic Java behavior. When I use terminal to navigate to the directory where jshell is located:

cd /Library/Java/JavaVirtualMachines/jdk-11.0.6.jdk/Contents/Home/bin

And then type jshell into the command prompt, I get the following error:

Error: Could not find Java SE Runtime Environment.

This is peculiar because java code in my Eclipse IDE (Version: 2019-12 (4.14.0)) compiles and executes just fine on this computer. Also, when I type java -version into terminal it yields the following:

java version "11.0.6" 2020-01-14 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.6+8-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.6+8-LTS, mixed mode)

So clearly the runtime environment is installed, but jshell can't access it for some reason. The best I can figure, I need to find where the JRE is installed and then add it to my $PATH, but I've got not clue how to do this.

答: Silly me. Because I wanted to make the jshell command executable from any directory, I copied (cp) it to my bin. However, this caused the command "jshell" to override any attempt to execute jshell from within the directory where it was originally installed. I deleted it from my bin and now it works fine. </p>


问:
'Unable to merge dex' error in Android Studio when adding a specific compile in dependencies
I'm trying to add a specific module into my Android project (this one over here: https://github.com/danysantiago/sendgrid-android), but while the project seems to build correctly, I get the following error when I try to run the project:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

I'm able to confirm that it's this specific module that is causing the error, since the project works if I comment the following line out of the gradle:

```<code>compile 'com.github.danysantiago:sendgrid-android:1'
</code>```

What I've tried so far:

I've cleaned and rebuilt the project.

Added multiDexEnabled true to android{defaultConfig{}}

Added implementation 'com.android.support:multidex:1.0.2' to
dependencies{}

Unfortunately, none of those items worked, and I wasn't able to find any other solutions on StackOverflow that solved the issue. Any help with this issue would be greatly appreciated!

答:
There is a new Android SendGrid library utilising Sendgrid's v3 API.
The updated library negates the issues when implementing older libraries into applications that target newer Android API version.

The library can be imported with jitpack

```<code>allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

dependencies {
     implementation 'com.github.jakebreen:android-sendgrid:1.2.2'
}
</code>```

https://github.com/Jakebreen/android-sendgrid

Body:
I'm trying to add a specific module into my Android project (this one over here: https://github.com/danysantiago/sendgrid-android), but while the project seems to build correctly, I get the following error when I try to run the project:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

I'm able to confirm that it's this specific module that is causing the error, since the project works if I comment the following line out of the gradle:

compile 'com.github.danysantiago:sendgrid-android:1'

What I've tried so far:

I've cleaned and rebuilt the project.

Added multiDexEnabled true to android{defaultConfig{}}

Added implementation 'com.android.support:multidex:1.0.2' to
dependencies{}

Unfortunately, none of those items worked, and I wasn't able to find any other solutions on StackOverflow that solved the issue. Any help with this issue would be greatly appreciated!

Body:
There is a new Android SendGrid library utilising Sendgrid's v3 API.
The updated library negates the issues when implementing older libraries into applications that target newer Android API version.

The library can be imported with jitpack

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

dependencies {
     implementation 'com.github.jakebreen:android-sendgrid:1.2.2'
}

https://github.com/Jakebreen/android-sendgrid