Title: For keywords(strings) in one column and values(floats) in another, I want to count the number ok keywords that fall per unit range of the value

Body:
I have a dataframe:

            keyword     val
    0   nt              0.93
    1   atm             0.94
    2   bank            1.00
    3   long            1.02
    4   number          1.11
    5   get             2.20
    6   money           3.50
    7   account         3.80
    8   deposit         3.90
    9   card            5.00
    10  credit          0.8
    11  debit           1.23

I want to find out the number of keywords per unit range of value
ie from 0.9-1 => [nt,atm]=>2
   from 1-1.1 => [bank,long,number] =>3 and so on

Body:
Use pd.cut() here with groupby():

bins=[0,1,2,3,5]

df.groupby(pd.cut(df.val,bins)).keyword.apply(list)

val
(0, 1]                    [nt, atm, bank]
(1, 2]                     [long, number]
(2, 3]                              [get]
(3, 5]    [money, account, deposit, card]

For count use:

df.groupby(pd.cut(df.val,bins)).keyword.size()

val
(0, 1]    3
(1, 2]    2
(2, 3]    1
(3, 5]    4

You can customize your bins like:

bins=[0,0.99,1,1.99,2,2.99,3,3.99,4,4.99,5]
df.groupby(pd.cut(df.val,bins)).keyword.size()

val
(0.0, 0.99]    2
(0.99, 1.0]    1
(1.0, 1.99]    2
(1.99, 2.0]    0
(2.0, 2.99]    1
(2.99, 3.0]    0
(3.0, 3.99]    3
(3.99, 4.0]    0
(4.0, 4.99]    0
(4.99, 5.0]    1


来源: stackexchange

问:
Arxiv API not taking the whole query terms
I am using arxiv API for scholarly papers search using python. For single term query arxiv API working perfectly well but for multi-term query (Key-phrase), API only took first term.

For example :

```<code> import urllib.request as ur
 from bs4 import BeautifulSoup

 url = 'http://export.arxiv.org/api/query?search_query=all:electron'
 s = ur.urlopen(url)
 sl = s.read()
 soup = BeautifulSoup(sl, 'html.parser')
 papers=[soup.find_all('title')]
 print(soup)
</code>```

Output(print the soup variable)

Here I used query term electron, Arxiv API search also electron term (highlighted).

But I used query term say quantum complexity of a black hole, arxiv API only took the first word (quantum).

```<code>import urllib.request as ur
from bs4 import BeautifulSoup

url = 'http://export.arxiv.org/api/query?search_query=all:quantum complexity of a black hole'
#url='http://export.arxiv.org/api/query?search_query=ti:"quantum complexity of a black hole"&sortBy=lastUpdatedDate&sortOrder=ascending'
s = ur.urlopen(url)
sl = s.read()
soup = BeautifulSoup(sl, 'html.parser')
print(soup)
</code>```

Output:

How can I search using whole key-words (quantum complexity of a black hole) so that it will return the scholarly papers that contain those key-words?

答:
You will have to encode your query params</p>

```<code>import urllib.parse
import urllib.request as ur
from bs4 import BeautifulSoup
query = urllib.parse.quote("all:quantum complexity of a black holeu")
url = 'http://export.arxiv.org/api/query?search_query=' + query
s = ur.urlopen(url)
sl = s.read()
soup = BeautifulSoup(sl, 'html.parser')
print(soup)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using arxiv API for scholarly papers search using python. For single term query arxiv API working perfectly well but for multi-term query (Key-phrase), API only took first term.

For example :

 import urllib.request as ur
 from bs4 import BeautifulSoup

 url = 'http://export.arxiv.org/api/query?search_query=all:electron'
 s = ur.urlopen(url)
 sl = s.read()
 soup = BeautifulSoup(sl, 'html.parser')
 papers=[soup.find_all('title')]
 print(soup)

Output(print the soup variable)

Here I used query term electron, Arxiv API search also electron term (highlighted).

But I used query term say quantum complexity of a black hole, arxiv API only took the first word (quantum).

import urllib.request as ur
from bs4 import BeautifulSoup

url = 'http://export.arxiv.org/api/query?search_query=all:quantum complexity of a black hole'
#url='http://export.arxiv.org/api/query?search_query=ti:"quantum complexity of a black hole"&sortBy=lastUpdatedDate&sortOrder=ascending'
s = ur.urlopen(url)
sl = s.read()
soup = BeautifulSoup(sl, 'html.parser')
print(soup)

Output:

How can I search using whole key-words (quantum complexity of a black hole) so that it will return the scholarly papers that contain those key-words?

Body:
You will have to encode your query params

import urllib.parse
import urllib.request as ur
from bs4 import BeautifulSoup
query = urllib.parse.quote("all:quantum complexity of a black holeu")
url = 'http://export.arxiv.org/api/query?search_query=' + query
s = ur.urlopen(url)
sl = s.read()
soup = BeautifulSoup(sl, 'html.parser')
print(soup)


问:
How to fix weird formatting when printing arrays, using \t
I'm working on a code which prints an array of locations, either in ascending or descending order. However, the formatting is all wrong for two out of 12 locations.

Code:

```<code>import java.util.*;
import static java.lang.System.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
class airwaysReservation {
    static Scanner sc = new Scanner(System.in);
    static String src[] = {"Mumbai", "London", "Hiroshima", "Lagos", "Minsk", "Baghdad", "Istanbul", "Delhi", "Fez", "Beijing", "Taipei", "Havana"};
    static String dest[] = {"Hyderabad", "Paris", "Athens", "Alexandria", "Seoul", "Hamburg", "Bengaluru", "Rome", "Montreal", "Saitama", "Philadelphia", "Pune"};
    public static void sortAsc(String arr[]) {
        Arrays.sort(arr);
    }
    public static void sortDesc(String arr[]) {
        //using libraries java.util.Arrays, and java.util.Collections, sorts arrays
        Arrays.sort(arr, Collections.reverseOrder());
    }
    public static void list() {
        out.println("Sources \t Destinations");
        for (int i = 0; i< 12; i++) {
            out.println(src[i] + "\t \t  " + dest[i]);
        }
    }
    public static void main(String[] args) {
        out.println("Welcome \n Would you like to see the sources in ascending, or descending order?");
        // stores ascending or descending for later
        char schoice = sc.next().charAt(0);
        out.println("Would you like to view the destinations in ascending, or descending order?");
        // stores ascending or descending for later
        char dchoice = sc.next().charAt(0);
        switch (schoice) {
            case 'a' :
            sortAsc(src);
            break;
            case 'd' :
            sortDesc(src);
            break;
            default:
            out.println("Invalid choice");
        }
        switch (dchoice) {
            case 'a' :
            sortAsc(dest);
            break;
            case 'd' :
            sortDesc(dest);
            break;
            default:
            out.println("Invalid choice");
        }
        list();
    }
}
</code>```

The output for this, choosing ascending and then descending comes out to be:

```<code>Sources      Destinations
Baghdad       Seoul
Beijing       Saitama
Delhi         Rome
Fez       Pune
Havana        Philadelphia
Hiroshima         Paris
Istanbul          Montreal
Lagos         Hyderabad
London        Hamburg
Minsk         Bengaluru
Mumbai        Athens
Taipei        Alexandria
</code>```

I have a feeling this issue is because of different word lengths, however, that doesn't seem to affect the last few lines (eg Minsk and Bengaluru).
How would I go about making all the destinations start from the same vertical line?
Any help will be appreciated, thanks!

答:
Notice it only affects lines where the first word is 8 characters or more.  A \t advances to the next tab position, which is usually at a multiple of 8 characters.

To do this correctly you must make a pass over the first words to find the maximum length, then use that when printing to insert the correct number of spaces after every word.

For example, if you determine that the longest first word is 13 characters, and you want to have the second word start in at offset 16 (position 17), you would print the first word in a fixed field of length 16.

Body:
I'm working on a code which prints an array of locations, either in ascending or descending order. However, the formatting is all wrong for two out of 12 locations.

Code:

import java.util.*;
import static java.lang.System.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
class airwaysReservation {
    static Scanner sc = new Scanner(System.in);
    static String src[] = {"Mumbai", "London", "Hiroshima", "Lagos", "Minsk", "Baghdad", "Istanbul", "Delhi", "Fez", "Beijing", "Taipei", "Havana"};
    static String dest[] = {"Hyderabad", "Paris", "Athens", "Alexandria", "Seoul", "Hamburg", "Bengaluru", "Rome", "Montreal", "Saitama", "Philadelphia", "Pune"};
    public static void sortAsc(String arr[]) {
        Arrays.sort(arr);
    }
    public static void sortDesc(String arr[]) {
        //using libraries java.util.Arrays, and java.util.Collections, sorts arrays
        Arrays.sort(arr, Collections.reverseOrder());
    }
    public static void list() {
        out.println("Sources \t Destinations");
        for (int i = 0; i< 12; i++) {
            out.println(src[i] + "\t \t  " + dest[i]);
        }
    }
    public static void main(String[] args) {
        out.println("Welcome \n Would you like to see the sources in ascending, or descending order?");
        // stores ascending or descending for later
        char schoice = sc.next().charAt(0);
        out.println("Would you like to view the destinations in ascending, or descending order?");
        // stores ascending or descending for later
        char dchoice = sc.next().charAt(0);
        switch (schoice) {
            case 'a' :
            sortAsc(src);
            break;
            case 'd' :
            sortDesc(src);
            break;
            default:
            out.println("Invalid choice");
        }
        switch (dchoice) {
            case 'a' :
            sortAsc(dest);
            break;
            case 'd' :
            sortDesc(dest);
            break;
            default:
            out.println("Invalid choice");
        }
        list();
    }
}

The output for this, choosing ascending and then descending comes out to be:

Sources      Destinations
Baghdad       Seoul
Beijing       Saitama
Delhi         Rome
Fez       Pune
Havana        Philadelphia
Hiroshima         Paris
Istanbul          Montreal
Lagos         Hyderabad
London        Hamburg
Minsk         Bengaluru
Mumbai        Athens
Taipei        Alexandria

I have a feeling this issue is because of different word lengths, however, that doesn't seem to affect the last few lines (eg Minsk and Bengaluru).
How would I go about making all the destinations start from the same vertical line?
Any help will be appreciated, thanks!


问:
Magento2: Crosssell products on order success page
I need some references or code for how to show Crosssell products on the order success page.

I put cross-sell block codes inside 'checkout_onepage_success.xml'.
I tried below code

```<code><?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>Success Page</title>
    </head>
    <body>
        <referenceBlock name="page.main.title">
            <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success.print.button" template="Magento_Checkout::button.phtml"/>
            <action method="setPageTitle">
                <argument translate="true" name="title" xsi:type="string">Thank you for your purchase!</argument>
            </action>
        </referenceBlock>
        <referenceContainer name="content">
            <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success" template="Magento_Checkout::success.phtml" cacheable="false">
                <container name="order.success.additional.info" label="Order Success Additional Info"/>
            </block>
            <block class="Magento\Checkout\Block\Registration" name="checkout.registration" template="Magento_Checkout::registration.phtml" cacheable="false"/>
        </referenceContainer>

        <block class="Magento\Checkout\Block\Cart\Crosssell" name="checkout.cart.crosssell" template="Magento_Catalog::product/list/items.phtml" cacheable="false">
            <arguments>
                <argument name="type" xsi:type="string">crosssell</argument>
            </arguments>
            <block class="Magento\Catalog\Block\Product\ProductList\Item\Container" name="crosssell.product.addto" as="addto">
                <block class="Magento\Catalog\Block\Product\ProductList\Item\AddTo\Compare"
                       name="crosssell.product.addto.compare" as="compare"
                       template="Magento_Catalog::product/list/addto/compare.phtml"/>
            </block>
        </block>

    </body>
</page>
</code>```

答:
You need to call Crosssell block inside content referenceContainer displays as follows:

```<code><body>
    <referenceBlock name="page.main.title">
        <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success.print.button" template="Magento_Checkout::button.phtml"/>
        <action method="setPageTitle">
            <argument translate="true" name="title" xsi:type="string">Thank you for your purchase!</argument>
        </action>
    </referenceBlock>
    <referenceContainer name="content">
        <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success" template="Magento_Checkout::success.phtml" cacheable="false">
            <container name="order.success.additional.info" label="Order Success Additional Info"/>
        </block>
        <block class="Magento\Checkout\Block\Registration" name="checkout.registration" template="Magento_Checkout::registration.phtml" cacheable="false"/>
        <block class="Magento\Checkout\Block\Cart\Crosssell" name="checkout.cart.crosssell" template="Magento_Catalog::product/list/items.phtml" cacheable="false">
            <arguments>
                <argument name="type" xsi:type="string">crosssell</argument>
            </arguments>
            <block class="Magento\Catalog\Block\Product\ProductList\Item\Container" name="crosssell.product.addto" as="addto">
                <block class="Magento\Catalog\Block\Product\ProductList\Item\AddTo\Compare"
               name="crosssell.product.addto.compare" as="compare"
               template="Magento_Catalog::product/list/addto/compare.phtml"/>
            </block>
        </block>
    </referenceContainer>
</body>
</code>```

Hope this may helpful to you!

Body:
I need some references or code for how to show Crosssell products on the order success page.

I put cross-sell block codes inside 'checkout_onepage_success.xml'.
I tried below code

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <title>Success Page</title>

        <referenceBlock name="page.main.title">
            <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success.print.button" template="Magento_Checkout::button.phtml"/>
            <action method="setPageTitle">
                <argument translate="true" name="title" xsi:type="string">Thank you for your purchase!</argument>
            </action>
        </referenceBlock>
        <referenceContainer name="content">
            <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success" template="Magento_Checkout::success.phtml" cacheable="false">
                <container name="order.success.additional.info" label="Order Success Additional Info"/>
            </block>
            <block class="Magento\Checkout\Block\Registration" name="checkout.registration" template="Magento_Checkout::registration.phtml" cacheable="false"/>
        </referenceContainer>

        <block class="Magento\Checkout\Block\Cart\Crosssell" name="checkout.cart.crosssell" template="Magento_Catalog::product/list/items.phtml" cacheable="false">
            <arguments>
                <argument name="type" xsi:type="string">crosssell</argument>
            </arguments>
            <block class="Magento\Catalog\Block\Product\ProductList\Item\Container" name="crosssell.product.addto" as="addto">
                <block class="Magento\Catalog\Block\Product\ProductList\Item\AddTo\Compare"
                       name="crosssell.product.addto.compare" as="compare"
                       template="Magento_Catalog::product/list/addto/compare.phtml"/>
            </block>
        </block>

</page>

Body:
You need to call Crosssell block inside content referenceContainer displays as follows:

<body>
    <referenceBlock name="page.main.title">
        <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success.print.button" template="Magento_Checkout::button.phtml"/>
        <action method="setPageTitle">
            <argument translate="true" name="title" xsi:type="string">Thank you for your purchase!</argument>
        </action>
    </referenceBlock>
    <referenceContainer name="content">
        <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success" template="Magento_Checkout::success.phtml" cacheable="false">
            <container name="order.success.additional.info" label="Order Success Additional Info"/>
        </block>
        <block class="Magento\Checkout\Block\Registration" name="checkout.registration" template="Magento_Checkout::registration.phtml" cacheable="false"/>
        <block class="Magento\Checkout\Block\Cart\Crosssell" name="checkout.cart.crosssell" template="Magento_Catalog::product/list/items.phtml" cacheable="false">
            <arguments>
                <argument name="type" xsi:type="string">crosssell</argument>
            </arguments>
            <block class="Magento\Catalog\Block\Product\ProductList\Item\Container" name="crosssell.product.addto" as="addto">
                <block class="Magento\Catalog\Block\Product\ProductList\Item\AddTo\Compare"
               name="crosssell.product.addto.compare" as="compare"
               template="Magento_Catalog::product/list/addto/compare.phtml"/>
            </block>
        </block>
    </referenceContainer>
</body>

Hope this may helpful to you!


问:
I am getting multiple calls from angular to the Post API in Node
I am trying to write a file from the data from the database but I'm getting multiple calls from the angular causing multiple entries of the same data.How can I stop that? And also it is causing to override write file after some time.

I am not getting what exactly should I do. I have tried subscribing thing in service in angular but it was of no help.
component.ts

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { CountryService } from './country.service';
import { ConfigService } from '../config.service';

@Component({
  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: []
})
export class CountryComponent implements OnInit {
  public modalRef: NgbModalRef;
  public form: FormGroup;
  public selectedCountry;
  public countries;
  constructor(public fb: FormBuilder, public toastrService: ToastrService,
    public modalService: NgbModal, public configService: ConfigService,
    public countryService: CountryService) {

  }

  ngOnInit() {
    this.form = this.fb.group({
      country: [null, Validators.compose([Validators.required])],
    });
    this.getCountries();
  }

  public getCountries() {
    this.countryService.getCountries((data) => {
      this.countries = data.countries;
    }, (err) => { });
  }

  public selectCountry(country) {
    this.countryService.selectCountry(country, (resp) => {
    }, (err) => { });
  }
}
</code>```

service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ConfigService } from '../config.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class CountryService {
  private setHeaders() {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    return headers;
  }
  constructor(private configService: ConfigService, public http: HttpClient, public toastrService: ToastrService) { }

  selectCountry(country: any, callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.post(this.configService.url + '/selectedCountry', country, options).subscribe((resp: any) => {
      callback(resp);
    }, err => {
      errCallback(err);
    });
  }

  getCountries(callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.get(this.configService.url + '/countries', options).subscribe((resp: any) => {
         callback(resp.msg);
    }, err => {
      errCallback(err);
    });
  }

}
</code>```

I want the call to be sent only once, not twice

答:
Try this:</p>

```<code>// Somewhere on init
let postRequestCount = 0;

// More stuff …

// Just before doing the POST request inside the `selectCountry` method
if(postRequestCount < 1) {
    http.post(); // TODO : Replace with the actual `post` method
}
postRequestCount++;
</code>```

Body:
I am trying to write a file from the data from the database but I'm getting multiple calls from the angular causing multiple entries of the same data.How can I stop that? And also it is causing to override write file after some time.

I am not getting what exactly should I do. I have tried subscribing thing in service in angular but it was of no help.
component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { CountryService } from './country.service';
import { ConfigService } from '../config.service';

@Component({
  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: []
})
export class CountryComponent implements OnInit {
  public modalRef: NgbModalRef;
  public form: FormGroup;
  public selectedCountry;
  public countries;
  constructor(public fb: FormBuilder, public toastrService: ToastrService,
    public modalService: NgbModal, public configService: ConfigService,
    public countryService: CountryService) {

  }

  ngOnInit() {
    this.form = this.fb.group({
      country: [null, Validators.compose([Validators.required])],
    });
    this.getCountries();
  }

  public getCountries() {
    this.countryService.getCountries((data) => {
      this.countries = data.countries;
    }, (err) => { });
  }

  public selectCountry(country) {
    this.countryService.selectCountry(country, (resp) => {
    }, (err) => { });
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ConfigService } from '../config.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class CountryService {
  private setHeaders() {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    return headers;
  }
  constructor(private configService: ConfigService, public http: HttpClient, public toastrService: ToastrService) { }

  selectCountry(country: any, callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.post(this.configService.url + '/selectedCountry', country, options).subscribe((resp: any) => {
      callback(resp);
    }, err => {
      errCallback(err);
    });
  }

  getCountries(callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.get(this.configService.url + '/countries', options).subscribe((resp: any) => {
         callback(resp.msg);
    }, err => {
      errCallback(err);
    });
  }

}

I want the call to be sent only once, not twice

Body:
Try this:

// Somewhere on init
let postRequestCount = 0;

// More stuff …

// Just before doing the POST request inside the `selectCountry` method
if(postRequestCount < 1) {
    http.post(); // TODO : Replace with the actual `post` method
}
postRequestCount++;


问:
iTextSharp - XFA fill date/time field
The workflow is like this:

we download a template form, prefill values which will be static, export a XML template

the XML is parsed with a .NET forms app, dynamic values are added

the resulting XML needs to be imported back into the PDF template

All goes well using the MergeXfaData method on iTextSharp, however for some reason, date/time fields are not being filled in (textfields and checkboxes work ok). Cannot figure out why. Searching through forums I discovered someone saying XFA only works for textfields. Why is this and how to work around?

Also as a next step I will need to attach an attachment to the PDF form. The attachments are also PDF but iTextSharp would not attach them. Have searched many forums but none of the mentioned methods works for me.

Thank you for your answers

答:
@Yuri, I just tried it with a date/time field and it worked perfectly. I create a simple PDF in Live Cycle with two fields, 1 text and 1 date/time, and two buttons, Submit and Print. The sample PDF is here:

I filled out the form and got this for XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<topmostSubform>
    <Text1>Chris</Text1>
    <DateTimeField1>2012-04-12</DateTimeField1>
</topmostSubform>
</code>```

When I imported it into the PDF and viewed the PDF in Acrobat the date/time field was filled out. I'm using iTextSharp 5.0.5.0 with the following code:

```<code>Option Explicit On
Option Strict On

Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim PDF_Input_File As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "Input.pdf")
        Dim PDF_Output_File As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "Export.pdf")

        ''//Create our reader
        Dim reader As New PdfReader(PDF_Input_File)
        ''//Create our file stream to output to
        Using FS As New System.IO.FileStream(PDF_Output_File, FileMode.Create, FileAccess.Write, FileShare.Read)
            ''//Create the stamper
            Dim stamper As New PdfStamper(reader, FS)

            ''//Just loading the XML raw instead of reading from disk, less files to attach to the post
            Dim Bytes = System.Text.Encoding.UTF8.GetBytes("<?xml version=""1.0"" encoding=""UTF-8""?><topmostSubform><Text1>Chris</Text1><DateTimeField1>2012-04-12</DateTimeField1></topmostSubform>")
            Using MS As New MemoryStream(Bytes)
                ''//Fill out the form
                stamper.AcroFields.Xfa.FillXfaForm(MS)
            End Using

            stamper.Close()
        End Using

        reader.Close()

        Me.Close()
    End Sub
End Class
</code>```

ContentLicense: CC BY-SA 3.0

Title: iTextSharp - XFA fill date/time field

Body:
@Yuri, I just tried it with a date/time field and it worked perfectly. I create a simple PDF in Live Cycle with two fields, 1 text and 1 date/time, and two buttons, Submit and Print. The sample PDF is here:

I filled out the form and got this for XML:

<?xml version="1.0" encoding="UTF-8"?>
<topmostSubform>
    <Text1>Chris</Text1>
    <DateTimeField1>2012-04-12</DateTimeField1>
</topmostSubform>

When I imported it into the PDF and viewed the PDF in Acrobat the date/time field was filled out. I'm using iTextSharp 5.0.5.0 with the following code:

Option Explicit On
Option Strict On

Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim PDF_Input_File As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "Input.pdf")
        Dim PDF_Output_File As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "Export.pdf")

        ''//Create our reader
        Dim reader As New PdfReader(PDF_Input_File)
        ''//Create our file stream to output to
        Using FS As New System.IO.FileStream(PDF_Output_File, FileMode.Create, FileAccess.Write, FileShare.Read)
            ''//Create the stamper
            Dim stamper As New PdfStamper(reader, FS)

            ''//Just loading the XML raw instead of reading from disk, less files to attach to the post
            Dim Bytes = System.Text.Encoding.UTF8.GetBytes("<?xml version=""1.0"" encoding=""UTF-8""?><topmostSubform><Text1>Chris</Text1><DateTimeField1>2012-04-12</DateTimeField1></topmostSubform>")
            Using MS As New MemoryStream(Bytes)
                ''//Fill out the form
                stamper.AcroFields.Xfa.FillXfaForm(MS)
            End Using

            stamper.Close()
        End Using

        reader.Close()

        Me.Close()
    End Sub
End Class


问:
nodejs - DataCloneError: function () { [native code] } could not be cloned
I'm trying to spawn threads (using the new Nodejs module 'worker_threads') and pass to each of them a complex object which is the 'page' object of a Puppeteer browser.newPage() instance. I tried both using workerData and MessageChannels - which, from docs:

port.postMessage: Sends a JavaScript value to the receiving side of this channel. value will be transferred in a way which is compatible with the HTML structured clone algorithm. In particular, it may contain circular references and objects like typed arrays that the JSON API is not able to stringify.

but I always get the error:

(node:7133) UnhandledPromiseRejectionWarning: DataCloneError: function () { [native code] } could not be cloned.
      at Worker.postMessage (internal/worker.js:378:23)

I also tried to stringify it and parse it but the page object also contains functions which I couldn't get to evaluate from the threads context (I also would like to avoid using eval()).

The question is: how do I pass a complex object like Puppeteer browser.newPage() instance to the threads spawned with worker_threads in Nodejs?

答:
dethSwathch is right about that: You can't. Message passing is only allowed for some few native data types, including Object (and Date and of course TypedArrays). That is why you lose all type information and functions. However, you can certainly use the "naked" object to just fill a new Page instance (or any other custom object).

This DataCloneError seems to be a limitation of the past. At least I couldn't reproduce it. The object should be copied automatically without any serialization.


答:
Have you tried String.format("%-12s %-12s", source, destination) ? This will allocate 12 characters for each string, but if you feel that you need more, go ahead and change each 12 to suit your needs.

Here is what I tried to demo it:

```<code>public static void main(String[] args) {
    String [][] arr = {
            { "Sources",      "Destinations" },
            { "Baghdad",       "Seoul" },
            { "Beijing",       "Saitama" },
            { "Delhi",         "Rome" },
            { "Fez",       "Pune" },
            { "Havana",        "Philadelphia" },
            { "Hiroshima",         "Paris" },
            { "Istanbul",          "Montreal" },
            { "Lagos",         "Hyderabad" },
            { "London",        "Hamburg" },
            { "Minsk",         "Bengaluru" },
            { "Mumbai",        "Athens" },
            { "Taipei",        "Alexandria" }
    };
    for (String[] a : arr) {
        System.out.printf("%-12s %-12s \n", a[0], a[1]);
    }
}
</code>```

Getting output:

```<code>Sources      Destinations
Baghdad      Seoul
Beijing      Saitama
Delhi        Rome
Fez          Pune
Havana       Philadelphia
Hiroshima    Paris
Istanbul     Montreal
Lagos        Hyderabad
London       Hamburg
Minsk        Bengaluru
Mumbai       Athens
Taipei       Alexandria
</code>```

Title: How to fix weird formatting when printing arrays, using \t

Body:
Have you tried String.format("%-12s %-12s", source, destination) ? This will allocate 12 characters for each string, but if you feel that you need more, go ahead and change each 12 to suit your needs.

Here is what I tried to demo it:

public static void main(String[] args) {
    String [][] arr = {
            { "Sources",      "Destinations" },
            { "Baghdad",       "Seoul" },
            { "Beijing",       "Saitama" },
            { "Delhi",         "Rome" },
            { "Fez",       "Pune" },
            { "Havana",        "Philadelphia" },
            { "Hiroshima",         "Paris" },
            { "Istanbul",          "Montreal" },
            { "Lagos",         "Hyderabad" },
            { "London",        "Hamburg" },
            { "Minsk",         "Bengaluru" },
            { "Mumbai",        "Athens" },
            { "Taipei",        "Alexandria" }
    };
    for (String[] a : arr) {
        System.out.printf("%-12s %-12s \n", a[0], a[1]);
    }
}

Getting output:

Sources      Destinations
Baghdad      Seoul
Beijing      Saitama
Delhi        Rome
Fez          Pune
Havana       Philadelphia
Hiroshima    Paris
Istanbul     Montreal
Lagos        Hyderabad
London       Hamburg
Minsk        Bengaluru
Mumbai       Athens
Taipei       Alexandria


问:
Data has been deleted from database but table row not removed and total record not reduced in php using ajax
Data is Deleted database but table row not removed and total not reduced php ajax
I am creating an e-commerce site for my final year project. I am running into the problem with delete the product. if I delete product has been deleted from database success. but final total didn’t reduce and table row not removed what I tried so far I attached below along with screenshot image below.

Table

```<code><div class="container">
                <table class="table table-striped" id="mytable">
                    <thead>
                    <tr>
                        <th>ProductID</th>
                        <th>Productname</th>
                        <th>Price</th>
                        <th>Qty</th>
                        <th>Amount</th>
                        <th>Delete</th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>

        </div>

        <div style='text-align: right; margin:10px'>
            <label><h3>Total amount: </h3></label>
            <span style="font-size: 40px; color: #ff0911" id='total-amount'></span>
        </div>
</code>```

Display the Products

```<code><script>
getProducts();
function getProducts() {
    $.ajax({
        type: 'GET',
        url: 'all_cart.php',
        dataType: 'JSON',
        success: function(data) {
            data.forEach(function(element) {
                var id = element.id;
                var product_name = element.product_name;
                var price = element.price;
                $('#mytable tbody').after
                (
                    '<tr> ' +
                    '<td>' + id + '</td>' +
                    '<td>' + product_name + '</td>' +
                    '<td>' + price + '</td>' +
                    "<input type='hidden' class='price' name='price' value='" + price + "'>" +
                    '<td>' + "<input type = 'text' class='qty' name='qty' value='1'/>" + '</td>' +
                    '<td>' + "<input type = 'text' class='amount' id='amount' disabled/>" + '</td>' +

                    '<td>' +  " <Button type='button' class='btn btn-primary' onclick='deleteProduct(this," + id + ")' >Delete</Button> " + '</td>' +
                    '</tr>');
            });
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}
</code>```

Calculating the Total

```<code>$(function() {
    $(".price, .qty").on("keydown keyup click", function () {
        var price = $(this).parents('tr').find('.price');
        var qty= $(this).parents('tr').find('.qty');
        var sum = (
        Number($(price).val()) * Number($(qty).val())
        );
        $(this).parents('tr').find('.amount').val(sum);
        calculateAmount();
    });
});

function calculateAmount() {
    var total = 0;
    $('.amount').each(function(e){
        total += Number($(this).val());
    });
    $('#total-amount').text(total);
}
</code>```

delete product function

```<code>function deleteProduct(event, id) {
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                        $(event).parent('tr').remove();
                        calculateAmount();
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });
}
</code>```

remove.php

```<code><?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include "db.php";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $stmt = $conn->prepare("delete from cart where id=?");
    $stmt->bind_param("s", $id);
    $id = $_POST["id"];
    if ($stmt->execute())
        {
            echo 1;
        }
    else
        {
                echo 0;
        }
        $stmt->close();
        }
?>
</code>```

答:
You may use logic like:

While displaying products (edit the line, just assign dynamic id to tr tag)-

```<code>....
'<tr id=tr_'+id+'> ' +
....
</code>```

& in delete product function (remove relevant tr using id)-

```<code>....
$('#tr_'+id).remove();
....
</code>```

In your code...

Diplay products function-

```<code><script>
getProducts();
function getProducts() {
    $.ajax({
        type: 'GET',
        url: 'all_cart.php',
        dataType: 'JSON',
        success: function(data) {
            data.forEach(function(element) {
                var id = element.id;
                var product_name = element.product_name;
                var price = element.price;
                $('#mytable tbody').after
                (
                    '<tr id=tr_'+id+'> ' +
                    '<td>' + id + '</td>' +
                    '<td>' + product_name + '</td>' +
                    '<td>' + price + '</td>' +
                    "<input type='hidden' class='price' name='price' value='" + price + "'>" +
                    '<td>' + "<input type = 'text' class='qty' name='qty' value='1'/>" + '</td>' +
                    '<td>' + "<input type = 'text' class='amount' id='amount' disabled/>" + '</td>' +

                    '<td>' +  " <Button type='button' class='btn btn-primary' onclick='deleteProduct(this," + id + ")' >Delete</Button> " + '</td>' +
                    '</tr>');
            });
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });
</code>```

& in delete function-

```<code>function deleteProduct(event, id) {
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                        //$(event).parent('tr').remove();
                        $('#tr_'+id).remove();
                        calculateAmount();
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });
}
</code>```

I am just explaining the logic.. but you need to go in detail to adjust the remaining rhings.. :)

Body:
Data is Deleted database but table row not removed and total not reduced php ajax
I am creating an e-commerce site for my final year project. I am running into the problem with delete the product. if I delete product has been deleted from database success. but final total didn’t reduce and table row not removed what I tried so far I attached below along with screenshot image below.

Table

                        ProductID
                        Productname
                        Price
                        Qty
                        Amount
                        Delete

Total amount:

Display the Products

Body:
You may use logic like:

While displaying products (edit the line, just assign dynamic id to tr tag)-

....
'<tr id=tr_'+id+'> ' +
....

& in delete product function (remove relevant tr using id)-

....
$('#tr_'+id).remove();
....

In your code...

Diplay products function-

<script>
getProducts();
function getProducts() {
    $.ajax({
        type: 'GET',
        url: 'all_cart.php',
        dataType: 'JSON',
        success: function(data) {
            data.forEach(function(element) {
                var id = element.id;
                var product_name = element.product_name;
                var price = element.price;
                $('#mytable tbody').after
                (
                    '<tr id=tr_'+id+'> ' +
                    '<td>' + id + '</td>' +
                    '<td>' + product_name + '</td>' +
                    '<td>' + price + '</td>' +
                    "<input type='hidden' class='price' name='price' value='" + price + "'>" +
                    '<td>' + "<input type = 'text' class='qty' name='qty' value='1'/>" + '</td>' +
                    '<td>' + "<input type = 'text' class='amount' id='amount' disabled/>" + '</td>' +

                    '<td>' +  " <Button type='button' class='btn btn-primary' onclick='deleteProduct(this," + id + ")' >Delete</Button> " + '</td>' +
                    '</tr>');
            });
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });

& in delete function-

function deleteProduct(event, id) {
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                        //$(event).parent('tr').remove();
                        $('#tr_'+id).remove();
                        calculateAmount();
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });
}

I am just explaining the logic.. but you need to go in detail to adjust the remaining rhings.. :)


问:
Issues bruteforcing password with python
I am working on some code for an assignment that it's supposed to brute-force a zip file. I was provided the first word of the password and I know that it has 3 more alphabet characters including uppercase and lowercase.

I am able to print each one of those combinations, but it seems to not find the password. Can somebody take a look at my code and see if you find a bug or something?

import zipfile
import itertools
import time

# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
    try:
        zip_file.extractall(pwd=password)
        return True
    except KeyboardInterrupt:
        exit(0)
    except Exception:
        pass

# Main code starts here...
# The file name of the zip file.
zipfilename = 'planz.zip'
# The first part of the password. We know this for sure!
first_half_password = 'Super'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
zip_file = zipfile.ZipFile(zipfilename)

# We know they always have 3 characters after Super...
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
    # Slowing it down on purpose to make it work better with the web terminal
    # Remove at your peril
    time.sleep(0.009)
    # Add the three letters to the first half of the password.
    password = first_half_password+''.join(c)
    # Try to extract the file.
    print ("Trying: %s" % password)
    # If the file was extracted, you found the right password.
    if extractFile(zip_file, password):
        print ('*' * 20)
        print ('Password found: %s' % password)
        print ('Files extracted...')
        exit(0)

# If no password was found by the end, let us know!
print ('Password not found.')
```

I expect the program to find the password which it should be Super + 3 more alphabet characters.

答:
The zip_file.extractall(pwd=password) is expecting a password in the form of bytes, not a string. Thus, since a string is passed in as the password, the try/except block within extractFile is always triggered, thus the password is never found. I have updated your code to include a byte conversion from a string for the password:

```<code>import zipfile
import itertools
import time

# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
    try:
        zip_file.extractall(pwd=password)
        return True
    except KeyboardInterrupt:
        exit(0)
    except Exception:
        pass

# Main code starts here...
# The file name of the zip file.
zipfilename = 'test_archive.zip'
# The first part of the password. We know this for sure!
first_half_password = 'Super'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
zip_file = zipfile.ZipFile(zipfilename)

# We know they always have 3 characters after Super...
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
    # Slowing it down on purpose to make it work better with the web terminal
    # Remove at your peril
    time.sleep(0.009)
    # Add the three letters to the first half of the password.
    password = first_half_password+''.join(c)
    # Try to extract the file.
    print ("Trying: %s" % password)
    # If the file was extracted, you found the right password.
    if extractFile(zip_file, str.encode(password)):
        print ('*' * 20)
        print ('Password found: %s' % password)
        print ('Files extracted...')
        exit(0)

# If no password was found by the end, let us know!
print ('Password not found.')
</code>```

This is accomplished with the str.encode built in method.

Body:
I am working on some code for an assignment that it's supposed to brute-force a zip file. I was provided the first word of the password and I know that it has 3 more alphabet characters including uppercase and lowercase.

I am able to print each one of those combinations, but it seems to not find the password. Can somebody take a look at my code and see if you find a bug or something?

import zipfile
import itertools
import time

# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
    try:
        zip_file.extractall(pwd=password)
        return True
    except KeyboardInterrupt:
        exit(0)
    except Exception:
        pass

# Main code starts here...
# The file name of the zip file.
zipfilename = 'planz.zip'
# The first part of the password. We know this for sure!
first_half_password = 'Super'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
zip_file = zipfile.ZipFile(zipfilename)

# We know they always have 3 characters after Super...
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
    # Slowing it down on purpose to make it work better with the web terminal
    # Remove at your peril
    time.sleep(0.009)
    # Add the three letters to the first half of the password.
    password = first_half_password+''.join(c)
    # Try to extract the file.
    print ("Trying: %s" % password)
    # If the file was extracted, you found the right password.
    if extractFile(zip_file, password):
        print ('*' * 20)
        print ('Password found: %s' % password)
        print ('Files extracted...')
        exit(0)

# If no password was found by the end, let us know!
print ('Password not found.')

I expect the program to find the password which it should be Super + 3 more alphabet characters.

Body:
The zip_file.extractall(pwd=password) is expecting a password in the form of bytes, not a string. Thus, since a string is passed in as the password, the try/except block within extractFile is always triggered, thus the password is never found. I have updated your code to include a byte conversion from a string for the password:

import zipfile
import itertools
import time

# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
    try:
        zip_file.extractall(pwd=password)
        return True
    except KeyboardInterrupt:
        exit(0)
    except Exception:
        pass

# Main code starts here...
# The file name of the zip file.
zipfilename = 'test_archive.zip'
# The first part of the password. We know this for sure!
first_half_password = 'Super'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
zip_file = zipfile.ZipFile(zipfilename)

# We know they always have 3 characters after Super...
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
    # Slowing it down on purpose to make it work better with the web terminal
    # Remove at your peril
    time.sleep(0.009)
    # Add the three letters to the first half of the password.
    password = first_half_password+''.join(c)
    # Try to extract the file.
    print ("Trying: %s" % password)
    # If the file was extracted, you found the right password.
    if extractFile(zip_file, str.encode(password)):
        print ('*' * 20)
        print ('Password found: %s' % password)
        print ('Files extracted...')
        exit(0)

# If no password was found by the end, let us know!
print ('Password not found.')

This is accomplished with the str.encode built in method.


问:
Execute a PHP script from another PHP script
How would I make my server run a php script by triggering it manually using php? Basically I have a pretty big cronjob file that is ran every 2 hours, but I want to be able to trigger the file manually myself without having to wait for it to load (i want it to be done on the server's side).

EDIT: I want to execute the file from a php file... Not command line.

答:
Try this:</p>

```<code>header('location: xyz.php'); //thats all for redirecting to another php file
</code>```

Body:
Try this:

header('location: xyz.php'); //thats all for redirecting to another php file


问:
DAO in Scala with type classes
Let my application contains business classes Order, Product, Customer, etc. and I would like to store/retrieve them in/from the database.

Usually, we use the DAO pattern for this purpose. That is, we define a DAO interface and implementation for every business class: OrderDAO, ProductDAO, etc. Now I would like to use the type class pattern:

```<code>trait DAO[T] {
  def create(t:T)
  ... // other CRUD operations
}
...
// DAO implementations for specific business objects
implicit object OrderDAO extends DAO[Order] {
   def create(o:Order) {...}
   ... // other CRUD operations
}
...
// create a business object in the database
def create[T](t:T)(implicit dao:DAO[T]) {dao.create(t)}</code>```

Now my problem is that all DAOs use a DataSource instance (a factory of database connections) and so I cannot define DAOs as objects. I should create a singleton instance of the DataSource and pass it to all DAOs upon their initialisation.

Let's say we have a function to create a DataSource: ```<code>def dataSource():DataSource = {...}</code>```
How would you implement the DAOs with type classes ?

答:
Agree with Sasha. Lift way should work:

```<code>trait DataSource

class MyDataSource extends DataSource

object DataSources {
  @volatile var dataSource: () => DataSource = () => new MyDataSource
}
</code>```

With such approach you can use object without loosing testability.

Title: DAO in Scala with type classes

Body:
Let my application contains business classes Order, Product, Customer, etc. and I would like to store/retrieve them in/from the database.

Usually, we use the DAO pattern for this purpose. That is, we define a DAO interface and implementation for every business class: OrderDAO, ProductDAO, etc. Now I would like to use the type class pattern:

trait DAO[T] {
  def create(t:T)
  ... // other CRUD operations
}
...
// DAO implementations for specific business objects
implicit object OrderDAO extends DAO[Order] {
   def create(o:Order) {...}
   ... // other CRUD operations
}
...
// create a business object in the database
def create[T](t:T)(implicit dao:DAO[T]) {dao.create(t)}

Now my problem is that all DAOs use a DataSource instance (a factory of database connections) and so I cannot define DAOs as objects. I should create a singleton instance of the DataSource and pass it to all DAOs upon their initialisation.

Let's say we have a function to create a DataSource:
def dataSource():DataSource = {...}

How would you implement the DAOs with type classes ?

Body:
Agree with Sasha. Lift way should work:

trait DataSource

class MyDataSource extends DataSource

object DataSources {
  @volatile var dataSource: () => DataSource = () => new MyDataSource
}

With such approach you can use object without loosing testability.


问:
functional react: how to handle setState with an input from map function?
Using react hook, I want to convert all my classes into function. suppose this is my returned render:

```<code>{layerList.map(i => {
        return (
          <Button
            className="button-layer"
            type="primary"
            onClick={handleAa(i)}
          > {aa}
          </Button>
          <Button
             className="button-layer"
             type="primary"
             key={some_values}
             onClick={ handleChange(i) }
          >
            {i}
          </Button>
        )
      } )}
</code>```

How can I pass i to the function handleChange?

答:
```<code>{
  layerList.map(i => {
        return (
          <Button
            className="button-layer"
            type="primary"
            onClick={() => handleAa(i)}
          > {aa}
          </Button>
          <Button
             className="button-layer"
             type="primary"
             key={some_values}
             onClick={ () => handleChange(i) }
           >
             {i}
          </Button>
        )}
    )
}
</code>```

you might need to define functions too

```<code>function handleAa(i){}
function handleChange(i){}
</code>```

Body:
Using react hook, I want to convert all my classes into function. suppose this is my returned render:

{layerList.map(i => {
        return (
          <Button
            className="button-layer"
            type="primary"
            onClick={handleAa(i)}
          > {aa}
          </Button>
          <Button
             className="button-layer"
             type="primary"
             key={some_values}
             onClick={ handleChange(i) }
          >
            {i}
          </Button>
        )
      } )}

How can I pass i to the function handleChange?

Body:
{
  layerList.map(i => {
        return (
          <Button
            className="button-layer"
            type="primary"
            onClick={() => handleAa(i)}
          > {aa}
          </Button>
          <Button
             className="button-layer"
             type="primary"
             key={some_values}
             onClick={ () => handleChange(i) }
           >
             {i}
          </Button>
        )}
    )
}

you might need to define functions too

function handleAa(i){}
function handleChange(i){}


问:
Trouble fiixing tumblr images?
Images will fit inside post container but will shrink significantly when doing so please help

Here is the link to my blog to look at the code

https://poke--spe.tumblr.com

答:
Try this:</p>

```<code>img {
    max-width: 100%;
    max-height: 200%;
    width: auto;
    height: auto;
}
</code>```

Title: Trouble fiixing tumblr images?

Body:
Try this:

img {
    max-width: 100%;
    max-height: 200%;
    width: auto;
    height: auto;
}


问:
MKStoreKit Implementation
I have spent the last 2 days fighting trying to get in app purchases working! The app has not been approved by Apple (its not ready yet), so I just did the Developer Pulled Binary method. I added a non-consumable (and I am pretty sure my contracts are cleared) and called it com.MYAPP.MYAPPNAME.levelone

I am using the MKStoreKit 3.1 relevant

I just want to see that the item will appear in the NSLog for the app, so I have this in my App Delagate

```<code>   - (void) applicationDidFinishLaunching:(UIApplication*)application
{

    [MKStoreManager sharedManager];
    [[MKStoreManager sharedManager] purchasableObjectsDescription];
        ...
</code>```

When I run this it just tells me

```<code>Problem in iTunes connect configuration for product: com.mycompany.myapp.005
Problem in iTunes connect configuration for product: com.mycompany.myapp.featureA
</code>```

This is a Cocos2d based game if it makes any difference.

答:
Remove the unused products inside MKStoreManager.m as follows</p>

```<code>-(void) requestProductData
{
    SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:
                                  kFeatureAId,
                                  //kConsumableFeatureBId,
                                  nil]];
    request.delegate = self;
    [request start];
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: MKStoreKit Implementation

Body:
I have spent the last 2 days fighting trying to get in app purchases working! The app has not been approved by Apple (its not ready yet), so I just did the Developer Pulled Binary method. I added a non-consumable (and I am pretty sure my contracts are cleared) and called it com.MYAPP.MYAPPNAME.levelone

I am using the MKStoreKit 3.1 relevant

I just want to see that the item will appear in the NSLog for the app, so I have this in my App Delagate

   - (void) applicationDidFinishLaunching:(UIApplication*)application
{

    [MKStoreManager sharedManager];
    [[MKStoreManager sharedManager] purchasableObjectsDescription];
        ...

When I run this it just tells me

Problem in iTunes connect configuration for product: com.mycompany.myapp.005
Problem in iTunes connect configuration for product: com.mycompany.myapp.featureA

This is a Cocos2d based game if it makes any difference.

Body:
Remove the unused products inside MKStoreManager.m as follows

-(void) requestProductData
{
    SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:
                                  kFeatureAId,
                                  //kConsumableFeatureBId,
                                  nil]];
    request.delegate = self;
    [request start];
}


问:
How to display a pdf document within an iframe by google docs viewer stored in firebase storage?
I have an iframe in which I want to put a preview of my pdf document hosted in firebase storage through google docs viewer. I am creating the html view in javascript dynamically and adding it by jquery's ('.someClass').html() method.

I tried to plug in the download url of the document to the iframe directly and it works just fine and displays the preview.

But I can't get it to display the preview through google docs.

What I meant is that this works just fine:

```<code>....making  my html on the fly in javascript

myHtml+='<iframe src="'+downloadUrlFirebaseStorage+'" width="100%"   frameborder="0"/>'

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);
</code>```

But this gets me an error:

```<code>....making  my html on the fly in javascript

myHtml+='<iframe src="https://docs.google.com/viewer?url='+downloadUrlFirebaseStorage+'&embedded=true" width="100%"   frameborder="0"/>'

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);
</code>```

The error I get is this:

```<code>Refused to display 'https://docs.google.com/gview?url=https://firebasestorage.googleapis.com/v0/b/habiganjmedicalcollege.appspot.com/o/documents%2FSampleDoc.pdf?alt=media&token=51df7c93-0c59-46a4-9229-267bc527705b%26embedded=true' in a frame because it set 'X-Frame-Options' to 'sameorigin'
</code>```

答:
try this :

```<code><iframe src="https://drive.google.com/viewerng/viewer?url=https://library.osu.edu/assets/Documents/SEL/QuickConvertWordPDF.pdf?pid=explorer&efh=false&a=v&chrome=false&embedded=true" width="400px" height="300px"  />
</code>```

and go to Link

Body:
I have an iframe in which I want to put a preview of my pdf document hosted in firebase storage through google docs viewer. I am creating the html view in javascript dynamically and adding it by jquery's ('.someClass').html() method.

I tried to plug in the download url of the document to the iframe directly and it works just fine and displays the preview.

But I can't get it to display the preview through google docs.

What I meant is that this works just fine:

....making  my html on the fly in javascript

myHtml+=''

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);

But this gets me an error:

....making  my html on the fly in javascript

myHtml+=''

....making remaining  rest of my html on the fly in javascript

$('.someClass').html(myHtml);

The error I get is this:

Refused to display 'https://docs.google.com/gview?url=https://firebasestorage.googleapis.com/v0/b/habiganjmedicalcollege.appspot.com/o/documents%2FSampleDoc.pdf?alt=media&token=51df7c93-0c59-46a4-9229-267bc527705b%26embedded=true' in a frame because it set 'X-Frame-Options' to 'sameorigin'

Body:
try this :

<iframe src="https://drive.google.com/viewerng/viewer?url=https://library.osu.edu/assets/Documents/SEL/QuickConvertWordPDF.pdf?pid=explorer&efh=false&a=v&chrome=false&embedded=true" width="400px" height="300px"  />

and go to Link


问:
How to save opus file using bytes in Golang?
We are using pion/webrtc library and we have incoming audio track from
RTCPeerConnection

We need to save opus audio file from RTCPacket.Raw (list of bytes). We tried to use their OpusWriter but it didn't work, audio is written but not playable.

So the question is how can we save Opus audio file from bytes?

The code:

```<code>        for {
          rtpPacket, err := remoteTrack.ReadRTP()
          b := rtpPacket.Raw

          if ivfFile != nil {
            if err := ivfFile.WriteRTP(rtpPacket); err != nil {
              log.Println(err)
            }
          }

          checkError(err)
          videoTrackLock.RLock()
          _, err = videoTrack.Write(b)
          videoTrackLock.RUnlock()

          if err != io.ErrClosedPipe {
            checkError(err)
          }
        }
</code>```

答:
Does the save-to-disk example not work for you? That demonstrates saving VP8/Opus to disk.

If you do want the audio directly from *RTP.Packet you should use the Payload field not Raw. Raw contains the RTP headers, while Payload will only contain the media.

Thanks for using Pion! I am happy to help either here or on Slack

Body:
We are using pion/webrtc library and we have incoming audio track from
RTCPeerConnection

We need to save opus audio file from RTCPacket.Raw (list of bytes). We tried to use their OpusWriter but it didn't work, audio is written but not playable.

So the question is how can we save Opus audio file from bytes?

The code:

        for {
          rtpPacket, err := remoteTrack.ReadRTP()
          b := rtpPacket.Raw

          if ivfFile != nil {
            if err := ivfFile.WriteRTP(rtpPacket); err != nil {
              log.Println(err)
            }
          }

          checkError(err)
          videoTrackLock.RLock()
          _, err = videoTrack.Write(b)
          videoTrackLock.RUnlock()

          if err != io.ErrClosedPipe {
            checkError(err)
          }
        }


问:
LocalDate deserialization &serialization error -jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate
The birthdate of the employee stored in the Elastic seems to be stored as an incorrect datatype. I have setup code for Elasticseach client with object mapper and registered JavaTime module. I am trying to pull employees list from Elasticsearch and it doesn't seem to work and is failing at deserializing.

```<code>Jar Versions:
org.elasticsearch.client:elasticsearch-rest-client -> 6.4.3 (*)
org.elasticsearch.client:elasticsearch-rest-high-level-client -> 6.4.3
org.elasticsearch:elasticsearch -> 6.4.3
org.springframework.data:spring-data-elasticsearch -> 3.1.4.RELEASE
com.fasterxml.jackson.datatype:jackson-datatype-hppc -> 2.9.8
com.fasterxml.jackson.core:jackson-core:2.9.8
com.fasterxml.jackson.core:jackson-databind:2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-jsr310 -> 2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-hibernate5 -> 2.9.8
com.fasterxml.jackson.core:jackson-annotations -> 2.9.0
com.fasterxml.jackson.module:jackson-module-afterburner -> 2.9.8
com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.8 (*)
com.fasterxml.jackson.module:jackson-modules-java8:2.9.8
</code>```

Build.Gradle:

```<code>compile "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
    compile "com.fasterxml.jackson.core:jackson-annotations"
    compile "com.fasterxml.jackson.core:jackson-databind"
    compile "com.fasterxml.jackson.module:jackson-module-afterburner"
    runtime group: 'com.fasterxml.jackson.module', name: 'jackson-modules-java8', version: '2.9.8', ext: 'pom'
    // https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-parameter-names', version: '2.9.8'

compile 'org.elasticsearch:elasticsearch'
    compile 'org.elasticsearch.client:transport'
    compile 'org.elasticsearch.client:elasticsearch-rest-client'
    compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client'

    compile 'org.springframework.data:spring-data-elasticsearch'

</code>```

application.yml

```<code>jackson:
    serialization:
         WRITE_DATES_AS_TIMESTAMPS: false
 jpa:

    open-in-view: false
</code>```

ElasticConfiguration Code:

```<code>@AutoConfigureAfter(value = { JacksonConfiguration.class })
public class ElasticsearchConfiguration {

    RestHighLevelClient client = null;

    @Bean
    public RestHighLevelClient buildClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    }

    @Bean
    @Primary
    public ElasticsearchOperations elasticsearchTemplate(final ElasticsearchConverter elasticsearchConverter,
            EntityMapper mapper, Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder ) {
        return new ElasticsearchTemplate((Client) buildClient(), new CustomEntityMapper(new ObjectMapper()));
    }
    //jackson2ObjectMapperBuilder.createXmlMapper(false).build()

    public class CustomEntityMapper implements EntityMapper {

        private ObjectMapper objectMapper;

        public CustomEntityMapper(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            //objectMapper.registerModule(new JavaTimeModule());
            JavaTimeModule javaTimeModule=new JavaTimeModule();
            // Hack time module to allow 'Z' at the end of string (i.e. javascript json's)
            javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
            javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_DATE));
            objectMapper.registerModule(javaTimeModule);
            objectMapper.registerModule(new ParameterNamesModule());
            objectMapper.registerModule(new Jdk8Module());
            objectMapper.findAndRegisterModules();
        }

        @Override
        public String mapToString(Object object) throws IOException {
            return objectMapper.writeValueAsString(object);
        }

        @Override
        public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
            return objectMapper.readValue(source, clazz);
        }
    }

}
</code>```

Error:

```<code>Caused by: org.springframework.data.elasticsearch.ElasticsearchException: failed to map source [ {"id":73,"name":"K****","birthDate":{"year":2019,"month":"MAY","dayOfYear":150,"leapYear":false,"dayOfMonth":30,"dayOfWeek":"THURSDAY","era":"CE","monthValue":5,"chronology":{"id":"ISO","calendarType":"iso8601"}},"role..}] to class Employee
    at org.springframework.data.elasticsearch.core.AbstractResultMapper.mapEntity(AbstractResultMapper.java:45) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.DefaultResultMapper.mapResults(DefaultResultMapper.java:102) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.queryForPage(ElasticsearchTemplate.java:315) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.queryForPage(ElasticsearchTemplate.java:309) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.queryForPage(ElasticsearchTemplate.java:139) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository.findAll(AbstractElasticsearchRepository.java:126) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository.findAll(AbstractElasticsearchRepository.java:120) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_211]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_211]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_211]
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"id":73,"name":"Kelly","birthDate":{"year":2019,"month":"MAY","dayOfYear":150,"leapYear":false,"dayOfMonth":30,"dayOfWeek":"THURSDAY","era":"CE","monthValue":5,"chronology":{"id":"ISO","calendarType":"iso8601"}},"role...}},"lastModifiedBy""[truncated 396 chars]; line: 1, column: 38] (through reference chain: Employee["birthDate"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004) ~[jackson-databind-2.9.8.jar:2.9.8]
    at org.springframework.data.elasticsearch.core.DefaultEntityMapper.mapToObject(DefaultEntityMapper.java:82) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.AbstractResultMapper.mapEntity(AbstractResultMapper.java:43) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    ... 34 common frames omitted
</code>```

Employee:

```<code>public class Employee extends AbstractAuditingEntity implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;

    //Remaining Fields are removed for brevity

</code>```

AbstractAuditEntity

```<code>@MappedSuperclass
@Audited
@EntityListeners({AuditingEntityListener.class, EntityAuditEventListener.class})
public abstract class AbstractAuditingEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @CreatedBy
    @Column(name = "created_by", nullable = true, length = 50, updatable = false)
    private String createdBy;

    @CreatedDate
    @Column(name = "created_date")
    private LocalDateTime createdDate = LocalDateTime.now();

    @LastModifiedBy
    @Column(name = "last_modified_by", length = 50)
    private String lastModifiedBy;

    @LastModifiedDate
    @Column(name = "last_modified_date")
    private LocalDateTime lastModifiedDate = LocalDateTime.now();
</code>```

答:
Your problem probably will be because Jackson does not support Java 8 DateTime Api out of the box.
So you can add the following library to add support for that (add in pom.xml):

```<code><dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>
</code>```

and configure object mapper to use this library module like :

```<code>ObjectMapper mapper = new ObjectMapper()
   .registerModule(new ParameterNamesModule())
   .registerModule(new Jdk8Module())
   .registerModule(new JavaTimeModule());
</code>```

Use the link for reference :
https://github.com/FasterXML/jackson-modules-java8

Body:
The birthdate of the employee stored in the Elastic seems to be stored as an incorrect datatype. I have setup code for Elasticseach client with object mapper and registered JavaTime module. I am trying to pull employees list from Elasticsearch and it doesn't seem to work and is failing at deserializing.

Jar Versions:
org.elasticsearch.client:elasticsearch-rest-client -> 6.4.3 (*)
org.elasticsearch.client:elasticsearch-rest-high-level-client -> 6.4.3
org.elasticsearch:elasticsearch -> 6.4.3
org.springframework.data:spring-data-elasticsearch -> 3.1.4.RELEASE
com.fasterxml.jackson.datatype:jackson-datatype-hppc -> 2.9.8
com.fasterxml.jackson.core:jackson-core:2.9.8
com.fasterxml.jackson.core:jackson-databind:2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-jsr310 -> 2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-hibernate5 -> 2.9.8
com.fasterxml.jackson.core:jackson-annotations -> 2.9.0
com.fasterxml.jackson.module:jackson-module-afterburner -> 2.9.8
com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.8 (*)
com.fasterxml.jackson.module:jackson-modules-java8:2.9.8

Build.Gradle:

compile "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
    compile "com.fasterxml.jackson.core:jackson-annotations"
    compile "com.fasterxml.jackson.core:jackson-databind"
    compile "com.fasterxml.jackson.module:jackson-module-afterburner"
    runtime group: 'com.fasterxml.jackson.module', name: 'jackson-modules-java8', version: '2.9.8', ext: 'pom'
    // https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-parameter-names', version: '2.9.8'

compile 'org.elasticsearch:elasticsearch'
    compile 'org.elasticsearch.client:transport'
    compile 'org.elasticsearch.client:elasticsearch-rest-client'
    compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client'

    compile 'org.springframework.data:spring-data-elasticsearch'

application.yml

jackson:
    serialization:
         WRITE_DATES_AS_TIMESTAMPS: false
 jpa:

    open-in-view: false

ElasticConfiguration Code:

@AutoConfigureAfter(value = { JacksonConfiguration.class })
public class ElasticsearchConfiguration {

    RestHighLevelClient client = null;

    @Bean
    public RestHighLevelClient buildClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    }

    @Bean
    @Primary
    public ElasticsearchOperations elasticsearchTemplate(final ElasticsearchConverter elasticsearchConverter,
            EntityMapper mapper, Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder ) {
        return new ElasticsearchTemplate((Client) buildClient(), new CustomEntityMapper(new ObjectMapper()));
    }
    //jackson2ObjectMapperBuilder.createXmlMapper(false).build()

    public class CustomEntityMapper implements EntityMapper {

        private ObjectMapper objectMapper;

        public CustomEntityMapper(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            //objectMapper.registerModule(new JavaTimeModule());
            JavaTimeModule javaTimeModule=new JavaTimeModule();
            // Hack time module to allow 'Z' at the end of string (i.e. javascript json's)
            javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
            javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_DATE));
            objectMapper.registerModule(javaTimeModule);
            objectMapper.registerModule(new ParameterNamesModule());
            objectMapper.registerModule(new Jdk8Module());
            objectMapper.findAndRegisterModules();
        }

        @Override
        public String mapToString(Object object) throws IOException {
            return objectMapper.writeValueAsString(object);
        }

        @Override
        public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
            return objectMapper.readValue(source, clazz);
        }
    }

}

Error:

Caused by: org.springframework.data.elasticsearch.ElasticsearchException: failed to map source [ {"id":73,"name":"K****","birthDate":{"year":2019,"month":"MAY","dayOfYear":150,"leapYear":false,"dayOfMonth":30,"dayOfWeek":"THURSDAY","era":"CE","monthValue":5,"chronology":{"id":"ISO","calendarType":"iso8601"}},"role..}] to class Employee
    at org.springframework.data.elasticsearch.core.AbstractResultMapper.mapEntity(AbstractResultMapper.java:45) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.DefaultResultMapper.mapResults(DefaultResultMapper.java:102) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.queryForPage(ElasticsearchTemplate.java:315) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.queryForPage(ElasticsearchTemplate.java:309) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.queryForPage(ElasticsearchTemplate.java:139) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository.findAll(AbstractElasticsearchRepository.java:126) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository.findAll(AbstractElasticsearchRepository.java:120) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_211]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_211]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_211]
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.4.RELEASE.jar:2.1.4.RELEASE]
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"id":73,"name":"Kelly","birthDate":{"year":2019,"month":"MAY","dayOfYear":150,"leapYear":false,"dayOfMonth":30,"dayOfWeek":"THURSDAY","era":"CE","monthValue":5,"chronology":{"id":"ISO","calendarType":"iso8601"}},"role...}},"lastModifiedBy""[truncated 396 chars]; line: 1, column: 38] (through reference chain: Employee["birthDate"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.8.jar:2.9.8]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004) ~[jackson-databind-2.9.8.jar:2.9.8]
    at org.springframework.data.elasticsearch.core.DefaultEntityMapper.mapToObject(DefaultEntityMapper.java:82) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    at org.springframework.data.elasticsearch.core.AbstractResultMapper.mapEntity(AbstractResultMapper.java:43) ~[spring-data-elasticsearch-3.1.4.RELEASE.jar:3.1.4.RELEASE]
    ... 34 common frames omitted

Employee:

public class Employee extends AbstractAuditingEntity implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;

    //Remaining Fields are removed for brevity

AbstractAuditEntity

@MappedSuperclass
@Audited
@EntityListeners({AuditingEntityListener.class, EntityAuditEventListener.class})
public abstract class AbstractAuditingEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @CreatedBy
    @Column(name = "created_by", nullable = true, length = 50, updatable = false)
    private String createdBy;

    @CreatedDate
    @Column(name = "created_date")
    private LocalDateTime createdDate = LocalDateTime.now();

    @LastModifiedBy
    @Column(name = "last_modified_by", length = 50)
    private String lastModifiedBy;

    @LastModifiedDate
    @Column(name = "last_modified_date")
    private LocalDateTime lastModifiedDate = LocalDateTime.now();

Body:
Your problem probably will be because Jackson does not support Java 8 DateTime Api out of the box.
So you can add the following library to add support for that (add in pom.xml):

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>

and configure object mapper to use this library module like :

ObjectMapper mapper = new ObjectMapper()
   .registerModule(new ParameterNamesModule())
   .registerModule(new Jdk8Module())
   .registerModule(new JavaTimeModule());

Use the link for reference :
https://github.com/FasterXML/jackson-modules-java8


问:
how to kill or quit .exe(debugging)application in c#
Hello i've got some code ,to check if is there a specific folder created, it will zip the file in the folder, and if there isn't a folder created , quit the app.

```<code> try
            {
                using (ZipFile zip = new ZipFile())
                {
                    zip.UseUnicodeAsNecessary = true;
                    zip.AddDirectory(@"C:\" + tglskrg + "\\Result");
                    zip.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), tglskrg + ".zip"));
                    zip.Save(@"C:\Users\Desktop\test.zip");
                }

            }
            catch (Exception e)
            {
                try
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    Marshal.ReleaseComObject(xlWS);
                    Marshal.ReleaseComObject(xlRange);

                    xlApp.Quit(); // release excel object
                }
                catch (Exception ex)
                {

                }
               //code to quit the .exe app
            }
...
//send email code : which its work
</code>```

I dont know how to kill the .exe app when its not success finding the folder.
i know to kill other process like notepad ,other  apps , but i dont know how to kill this debug .exe app, i hope u guys understand because my english is so bad

Thankyouu

答:
Try Application.Exit(). If I understood your question correctly, it is what you need.

The above method, as vasily.sib said, is for WinForms. For WPF you can use Application.shutDown() and for general you can use Environment.Exit(int)

Body:
Hello i've got some code ,to check if is there a specific folder created, it will zip the file in the folder, and if there isn't a folder created , quit the app.

 try
            {
                using (ZipFile zip = new ZipFile())
                {
                    zip.UseUnicodeAsNecessary = true;
                    zip.AddDirectory(@"C:\" + tglskrg + "\\Result");
                    zip.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), tglskrg + ".zip"));
                    zip.Save(@"C:\Users\Desktop\test.zip");
                }

            }
            catch (Exception e)
            {
                try
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    Marshal.ReleaseComObject(xlWS);
                    Marshal.ReleaseComObject(xlRange);

                    xlApp.Quit(); // release excel object
                }
                catch (Exception ex)
                {

                }
               //code to quit the .exe app
            }
...
//send email code : which its work

I dont know how to kill the .exe app when its not success finding the folder.
i know to kill other process like notepad ,other  apps , but i dont know how to kill this debug .exe app, i hope u guys understand because my english is so bad

Thankyouu


问:
Not able to reset input field in laravel
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

```<code> <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
</code>```

JS for reset button:

```<code>document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };
</code>```

Reset Button:

```<code><button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
</code>```

答:
Please try to use in js like:</p>

```<code>$(document).on('click', '#YourOnclickButtonID', function(){
    var $alertas = $('#YourFormID');
    $alertas.validate().resetForm();
});
</code>```

Body:
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

 <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>

JS for reset button:

document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };

Reset Button:

<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>

Body:
Please try to use in js like:

$(document).on('click', '#YourOnclickButtonID', function(){
    var $alertas = $('#YourFormID');
    $alertas.validate().resetForm();
});


问:
How to fix " implicit declaration of function"
I'm working on a GUI library in C for a school work, but I've got a problem with header files (I think).
I have a function "rectangle_coordinates" in a "draw.c" file, with the adequate "draw.h" header file, and in a file "widget_frame.c" I call this function, after including the "draw.h" header file.
But I still got a warning :

```<code>./src/ei_widget_frame.c:40:5: warning: implicit declaration of function 'rectangle_coordinates' [-Wimplicit-function-declaration]
     rectangle_coordinates(&frame_to_draw, &xmin, &xmax, &ymin, &ymax);
</code>```

Do you have an idea that can fix my problem ?

答:
At a minimum, all things below should be verified and corrected (if needed).

The function name must be the same in all places (check for typo's).

The return type must be the same in all places.

The parameters list must be the same in all places.

In draw.h you should have something like:

```<code>extern /type/ rectangle_coordinates(&frame_to_draw, &xmin, &xmax, &ymin, &ymax);
</code>```

where:

/type/ is the return type of the function.

the parameters list needs to be written correctly (I just made copy / paste from the warning message provided).

In both draw.c and ei_widget_frame.c you should have:

```<code>#include "draw.h"
</code>```

Body:
I'm working on a GUI library in C for a school work, but I've got a problem with header files (I think).
I have a function "rectangle_coordinates" in a "draw.c" file, with the adequate "draw.h" header file, and in a file "widget_frame.c" I call this function, after including the "draw.h" header file.
But I still got a warning :

./src/ei_widget_frame.c:40:5: warning: implicit declaration of function 'rectangle_coordinates' [-Wimplicit-function-declaration]
     rectangle_coordinates(&frame_to_draw, &xmin, &xmax, &ymin, &ymax);

Do you have an idea that can fix my problem ?

Body:
At a minimum, all things below should be verified and corrected (if needed).

The function name must be the same in all places (check for typo's).

The return type must be the same in all places.

The parameters list must be the same in all places.

In draw.h you should have something like:

extern /type/ rectangle_coordinates(&frame_to_draw, &xmin, &xmax, &ymin, &ymax);

where:

/type/ is the return type of the function.

the parameters list needs to be written correctly (I just made copy / paste from the warning message provided).

In both draw.c and ei_widget_frame.c you should have:

#include "draw.h"