问:
Get contents of a particular row
I want to locate 'td' where text is 'xyz' so that I can find other attributes in the row. I only have 'xyz' with me and want to get other elements in that row.

```<code>.
.
.

<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>

.
.
.
</code>```

I can get 'xyz' easily by using

```<code>required = soup.find('a', text = 'xyz')
print(required[0].text)
</code>```

but I'm not able to locate 'td' so that I can use find_next_siblings() to get other columns.

Expected output:

```<code>xyz
address
phone number
</code>```

答:
If you have modern BeautifulSoup, you can use CSS selector :contains. Then traverse back with find_parent() method.

```<code>from bs4 import BeautifulSoup

s = '''
<tr>
    <td>Other1</td>
    <td>Other1</td>
    <td>Other1</td>
</tr>
<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>'''

soup = BeautifulSoup(s, 'lxml')

for td in soup.select_one('a:contains(xyz)').find_parent('tr').select('td'):
    print(td.text.strip())
</code>```

Prints:

```<code>xyz
address
phone number
</code>```

Title: Get contents of a particular row

Body:
I want to locate 'td' where text is 'xyz' so that I can find other attributes in the row. I only have 'xyz' with me and want to get other elements in that row.

.
.
.

        xyz

    address
    phone number

.
.
.

I can get 'xyz' easily by using

required = soup.find('a', text = 'xyz')
print(required[0].text)

but I'm not able to locate 'td' so that I can use find_next_siblings() to get other columns.

Expected output:

xyz
address
phone number

Body:
If you have modern BeautifulSoup, you can use CSS selector :contains. Then traverse back with find_parent() method.

from bs4 import BeautifulSoup

s = '''
<tr>
    <td>Other1</td>
    <td>Other1</td>
    <td>Other1</td>
</tr>
<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>'''

soup = BeautifulSoup(s, 'lxml')

for td in soup.select_one('a:contains(xyz)').find_parent('tr').select('td'):
    print(td.text.strip())

Prints:

xyz
address
phone number


来源: stackexchange

问:
How to add Footer / Header in CollectionView

code Snippet

```<code>class TemporaryViewController: UIViewController {
     @IBOutlet weak var itemCollectionView: UICollectionView!   // Main Collection View
     private var footerView: DashboardBottomViewCollectionViewCell?

     override func viewDidLoad() {
       super.viewDidLoad()
        self.itemCollectionView.delegate = self
        self.itemCollectionView.dataSource = self
        self.itemCollectionView.register(UINib(nibName: nibParameter.DASHBOARD_CENTER_NIB, bundle: nil), forCellWithReuseIdentifier: nibParameter.DASHBOARD_CENTER_NIB)
        self.itemCollectionView.register(UINib(nibName: "DashboardBottomViewCollectionViewCell", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "DashboardBottomViewCollectionViewCell")
       }}

extension TemporaryViewController:  UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

     func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

       switch kind {
          case UICollectionView.elementKindSectionHeader:
          return nil

          case UICollectionView.elementKindSectionFooter:
           let footerView = itemCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "DashboardBottomViewCollectionViewCell", for: indexPath) as! DashboardBottomViewCollectionViewCell
           self.footerView = footerView
           self.footerView?.contentView?.clipsToBounds = true
           footerView?.dashboardBottomDelegate = self
           footerView?.clipsToBounds = true
           return footerView!

    default:
        return headerView!
    }
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
     return CGSize(width: 600, height: 300.0)
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
     return CGSize(width: 100.0, height: 300.0)
}

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return 3
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

     let width = -10 + (collectionView.frame.width)
     return CGSize(width: width,
                  height: 90)
}
}
</code>```

Footer Class to Show collection View

```<code>class DashboardBottomViewCollectionViewCell: UICollectionReusableView {

weak var dashboardBottomDelegate: DashboardBottomViewCollectionViewDelegate?
@IBOutlet weak var itemCollectionView: UICollectionView!
@IBOutlet weak var imageView: UIView!
var estimateWidth = 160.0
var cellMarginSize = 16.0
var contentView : DashboardBottomViewCollectionViewCell?

override init(frame: CGRect) {
    super.init(frame: frame)
    let contents = Bundle.main.loadNibNamed("DashboardBottomViewCollectionViewCell", owner: self, options: nil)?.first as! DashboardBottomViewCollectionViewCell
    self.addSubview(contents)
    contentView = contents
    contents.itemCollectionView.register(UINib(nibName: nibParameter.DASHBOARD_PURCHASE_NIB, bundle: nil), forCellWithReuseIdentifier:nibParameter.DASHBOARD_PURCHASE_NIB)
    contents.itemCollectionView.delegate = self
    contents.itemCollectionView.dataSource = self
    let flow = contents.itemCollectionView?.collectionViewLayout as! UICollectionViewFlowLayout
    flow.minimumInteritemSpacing = CGFloat(self.cellMarginSize)
    flow.minimumLineSpacing =  CGFloat(self.cellMarginSize)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

func reloadData() {
    contentView?.itemCollectionView.reloadData()
}
}

extension DashboardBottomViewCollectionViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 15
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: nibParameter.DASHBOARD_PURCHASE_NIB, for: indexPath) as! RecentPurchaseCollectionViewCell

    cell.purchaseLabel.text = "trainers.trainerName"
    cell.imageView.sd_setImage(with: URL(string: "trainers.tarinerProfilePictureUrl" != nil ? "trainers.tarinerProfilePictureUrl" : ""), placeholderImage: UIImage.init(named: "tour_placeholder"), options: .handleCookies, completed: nil)
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = 0 + (collectionView.frame.width / 1)
    return CGSize(width: width,
                  height: 100)
}
}

extension DashboardBottomViewCollectionViewCell : UICollectionViewDelegate {

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    dashboardBottomDelegate?.didSelect(tem: indexPath.item)
}
}
</code>```

As per the code, I can see this:

I can see a collectionView in Footer but can't change the orientation to vertical instead of the Grid view like this:

I am stuck and couldn't find any hint. Any hint would be appreciable. Thanks

答:
Have you tried putting your setup code DashboardBottomViewCollectionViewCell.init(frame:) in awakeFromNib() instead?

```<code>    override func awakeFromNib() {
        super.awakeFromNib()
        //setup cell and stuffs
    }
</code>```

Also call footerView?.reloadData() to reload the contents.

ContentLicense: CC BY-SA 4.0

Body:
code Snippet

class TemporaryViewController: UIViewController {
     @IBOutlet weak var itemCollectionView: UICollectionView!   // Main Collection View
     private var footerView: DashboardBottomViewCollectionViewCell?

     override func viewDidLoad() {
       super.viewDidLoad()
        self.itemCollectionView.delegate = self
        self.itemCollectionView.dataSource = self
        self.itemCollectionView.register(UINib(nibName: nibParameter.DASHBOARD_CENTER_NIB, bundle: nil), forCellWithReuseIdentifier: nibParameter.DASHBOARD_CENTER_NIB)
        self.itemCollectionView.register(UINib(nibName: "DashboardBottomViewCollectionViewCell", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "DashboardBottomViewCollectionViewCell")
       }}

extension TemporaryViewController:  UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

     func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

       switch kind {
          case UICollectionView.elementKindSectionHeader:
          return nil

          case UICollectionView.elementKindSectionFooter:
           let footerView = itemCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "DashboardBottomViewCollectionViewCell", for: indexPath) as! DashboardBottomViewCollectionViewCell
           self.footerView = footerView
           self.footerView?.contentView?.clipsToBounds = true
           footerView?.dashboardBottomDelegate = self
           footerView?.clipsToBounds = true
           return footerView!

    default:
        return headerView!
    }
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
     return CGSize(width: 600, height: 300.0)
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
     return CGSize(width: 100.0, height: 300.0)
}

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return 3
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

     let width = -10 + (collectionView.frame.width)
     return CGSize(width: width,
                  height: 90)
}
}

Footer Class to Show collection View

class DashboardBottomViewCollectionViewCell: UICollectionReusableView {

weak var dashboardBottomDelegate: DashboardBottomViewCollectionViewDelegate?
@IBOutlet weak var itemCollectionView: UICollectionView!
@IBOutlet weak var imageView: UIView!
var estimateWidth = 160.0
var cellMarginSize = 16.0
var contentView : DashboardBottomViewCollectionViewCell?

override init(frame: CGRect) {
    super.init(frame: frame)
    let contents = Bundle.main.loadNibNamed("DashboardBottomViewCollectionViewCell", owner: self, options: nil)?.first as! DashboardBottomViewCollectionViewCell
    self.addSubview(contents)
    contentView = contents
    contents.itemCollectionView.register(UINib(nibName: nibParameter.DASHBOARD_PURCHASE_NIB, bundle: nil), forCellWithReuseIdentifier:nibParameter.DASHBOARD_PURCHASE_NIB)
    contents.itemCollectionView.delegate = self
    contents.itemCollectionView.dataSource = self
    let flow = contents.itemCollectionView?.collectionViewLayout as! UICollectionViewFlowLayout
    flow.minimumInteritemSpacing = CGFloat(self.cellMarginSize)
    flow.minimumLineSpacing =  CGFloat(self.cellMarginSize)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

func reloadData() {
    contentView?.itemCollectionView.reloadData()
}
}

extension DashboardBottomViewCollectionViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 15
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: nibParameter.DASHBOARD_PURCHASE_NIB, for: indexPath) as! RecentPurchaseCollectionViewCell

    cell.purchaseLabel.text = "trainers.trainerName"
    cell.imageView.sd_setImage(with: URL(string: "trainers.tarinerProfilePictureUrl" != nil ? "trainers.tarinerProfilePictureUrl" : ""), placeholderImage: UIImage.init(named: "tour_placeholder"), options: .handleCookies, completed: nil)
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = 0 + (collectionView.frame.width / 1)
    return CGSize(width: width,
                  height: 100)
}
}

extension DashboardBottomViewCollectionViewCell : UICollectionViewDelegate {

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    dashboardBottomDelegate?.didSelect(tem: indexPath.item)
}
}

As per the code, I can see this:

I can see a collectionView in Footer but can't change the orientation to vertical instead of the Grid view like this:

I am stuck and couldn't find any hint. Any hint would be appreciable. Thanks

Body:
Have you tried putting your setup code DashboardBottomViewCollectionViewCell.init(frame:) in awakeFromNib() instead?

    override func awakeFromNib() {
        super.awakeFromNib()
        //setup cell and stuffs
    }

Also call footerView?.reloadData() to reload the contents.


问:
Firestore rules if..else
I have just started to get my head around Firestore rules and my head is expanding rapidly.

I'm trying to work out how to apply a rule to one collection and another rule to all other collections and their sub-collections.

So I start with the default rule that seems to come with Firestore:

```<code>service cloud.firestore {
  match /databases/{database}/documents {

    match /{document=**} {
      allow read, write;
    }
  }
}
</code>```

which would allow read write access to all collections and their documents.

But suppose I want to apply a rule to the documents in one collection and retain the default rule for all other collections. The following will not work:

```<code>service cloud.firestore {
  match /databases/{database}/documents {

      match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
}

  match /{document=**} {
    allow read, write;
}

 }
}
</code>```

because the second rule will override the first.

Is there a way to do what I am trying to do?

答:
I understand that you want to apply a rule to the documents in one collection and retain the default rule for all other collections. There's a way to do what you're trying to do and you're not going to like it.

You have to specify the default rules for all the other collections explicitly.

Here's a sample.

```<code>service cloud.firestore {
  match /databases/{database}/documents {

    //Rule for Suppliers collection
    match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
    }

    //Rule for Changelog collection allowing complete access
    match /Changelog/{id} {
        allow read: if true;
        allow write: if true;
    }

    //Rule for Vendors collection allowing complete access
    match /Vendors/{id} {
        allow read: if true;
        allow write: if true;
    }

  }
}
</code>```

Note: Firestore rules doesn't support if else statements. But you can use AND and OR conditions as a workaround to simulate the same.

Title: Firestore rules if..else

Body:
I have just started to get my head around Firestore rules and my head is expanding rapidly.

I'm trying to work out how to apply a rule to one collection and another rule to all other collections and their sub-collections.

So I start with the default rule that seems to come with Firestore:

service cloud.firestore {
  match /databases/{database}/documents {

    match /{document=**} {
      allow read, write;
    }
  }
}

which would allow read write access to all collections and their documents.

But suppose I want to apply a rule to the documents in one collection and retain the default rule for all other collections. The following will not work:

service cloud.firestore {
  match /databases/{database}/documents {

      match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
}

  match /{document=**} {
    allow read, write;
}

 }
}

because the second rule will override the first.

Is there a way to do what I am trying to do?

Body:
I understand that you want to apply a rule to the documents in one collection and retain the default rule for all other collections. There's a way to do what you're trying to do and you're not going to like it.

You have to specify the default rules for all the other collections explicitly.

Here's a sample.

service cloud.firestore {
  match /databases/{database}/documents {

    //Rule for Suppliers collection
    match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
    }

    //Rule for Changelog collection allowing complete access
    match /Changelog/{id} {
        allow read: if true;
        allow write: if true;
    }

    //Rule for Vendors collection allowing complete access
    match /Vendors/{id} {
        allow read: if true;
        allow write: if true;
    }

  }
}

Note: Firestore rules doesn't support if else statements. But you can use AND and OR conditions as a workaround to simulate the same.


问:
is there any function to make touchable url while converting html text to plain text
I'm trying to convert HTML text into plain text but the URL present in HTML in not touchable in plain text </p>

```<code>var htmlString = """
<p style=\"text-align: justify;\">The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019. </p>\n<p style=\"text-align: justify;\">Form AGILE is an application for Goods and services tax Identification number, employees state Insurance corporation registration plus Employees provident fund organisation registration.  </p>\n<p style=\"text-align: justify;\">Stakeholders are advised to check the latest version before filing.</p>\n<p style=\"text-align: justify;\"><a href=\"http://www.mca.gov.in/ /
"""
let encodedData = htmlString.data(using: .unicode, allowLossyConversion: false)

var attributedString: NSAttributedString?

do {
    attributedString = try NSAttributedString(data: encodedData!, options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding:NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)

} catch let error as NSError {
    print(error.localizedDescription)
} catch {
    print("error")
}
print(encodedData!)
print(attributedString)
</code>```

答:
Here is how you convert HTML

```<code>var htmlString = """
<p style=\"text-align: justify;\">The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019. </p><p style=\"text-align: justify;\"><a href=\"http://example.org\">Link</a></p>
"""

let attributedString = try? NSAttributedString(data: Data(htmlString.utf8), options: [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
textView.attributedText = attributedString
</code>```

That yields:

Body:
I'm trying to convert HTML text into plain text but the URL present in HTML in not touchable in plain text

var htmlString = """

The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019.
\n
Form AGILE is an application for Goods and services tax Identification number, employees state Insurance corporation registration plus Employees provident fund organisation registration.
\n
Stakeholders are advised to check the latest version before filing.
\n
<a href=\"http://www.mca.gov.in/ /
"""
let encodedData = htmlString.data(using: .unicode, allowLossyConversion: false)

var attributedString: NSAttributedString?

do {
    attributedString = try NSAttributedString(data: encodedData!, options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding:NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)

} catch let error as NSError {
    print(error.localizedDescription)
} catch {
    print("error")
}
print(encodedData!)
print(attributedString)

Body:
Here is how you convert HTML

var htmlString = """
<p style=\"text-align: justify;\">The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019.&nbsp;</p><p style=\"text-align: justify;\"><a href=\"http://example.org\">Link</a></p>
"""

let attributedString = try? NSAttributedString(data: Data(htmlString.utf8), options: [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
textView.attributedText = attributedString

That yields:


问:
c# how to set beginInvoke end?
I have code my system to save a temporary image file to a folder from the pictureBox then I have to make sure that the beginInvoke end and code the system to delete the temporary image file of that folder. Anyone know how to do that?

This is my code:

```<code>    //Image Selection End Point
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        // Do nothing it we're not selecting an area.
        if (!RegionSelect) return;
        RegionSelect = false;

        //Display the original image.
        pictureBox1.Image = bmpImage;

        // Copy the selected part of the image.
        int wid = Math.Abs(x0 - x1);
        int hgt = Math.Abs(y0 - y1);
        if ((wid < 1) || (hgt < 1)) return;

        Bitmap area = new Bitmap(wid, hgt);
        using (Graphics g = Graphics.FromImage(area))
        {
            Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
            Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
            g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
        }

        // Display the result.
        pictureBox3.Image = area;
        Bitmap bm = new Bitmap(area);
        bm.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
        singleFileInfo = new FileInfo(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg");
    }

    private void ScanBT_Click(object sender, EventArgs e)
    {
        var folder = @"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";

        DirectoryInfo directoryInfo;
        FileInfo[] files;
        directoryInfo = new DirectoryInfo(folder);
        files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);

        var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
        processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);
    }

    private void ProcessImages2(FileInfo[] files)
    {
        var comparableImages = new List<ComparableImage>();

        var index = 0x0;

        var operationStartTime = DateTime.Now;

        foreach (var file in files)
        {
            if (exit)
            {
                return;
            }

            var comparableImage = new ComparableImage(file);
            comparableImages.Add(comparableImage);
            index++;
        }

        index = 0;

        similarityImagesSorted = new List<SimilarityImages>();

        operationStartTime = DateTime.Now;

        var fileImage = new ComparableImage(singleFileInfo);

        for (var i = 0; i < comparableImages.Count; i++)
        {
            if (exit)
                return;

            var destination = comparableImages[i];
            var similarity = fileImage.CalculateSimilarity(destination);
            var sim = new SimilarityImages(fileImage, destination, similarity);
            similarityImagesSorted.Add(sim);
            index++;
        }

        similarityImagesSorted.Sort();
        similarityImagesSorted.Reverse();
        similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);

        con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
        con.Open();

        String getImage = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
        String getImage1 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[1].Destination.ToString() + "'";
        String getImage2 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[2].Destination.ToString() + "'";

        SqlCommand cmd = new SqlCommand(getImage, con);
        SqlDataReader rd = cmd.ExecuteReader();

        while (rd.Read())
        {
             getPath = rd["ImagePath"].ToString();
             pictureBox4.Image = Image.FromFile(getPath);
        }
        rd.Close();

        SqlCommand cmd1 = new SqlCommand(getImage1, con);
        SqlDataReader rd1 = cmd1.ExecuteReader();

        while (rd1.Read())
        {
            getPath1 = rd1["ImagePath"].ToString();
            pictureBox5.Image = Image.FromFile(getPath1);
        }
        rd1.Close();

        SqlCommand cmd2 = new SqlCommand(getImage2, con);
        SqlDataReader rd2 = cmd2.ExecuteReader();

        while (rd2.Read())
        {
            getPath2 = rd2["ImagePath"].ToString();
            pictureBox6.Image = Image.FromFile(getPath2);
        }
        con.Close();
     }

    private void pictureBox4_Click(object sender, EventArgs e)
    {
        if (pictureBox4.Image == null)
        {
            MessageBox.Show("Nothing has been scanned yet!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        else
        {
            con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
            con.Open();
            String getText = "SELECT ImagePath, Character FROM CharacterImage WHERE ImagePath='" + getPath + "'";
            SqlCommand cmd = new SqlCommand(getText, con);
            SqlDataReader rd = cmd.ExecuteReader();

            while (rd.Read())
            {
                for (int i = 0; i < 1; i++)
                {
                    String imageChar = rd["Character"].ToString();
                    Action showText = () => ocrTB.AppendText(imageChar);
                    ocrTB.Invoke(showText);
                }
            }
            rd.Close();
        }

    }
</code>```

答:
BeginInvoke returns you with an IAsyncResult which you can use to wait for the operation to complete:

```<code>IAsyncResult result = processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);
</code>```

You can then check whether the operation completed using the result.IsCompleted property, or you can wait on the WaitHandle returned from  result.AsyncWaitHandle.

ContentLicense: CC BY-SA 3.0

Title: c# how to set beginInvoke end?

Body:
I have code my system to save a temporary image file to a folder from the pictureBox then I have to make sure that the beginInvoke end and code the system to delete the temporary image file of that folder. Anyone know how to do that?

This is my code:

    //Image Selection End Point
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        // Do nothing it we're not selecting an area.
        if (!RegionSelect) return;
        RegionSelect = false;

        //Display the original image.
        pictureBox1.Image = bmpImage;

        // Copy the selected part of the image.
        int wid = Math.Abs(x0 - x1);
        int hgt = Math.Abs(y0 - y1);
        if ((wid < 1) || (hgt < 1)) return;

        Bitmap area = new Bitmap(wid, hgt);
        using (Graphics g = Graphics.FromImage(area))
        {
            Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
            Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
            g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
        }

        // Display the result.
        pictureBox3.Image = area;
        Bitmap bm = new Bitmap(area);
        bm.Save(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
        singleFileInfo = new FileInfo(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg");
    }

    private void ScanBT_Click(object sender, EventArgs e)
    {
        var folder = @"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";

        DirectoryInfo directoryInfo;
        FileInfo[] files;
        directoryInfo = new DirectoryInfo(folder);
        files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);

        var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
        processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);
    }

    private void ProcessImages2(FileInfo[] files)
    {
        var comparableImages = new List<ComparableImage>();

        var index = 0x0;

        var operationStartTime = DateTime.Now;

        foreach (var file in files)
        {
            if (exit)
            {
                return;
            }

            var comparableImage = new ComparableImage(file);
            comparableImages.Add(comparableImage);
            index++;
        }

        index = 0;

        similarityImagesSorted = new List<SimilarityImages>();

        operationStartTime = DateTime.Now;

        var fileImage = new ComparableImage(singleFileInfo);

        for (var i = 0; i < comparableImages.Count; i++)
        {
            if (exit)
                return;

            var destination = comparableImages[i];
            var similarity = fileImage.CalculateSimilarity(destination);
            var sim = new SimilarityImages(fileImage, destination, similarity);
            similarityImagesSorted.Add(sim);
            index++;
        }

        similarityImagesSorted.Sort();
        similarityImagesSorted.Reverse();
        similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);

        con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
        con.Open();

        String getImage = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
        String getImage1 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[1].Destination.ToString() + "'";
        String getImage2 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[2].Destination.ToString() + "'";

        SqlCommand cmd = new SqlCommand(getImage, con);
        SqlDataReader rd = cmd.ExecuteReader();

        while (rd.Read())
        {
             getPath = rd["ImagePath"].ToString();
             pictureBox4.Image = Image.FromFile(getPath);
        }
        rd.Close();

        SqlCommand cmd1 = new SqlCommand(getImage1, con);
        SqlDataReader rd1 = cmd1.ExecuteReader();

        while (rd1.Read())
        {
            getPath1 = rd1["ImagePath"].ToString();
            pictureBox5.Image = Image.FromFile(getPath1);
        }
        rd1.Close();

        SqlCommand cmd2 = new SqlCommand(getImage2, con);
        SqlDataReader rd2 = cmd2.ExecuteReader();

        while (rd2.Read())
        {
            getPath2 = rd2["ImagePath"].ToString();
            pictureBox6.Image = Image.FromFile(getPath2);
        }
        con.Close();
     }

    private void pictureBox4_Click(object sender, EventArgs e)
    {
        if (pictureBox4.Image == null)
        {
            MessageBox.Show("Nothing has been scanned yet!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        else
        {
            con = new System.Data.SqlClient.SqlConnection();
            con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
            con.Open();
            String getText = "SELECT ImagePath, Character FROM CharacterImage WHERE ImagePath='" + getPath + "'";
            SqlCommand cmd = new SqlCommand(getText, con);
            SqlDataReader rd = cmd.ExecuteReader();

            while (rd.Read())
            {
                for (int i = 0; i < 1; i++)
                {
                    String imageChar = rd["Character"].ToString();
                    Action showText = () => ocrTB.AppendText(imageChar);
                    ocrTB.Invoke(showText);
                }
            }
            rd.Close();
        }

    }

Body:
BeginInvoke returns you with an IAsyncResult which you can use to wait for the operation to complete:

IAsyncResult result = processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);

You can then check whether the operation completed using the result.IsCompleted property, or you can wait on the WaitHandle returned from  result.AsyncWaitHandle.


问:
How to write dictionary with key-value pair (both having integer values) into excel through python pandas
Dictionary contains both integer values of key-value pair. If it is passed via python pandas, it results in

"ValueError: If using all scalar values, you must pass an index".
   How to overcome this problem and to write both key and value in 2 separate columns using python pandas

```<code>Dic={1:1,2:2,3:3}
</code>```

In Excel, Column A contains the dictionary key and Column B contains the dictionary values

答:
As your question is not clear to me try this if you want to create the dictionary from a dataframe:

```<code>dict(zip(df.col1, df.col2))
</code>```

I am assuming that the col1 and col2 are from the excel and you converted it to a data frame called df

And try this if you want to convert this dictionary to pandas dataframe:

```<code>df=pd.DataFrame(Dic.items(), columns=['A', 'B'])
</code>```

to convert it into excel:

```<code>df.to_csv(df.csv,index=False)
</code>```

Body:
Dictionary contains both integer values of key-value pair. If it is passed via python pandas, it results in

"ValueError: If using all scalar values, you must pass an index".
   How to overcome this problem and to write both key and value in 2 separate columns using python pandas

Dic={1:1,2:2,3:3}

In Excel, Column A contains the dictionary key and Column B contains the dictionary values

Body:
As your question is not clear to me try this if you want to create the dictionary from a dataframe:

dict(zip(df.col1, df.col2))

I am assuming that the col1 and col2 are from the excel and you converted it to a data frame called df

And try this if you want to convert this dictionary to pandas dataframe:

df=pd.DataFrame(Dic.items(), columns=['A', 'B'])

to convert it into excel:

df.to_csv(df.csv,index=False)


问:
didReceiveRemoteNotification not called Swift
For some reason my didReceiveRemoteNotification is never called. I have done the following:

checklist of APNS:

Create AppId allowed with Push Notification

Create SSL certificate with valid certificate and app id

Create Provisioning profile with same certificate and make sure to add device

With Code:

Register app for push notification

Handle didRegisterForRemoteNotificationsWithDeviceToken method

Set targets> Capability> background modes> Remote Notification
Handle didReceiveRemoteNotification

Yet my function does not seem to get called. My code looks like this:

```<code>  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    if (application.respondsToSelector("isRegisteredForRemoteNotifications"))
    {
        // iOS 8 Notifications
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (.Badge | .Sound | .Alert), categories: nil));
        application.registerForRemoteNotifications()
    }
    else
    {
        // iOS < 8 Notifications
        application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert)
    }

    return true
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for var i = 0; i < deviceToken.length; i++ {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    apnsID = tokenString
    println("******apnsID is \(apnsID)")
    dToken = deviceToken
    println("******dToken is \(dToken)")
    NSUserDefaults.standardUserDefaults().setObject(deviceToken, forKey: "deviceToken")
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    println("***********didFailToRegisterForRemoteNotificationsWithError")
    println(error)
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

    println("Getting notification")

    var message: NSString = ""
    var alert: AnyObject? = userInfo["aps"]

    println(userInfo["aps"])

    if((alert) != nil){
        var alert = UIAlertView()
        alert.title = "Title"
        alert.message = "Message"
        alert.addButtonWithTitle("OK")
        alert.show()
    }

}
</code>```

答: As I found out having the same problem myself, in order for didReceiveRemoteNotificationto be called, the incoming notification music carry an "available_content" : true parameter with the notification payload. So  in case of you sending the notification in a dictionary form , as was my case in device to device pushes, you just have to add it in the dictionary as you would  specify other parameters as you would for sound or badge, also needed if you're using some sort of push service as Postman

Body:
For some reason my didReceiveRemoteNotification is never called. I have done the following:

checklist of APNS:

Create AppId allowed with Push Notification

Create SSL certificate with valid certificate and app id

Create Provisioning profile with same certificate and make sure to add device

With Code:

Register app for push notification

Handle didRegisterForRemoteNotificationsWithDeviceToken method

Set targets> Capability> background modes> Remote Notification
Handle didReceiveRemoteNotification

Yet my function does not seem to get called. My code looks like this:

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    if (application.respondsToSelector("isRegisteredForRemoteNotifications"))
    {
        // iOS 8 Notifications
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (.Badge | .Sound | .Alert), categories: nil));
        application.registerForRemoteNotifications()
    }
    else
    {
        // iOS < 8 Notifications
        application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert)
    }

    return true
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for var i = 0; i < deviceToken.length; i++ {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    apnsID = tokenString
    println("******apnsID is \(apnsID)")
    dToken = deviceToken
    println("******dToken is \(dToken)")
    NSUserDefaults.standardUserDefaults().setObject(deviceToken, forKey: "deviceToken")
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    println("***********didFailToRegisterForRemoteNotificationsWithError")
    println(error)
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

    println("Getting notification")

    var message: NSString = ""
    var alert: AnyObject? = userInfo["aps"]

    println(userInfo["aps"])

    if((alert) != nil){
        var alert = UIAlertView()
        alert.title = "Title"
        alert.message = "Message"
        alert.addButtonWithTitle("OK")
        alert.show()
    }

}


问:
Design Android EditText to show error message as described by google
I need an EditText that looks like this onError:

calling onError looks like this instead :

Note: the app is running on SDK 19 (4.4.2)

min SDK is 1

Is there a method similar to setError that does this automatically,
or do I have to write the code for it ?

Thank you

答:
If anybody still facing the error with using google's design library as mentioned in the answer then, please use this as commented by @h_k which is -

Instead of calling setError on TextInputLayout, You might be using setError on EditText itself.


问:
How to Unit Test locale-specific local notifications
I have just added local notifications to my app. These notifications are supposed to fire only if the app Locale's regionCode (i.e. Locale.current.regionCode) is "US" or "CA". I am not interested in the locale's language.

I will also want to write the complementary test case, but once I know how to write one test case, the other will follow naturally.

Therefore, my question is: How can a Locale be injected into the test (see testSuccessfulNotificationDelivery())?

LocalNotificationTests.swift:

```<code>class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)

    // This object manages LocalNotifications
    // by building them into UNUserNotifications
    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery() {

        // setup locale and use it for testing, somehow
        let  = Locale(identifier: "en_CA")

        // The answer to my question would go here.
        // (Inject Locale into the test, somehow?)

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: .regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}
</code>```

Assume default setup() and tearDown().

答:
If you edit your scheme and select Test/Options, you can set the Application Region:

Would it be enough to have different schemes for manual testing?

Also, if you create a bot, you can set the build configuration so that it selects a certain Region:  If you define different bots, you could run the tests automatically.

Body:
I have just added local notifications to my app. These notifications are supposed to fire only if the app Locale's regionCode (i.e. Locale.current.regionCode) is "US" or "CA". I am not interested in the locale's language.

I will also want to write the complementary test case, but once I know how to write one test case, the other will follow naturally.

Therefore, my question is: How can a Locale be injected into the test (see testSuccessfulNotificationDelivery())?

LocalNotificationTests.swift:

class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)

    // This object manages LocalNotifications
    // by building them into UNUserNotifications
    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery() {

        // setup locale and use it for testing, somehow
        let  = Locale(identifier: "en_CA")

        // The answer to my question would go here.
        // (Inject Locale into the test, somehow?)

        notificationManager.schedule(notifications: [notification1, notification2],
                                     withRegionCode: .regionCode)

        let expectation = self.expectation(description: "notification delivery")

        var deliveredNotifications: [UNNotification]?

        UNUserNotificationCenter.current().getDeliveredNotifications {
            deliveredNotifications = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10, handler: nil)

        XCTAssertEqual(deliveredNotifications?.count, 2)
    }
}

Assume default setup() and tearDown().


问:
I'm trying to match dictionary keys with its values based on some rules, without using additional libraries
The dict_key contains the correct spelling and its corresponding value contains the spelling of the candidate

The function should identify the degree of correctness as mentioned below:

CORRECT, if it is an exact match

ALMOST CORRECT, if no more than 2 letters are wrong

WRONG, if more than 2 letters are wrong or if length (correct spelling versus spelling given by contestant) mismatches.

and return a list containing the number of CORRECT answers, number of ALMOST CORRECT answers and number of WRONG

My program assumes that all the words are in uppercase and max word length is 10

Here is my code:

```<code>def find_correct(word_dict):
#start writing your code here
    correct_count=0
    almost_correct_count=0
    incorrect_count=0

    for k,v in word_dict.items():
        if len(k)<=10:
            if len(k)==len(v):
                if k==v:
                    correct_count+=1
                else:
                    for i in k:
                        i_count=0
                        #print(i)
                        for j in v:
                            #print(j)
                            if not i==j:
                               i_count+=1
                               break
                    if i_count<=2:
                        almost_correct_count+=i_count
                    else:
                        incorrect_count+=i_count

            else:
                incorrect_count+=1
        else:
            incorrect_count+=1
    print(correct_count,almost_correct_count,incorrect_count)
</code>```

Driver Code:

```<code>word_dict={"WhIZZY":"MIZZLY","PRETTY":"PRESEN"}
print(find_correct(word_dict))
</code>```

My Output:
0,2,0

Expected Output:
0,0,2

答:
```<code>def find_correct(word_dict):
    correct,almost,incorrect=0,0,0
    for key,value in word_dict.items():
        count=0
        if(key==value):
            correct+=1
        elif(len(key)==len(value)):
            for i in range(0,len(key)):
                if(key[i]!=value[i]):
                    count+=1
            if(count<=2):
                almost+=1
            else:
                incorrect+=1
        else:
            incorrect+=1
    list=[correct,almost,incorrect]
    return list

    word_dict={'WHIZZY': 'MIZZLY', 'PRETTY': 'PRESEN'}
    print(find_correct(word_dict))
</code>```

Body:
The dict_key contains the correct spelling and its corresponding value contains the spelling of the candidate

The function should identify the degree of correctness as mentioned below:

CORRECT, if it is an exact match

ALMOST CORRECT, if no more than 2 letters are wrong

WRONG, if more than 2 letters are wrong or if length (correct spelling versus spelling given by contestant) mismatches.

and return a list containing the number of CORRECT answers, number of ALMOST CORRECT answers and number of WRONG

My program assumes that all the words are in uppercase and max word length is 10

Here is my code:

def find_correct(word_dict):
#start writing your code here
    correct_count=0
    almost_correct_count=0
    incorrect_count=0

    for k,v in word_dict.items():
        if len(k)<=10:
            if len(k)==len(v):
                if k==v:
                    correct_count+=1
                else:
                    for i in k:
                        i_count=0
                        #print(i)
                        for j in v:
                            #print(j)
                            if not i==j:
                               i_count+=1
                               break
                    if i_count<=2:
                        almost_correct_count+=i_count
                    else:
                        incorrect_count+=i_count

            else:
                incorrect_count+=1
        else:
            incorrect_count+=1
    print(correct_count,almost_correct_count,incorrect_count)

Driver Code:

word_dict={"WhIZZY":"MIZZLY","PRETTY":"PRESEN"}
print(find_correct(word_dict))

My Output:
0,2,0

Expected Output:
0,0,2


问:
How to get text / String from nth line of UILabel?
Is there an easy way to get (or simply display) the text from a given line in a UILabel?

My UILabel is correctly displaying my text and laying it out beautifully but occasionally I need to be able to just show certain lines but obviously I need to know how UILabel has positioned everything to do this.

I know this could easily be done with a substring but I'd need to know the start and end point of the line.

Alternatively I could scroll the UILabel if there was some kind of offset to the UILabel's frame and hide the rest of the content I didn't want to see.

I've not been able to uncover anything that shows how this could be done easily. Anyone got any good ideas?

Thanks

iphaaw

答:
Sorry, my reputation is too low to place a comment.
This is a comment to https://stackoverflow.com/a/53783203/2439941 from Philipp Jahoda.

Your code snippet worked flawless, until we enabled Dynamic Type on the UILabel. When we set the text size to the largest value in the iOS Settings app, it started to miss characters in the last line of the returned array. Or even missing the last line completely with a significant amount of text.

We managed to resolve this by using a different way to get frame:

```<code>let frameSetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.frame.width, height: .greatestFiniteMagnitude))
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attStr.length), path.cgPath, nil)
guard let lines = CTFrameGetLines(frame) as? [Any] else { return nil }
</code>```

Now it works correctly for any Dynamic Type size.

The complete function is then:

```<code>extension UILabel {

    /// creates an array containing one entry for each line of text the label has
    var lines: [String]? {

        guard let text = text, let font = font else { return nil }

        let attStr = NSMutableAttributedString(string: text)
        attStr.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: attStr.length))

        let frameSetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
        let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.frame.width, height: .greatestFiniteMagnitude))
        let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attStr.length), path.cgPath, nil)
        guard let lines = CTFrameGetLines(frame) as? [Any] else { return nil }

        var linesArray: [String] = []

        for line in lines {
            let lineRef = line as! CTLine
            let lineRange = CTLineGetStringRange(lineRef)
            let range = NSRange(location: lineRange.location, length: lineRange.length)
            let lineString = (text as NSString).substring(with: range)
            linesArray.append(lineString)
        }
        return linesArray
    }
}
</code>```

Body:
Sorry, my reputation is too low to place a comment.
This is a comment to https://stackoverflow.com/a/53783203/2439941 from Philipp Jahoda.

Your code snippet worked flawless, until we enabled Dynamic Type on the UILabel. When we set the text size to the largest value in the iOS Settings app, it started to miss characters in the last line of the returned array. Or even missing the last line completely with a significant amount of text.

We managed to resolve this by using a different way to get frame:

let frameSetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.frame.width, height: .greatestFiniteMagnitude))
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attStr.length), path.cgPath, nil)
guard let lines = CTFrameGetLines(frame) as? [Any] else { return nil }

Now it works correctly for any Dynamic Type size.

The complete function is then:

extension UILabel {

    /// creates an array containing one entry for each line of text the label has
    var lines: [String]? {

        guard let text = text, let font = font else { return nil }

        let attStr = NSMutableAttributedString(string: text)
        attStr.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: attStr.length))

        let frameSetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
        let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.frame.width, height: .greatestFiniteMagnitude))
        let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attStr.length), path.cgPath, nil)
        guard let lines = CTFrameGetLines(frame) as? [Any] else { return nil }

        var linesArray: [String] = []

        for line in lines {
            let lineRef = line as! CTLine
            let lineRange = CTLineGetStringRange(lineRef)
            let range = NSRange(location: lineRange.location, length: lineRange.length)
            let lineString = (text as NSString).substring(with: range)
            linesArray.append(lineString)
        }
        return linesArray
    }
}


问:
How make a matplotlib.Figure() accept Drop events to plot data?
I'm setting a QListWidget with Drag and Drop Mode enable with names of some data, and I want to Drop those names to a matplotlib.figure then plot it.

How can I make the Figure() accept Drop events?

I'm using the libraries PyQt5 and Matplotlib.

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        # ...

        self.parametersList = QListWidget()
        self.parametersList.setDragDropMode(QAbstractItemView.DragDrop)
        self.parametersList.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.parametersList.setAcceptDrops(True)

        # Right side of the screen
        self.graphFigure = Figure()
        self.graphCanvas = FigureCanvas(self.graphFigure)

        self.toolbar = NavigationToolbar(self.graphCanvas, self)

        self.ax = self.graphFigure.add_subplot(111)
        self.ax.tick_params(axis='y', labelcolor='tab:red')

    def enterDrop (self, data):
    ''' Something to pass data via Drop '''
        self.ax.plot(data)
```

答:
The FigureCanvas is a QWidget so you must implement drag and drop the dragEnterEvent and dropEvent methods.

import random
import string
from PyQt5 import QtCore, QtGui, QtWidgets

from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg as FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar,
)
from matplotlib.figure import Figure

import numpy as np

def random_string(string_length=10):
    letter = string.ascii_lowercase
    return "".join(random.sample(letter, string_length))

class DropCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self.setAcceptDrops(True)
        self.axes = self.figure.add_subplot(111)
        self.axes.tick_params(axis="y", labelcolor="tab:red")
        t = np.arange(0.0, 5.0, 0.01)
        y = 100 * np.exp(-t) * np.cos(2 * np.pi * t)
        self.axes.plot(t, y)

    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat(
            "application/x-qabstractitemmodeldatalist"
        ):
            event.acceptProposedAction()

    def dropEvent(self, event):
        if (
            isinstance(event.source(), QtWidgets.QListView)
            and event.possibleActions() & QtCore.Qt.CopyAction
        ):
            monkey_model = QtGui.QStandardItemModel()
            if monkey_model.dropMimeData(
                event.mimeData(),
                QtCore.Qt.CopyAction,
                0,
                0,
                QtCore.QModelIndex(),
            ):
                if (
                    monkey_model.rowCount() >= 1
                    and monkey_model.columnCount() >= 1
                ):
                    it = monkey_model.item(0, 0)
                    # get text
                    text = it.text()
                    p = event.pos()
                    width, height = self.get_width_height()
                    # In matplotlib, 0,0 is the lower left corner,
                    # whereas it's usually the upper
                    # right for most image software, so we'll flip the y-coords
                    x_pixel, y_pixel = p.x(), height - p.y()
                    x, y = self.axes.transData.inverted().transform(
                        (x_pixel, y_pixel)
                    )
                    self.axes.scatter(x, y)
                    self.axes.text(x, y, text, fontsize=12)
                    self.axes.figure.canvas.draw()
                    event.acceptProposedAction()

class Dialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        list_widget = QtWidgets.QListWidget(
            dragDropMode=QtWidgets.QAbstractItemView.DragOnly
        )
        for _ in range(10):
            text = random_string()
            it = QtWidgets.QListWidgetItem(text)
            list_widget.addItem(text)

        canvas = DropCanvas()
        toolbar = NavigationToolbar(canvas, self)

        hlay = QtWidgets.QHBoxLayout(self)
        vlay = QtWidgets.QVBoxLayout()

        hlay.addWidget(list_widget)
        hlay.addLayout(vlay)
        vlay.addWidget(toolbar)
        vlay.addWidget(canvas)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Dialog()
    w.show()
    sys.exit(app.exec_())
```


问:
what's the purpose of static read only 'Empty' in EventArgs
I'm new to C#, just a question on EventArgs class. We know the definition is :

```<code>public class EventArgs
{
   public static readonly EventArgs Empty;
   public EventArgs();
}
</code>```

and I guess one of the use is when you don't care about passing custom information

```<code>public event EventHandler<EventArgs> TestHappening;

private void MyMethod()
{
    TestHappening( this, EventArgs.Empty );
}
</code>```

but can't we achieve the same goal by using:

```<code> TestHappening( this, new EventArgs() );
</code>```

答: EventArgs.Empty is just define an instance of EventArgs without data. In C# there is a lot of class with defined property to declare a state or a kind or a value of this class to support who are just approach C#. string.Empty, int.MaxValue, etc are example for this

Body:
I'm new to C#, just a question on EventArgs class. We know the definition is :

public class EventArgs
{
   public static readonly EventArgs Empty;
   public EventArgs();
}

and I guess one of the use is when you don't care about passing custom information

public event EventHandler<EventArgs> TestHappening;

private void MyMethod()
{
    TestHappening( this, EventArgs.Empty );
}

but can't we achieve the same goal by using:

 TestHappening( this, new EventArgs() );


问:
Getting random Permission Denied errors when accessing from ExternalFilesDir
I am using NanoHTTPD to serve files to a WebView and getting random Permission denied error on some files.

This happens rarely and not on specific files, and I have observed even outside of this function.
It looks like an android bug, since the permission denial can happen to a single file in a folder of multiple files.

The folders are are stored in getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).

```<code>private InputStream loadResourceStream(String uri) {
      File initialFile = new File(uri);
      InputStream targetStream = null;
      try {
          targetStream = new FileInputStream(initialFile);
      } catch (FileNotFoundException e) {
          logNonFatalError(e);
          e.printStackTrace();
      }
      return targetStream;
}
</code>```

The error is thrown in line
targetStream = new FileInputStream(initialFile);

答: If you trying to save file then you should ask run time permission for Write file in storage.</p>

Body:
I am using NanoHTTPD to serve files to a WebView and getting random Permission denied error on some files.

This happens rarely and not on specific files, and I have observed even outside of this function.
It looks like an android bug, since the permission denial can happen to a single file in a folder of multiple files.

The folders are are stored in getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).

private InputStream loadResourceStream(String uri) {
      File initialFile = new File(uri);
      InputStream targetStream = null;
      try {
          targetStream = new FileInputStream(initialFile);
      } catch (FileNotFoundException e) {
          logNonFatalError(e);
          e.printStackTrace();
      }
      return targetStream;
}

The error is thrown in line
targetStream = new FileInputStream(initialFile);


问:
PostgreSQL and locking
Hopefully some smarter DBAs than I can help me find a good solution for what I need to do.

For the sake of discussion, lets assume I have a table called 'work' with some number of columns, one of which is a column that represents ownership of that row of work from a given client.  The scenario is that I'll have 2 clients connected and polling a table for work to be done, when a row (or some number of rows) shows up, the first client that selects the rows will also update them to imply ownership, that update will remove those rows from being returned to any other client's selects.  My question is, in this scenario, what sort of locking can I use to prevent 2 clients from hitting the table at the same time and both of them being returned the same rows via the select?

答:
My question is, in this scenario, what sort of locking can I use to prevent 2 clients from hitting the table at the same time and both of them being returned the same rows via the select?

No locking needed here.

In the UPDATE, simply specify that you only want the script to take ownership of the task if the owner is still null (assuming that's how you flag unassigned tasks).  This should work:

```<code>UPDATE foo SET owner = ? WHERE id = ? AND owner = ? WHERE owner IS NULL
</code>```

If the number of modified rows is equal to the number you expected (or a RETURNING clause returns results as suggested by @Ketema), then you successfully grabbed ownership.

Fake edit because I noticed your comment mere moments before submitting this answer:

eg: 2 clients issuing that query at the same time, they have no chance of manipulating the same rows?

Correct.  You might want to read up on MVCC.  Running these statements outside of a transaction will do the right thing.  Behavior inside a transaction will be different.

Title: PostgreSQL and locking

Body:
My question is, in this scenario, what sort of locking can I use to prevent 2 clients from hitting the table at the same time and both of them being returned the same rows via the select?

No locking needed here.

In the UPDATE, simply specify that you only want the script to take ownership of the task if the owner is still null (assuming that's how you flag unassigned tasks).  This should work:

UPDATE foo SET owner = ? WHERE id = ? AND owner = ? WHERE owner IS NULL

If the number of modified rows is equal to the number you expected (or a RETURNING clause returns results as suggested by @Ketema), then you successfully grabbed ownership.

Fake edit because I noticed your comment mere moments before submitting this answer:

eg: 2 clients issuing that query at the same time, they have no chance of manipulating the same rows?

Correct.  You might want to read up on MVCC.  Running these statements outside of a transaction will do the right thing.  Behavior inside a transaction will be different.


问:
How to fix Pyinstaller making an executable that doesn't run
I'm running python 3.7.0 32 bit version. I'm having issues turning a script into an executable. Pyinstaller successfully creates the build and dist folders and I have an executable but it doesn't do anything when I run it.

I've read other issues and I've used set Path=%Path%;C:\Windows\System32\downlevel; and i don't receive any warning about my dll files so they're all good. I have also tried on python 3.6.2 and experienced the same issues, I'm not sure whats going on.

This is the Hello World program I tried to do:

```<code>import tkinter as tk
class Go:
    def __init__(self,root):
        self.master = root
        self.frame = tk.Frame(self.master)
        self.testLabel = tk.Label(self.frame,text='hello world')
        self.testLabel.grid(row=0,column=0)
        self.frame.pack()

def main():
    root = tk.Tk()
    root.geometry('600x600')
    app = Go(root)

if __name__ == '__main__':
    main()
</code>```

Run of pyinstaller:

```<code>C:\Users\kiern\AppData\Local\Programs\Python\Python37-32\Scripts>set Path=%Path%;C:\Windows\System32\downlevel;

C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts>pyinstaller --onefile test.py
73 INFO: PyInstaller: 3.4
75 INFO: Python: 3.7.0
76 INFO: Platform: Windows-10-10.0.17763-SP0
77 INFO: wrote C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\test.spec
83 INFO: UPX is not available.
87 INFO: Extending PYTHONPATH with paths
['C:\\Users\\kiern\\AppData\\Local\\Programs\\Python\\Python37-
32\\Scripts',
'C:\\Users\\kiern\\AppData\\Local\\Programs\\Python\\Python37-
32\\Scripts']
87 INFO: checking Analysis
91 INFO: Building Analysis because Analysis-00.toc is non existent
91 INFO: Initializing module dependency graph...
96 INFO: Initializing module graph hooks...
100 INFO: Analyzing base_library.zip ...
4348 INFO: running Analysis Analysis-00.toc
4381 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:\users\kiern\appdata\local\programs\python\python37-32\python.exe
4792 INFO: Caching module hooks...
4798 INFO: Analyzing
C:\Users\kiern\AppData\Local\Programs\Python\Python37-32\Scripts\test.py
4978 INFO: Loading module hooks...
4979 INFO: Loading module hook "hook-encodings.py"...
5081 INFO: Loading module hook "hook-pydoc.py"...
5084 INFO: Loading module hook "hook-xml.py"...
5360 INFO: Loading module hook "hook-_tkinter.py"...
5624 INFO: checking Tree
5627 INFO: Building Tree because Tree-00.toc is non existent
5629 INFO: Building Tree Tree-00.toc
5751 INFO: checking Tree
5754 INFO: Building Tree because Tree-01.toc is non existent
5755 INFO: Building Tree Tree-01.toc
5798 INFO: Looking for ctypes DLLs
5798 INFO: Analyzing run-time hooks ...
5803 INFO: Including run-time hook 'pyi_rth__tkinter.py'
5814 INFO: Looking for dynamic libraries
6094 INFO: Looking for eggs
6095 INFO: Using Python library
c:\users\kiern\appdata\local\programs\python\python37-32\python37.dll
6096 INFO: Found binding redirects:
[]
6163 INFO: Warnings written to
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\warn-test.txt
6264 INFO: Graph cross-reference written to
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\xref-test.html
6323 INFO: checking PYZ
6323 INFO: Building PYZ because PYZ-00.toc is non existent
6324 INFO: Building PYZ (ZlibArchive)
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\PYZ-00.pyz
6937 INFO: Building PYZ (ZlibArchive)
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\PYZ-00.pyz completed successfully.
6947 INFO: checking PKG
6947 INFO: Building PKG because PKG-00.toc is non existent
6951 INFO: Building PKG (CArchive) PKG-00.pkg
9744 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
9812 INFO: Bootloader
c:\users\kiern\appdata\local\programs\python\python37-32\lib\site-
packages\PyInstaller\bootloader\Windows-32bit\run.exe
9812 INFO: checking EXE
9817 INFO: Building EXE because EXE-00.toc is non existent
9820 INFO: Building EXE from EXE-00.toc
9822 INFO: Appending archive to EXE
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\dist\test.exe
9832 INFO: Building EXE from EXE-00.toc completed successfully.

C:\Users\kiern\AppData\Local\Programs\Python\Python37-32\Scripts>
</code>```

My expected goal is to have an executable that actually shows something. Any help please?

Edit:
I just tried to do a simple program that does the main then prints hello world and the same issue occurred, the executable brings the cmd up for like 1 second then crashes or just stops and nothing happens

答:
Your code is fine and runs without any errors but there is no output to see because you are forgetting to add mainloop() function to show your TK window.

```<code>import tkinter as tk

class Go:
    def __init__(self, root):
        self.master = root
        self.frame = tk.Frame(self.master)
        self.testLabel = tk.Label(self.frame, text='hello world')
        self.testLabel.grid(row=0, column=0)
        self.frame.pack()
        # dont forget this
        self.master.mainloop()

def main():
    root = tk.Tk()
    root.geometry('600x600')
    Go(root)

if __name__ == '__main__':
    main()
</code>```

Then you can simply freeze your app with pyinstaller -F script.py.

Body:
I'm running python 3.7.0 32 bit version. I'm having issues turning a script into an executable. Pyinstaller successfully creates the build and dist folders and I have an executable but it doesn't do anything when I run it.

I've read other issues and I've used set Path=%Path%;C:\Windows\System32\downlevel; and i don't receive any warning about my dll files so they're all good. I have also tried on python 3.6.2 and experienced the same issues, I'm not sure whats going on.

This is the Hello World program I tried to do:

import tkinter as tk
class Go:
    def __init__(self,root):
        self.master = root
        self.frame = tk.Frame(self.master)
        self.testLabel = tk.Label(self.frame,text='hello world')
        self.testLabel.grid(row=0,column=0)
        self.frame.pack()

def main():
    root = tk.Tk()
    root.geometry('600x600')
    app = Go(root)

if __name__ == '__main__':
    main()

Run of pyinstaller:

C:\Users\kiern\AppData\Local\Programs\Python\Python37-32\Scripts>set Path=%Path%;C:\Windows\System32\downlevel;

C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts>pyinstaller --onefile test.py
73 INFO: PyInstaller: 3.4
75 INFO: Python: 3.7.0
76 INFO: Platform: Windows-10-10.0.17763-SP0
77 INFO: wrote C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\test.spec
83 INFO: UPX is not available.
87 INFO: Extending PYTHONPATH with paths
['C:\\Users\\kiern\\AppData\\Local\\Programs\\Python\\Python37-
32\\Scripts',
'C:\\Users\\kiern\\AppData\\Local\\Programs\\Python\\Python37-
32\\Scripts']
87 INFO: checking Analysis
91 INFO: Building Analysis because Analysis-00.toc is non existent
91 INFO: Initializing module dependency graph...
96 INFO: Initializing module graph hooks...
100 INFO: Analyzing base_library.zip ...
4348 INFO: running Analysis Analysis-00.toc
4381 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:\users\kiern\appdata\local\programs\python\python37-32\python.exe
4792 INFO: Caching module hooks...
4798 INFO: Analyzing
C:\Users\kiern\AppData\Local\Programs\Python\Python37-32\Scripts\test.py
4978 INFO: Loading module hooks...
4979 INFO: Loading module hook "hook-encodings.py"...
5081 INFO: Loading module hook "hook-pydoc.py"...
5084 INFO: Loading module hook "hook-xml.py"...
5360 INFO: Loading module hook "hook-_tkinter.py"...
5624 INFO: checking Tree
5627 INFO: Building Tree because Tree-00.toc is non existent
5629 INFO: Building Tree Tree-00.toc
5751 INFO: checking Tree
5754 INFO: Building Tree because Tree-01.toc is non existent
5755 INFO: Building Tree Tree-01.toc
5798 INFO: Looking for ctypes DLLs
5798 INFO: Analyzing run-time hooks ...
5803 INFO: Including run-time hook 'pyi_rth__tkinter.py'
5814 INFO: Looking for dynamic libraries
6094 INFO: Looking for eggs
6095 INFO: Using Python library
c:\users\kiern\appdata\local\programs\python\python37-32\python37.dll
6096 INFO: Found binding redirects:
[]
6163 INFO: Warnings written to
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\warn-test.txt
6264 INFO: Graph cross-reference written to
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\xref-test.html
6323 INFO: checking PYZ
6323 INFO: Building PYZ because PYZ-00.toc is non existent
6324 INFO: Building PYZ (ZlibArchive)
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\PYZ-00.pyz
6937 INFO: Building PYZ (ZlibArchive)
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\build\test\PYZ-00.pyz completed successfully.
6947 INFO: checking PKG
6947 INFO: Building PKG because PKG-00.toc is non existent
6951 INFO: Building PKG (CArchive) PKG-00.pkg
9744 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
9812 INFO: Bootloader
c:\users\kiern\appdata\local\programs\python\python37-32\lib\site-
packages\PyInstaller\bootloader\Windows-32bit\run.exe
9812 INFO: checking EXE
9817 INFO: Building EXE because EXE-00.toc is non existent
9820 INFO: Building EXE from EXE-00.toc
9822 INFO: Appending archive to EXE
C:\Users\kiern\AppData\Local\Programs\Python\Python37-
32\Scripts\dist\test.exe
9832 INFO: Building EXE from EXE-00.toc completed successfully.

C:\Users\kiern\AppData\Local\Programs\Python\Python37-32\Scripts>

My expected goal is to have an executable that actually shows something. Any help please?

Edit:
I just tried to do a simple program that does the main then prints hello world and the same issue occurred, the executable brings the cmd up for like 1 second then crashes or just stops and nothing happens

Body:
Your code is fine and runs without any errors but there is no output to see because you are forgetting to add mainloop() function to show your TK window.

import tkinter as tk

class Go:
    def __init__(self, root):
        self.master = root
        self.frame = tk.Frame(self.master)
        self.testLabel = tk.Label(self.frame, text='hello world')
        self.testLabel.grid(row=0, column=0)
        self.frame.pack()
        # dont forget this
        self.master.mainloop()

def main():
    root = tk.Tk()
    root.geometry('600x600')
    Go(root)

if __name__ == '__main__':
    main()

Then you can simply freeze your app with pyinstaller -F script.py.


问:
Kotlin - How do I concatenate a String to an Int value?
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

```<code>for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}
</code>```

Expected Outcome

15 14 13 12 11 10

答:
You've got several options:

1. String templates. I think it is the best one. It works absolutely like 2-st solution, but looks better and allow to add some needed characters.

```<code>print("$i")
</code>```

and if you want to add something

```<code>print("$i ")
print("$i - is good")
</code>```

to add some expression place it in brackets

```<code>print("${i + 1} - is better")
</code>```

2. toString method which can be used for any object in kotlin.

```<code>print(i.toString())
</code>```

3. Java-like solution with concatenating

```<code>print("" + i)
</code>```

Body:
A very basic question, What is the right approach to concatenate String to an Int?

I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.

for (i in 15 downTo 10){
  print(i + " "); //error: None of the following function can be called with the argument supplied:
  print(i); //It's Working but I need some space after the integer value.
}

Expected Outcome

15 14 13 12 11 10

Body:
You've got several options:

1. String templates. I think it is the best one. It works absolutely like 2-st solution, but looks better and allow to add some needed characters.

print("$i")

and if you want to add something

print("$i ")
print("$i - is good")

to add some expression place it in brackets

print("${i + 1} - is better")

2. toString method which can be used for any object in kotlin.

print(i.toString())

3. Java-like solution with concatenating

print("" + i)


问:
How do I know which image the user clicked?
I am setting up a new website and I want to be able to detect which pizza the user clicked on the OnlinePizzaOrderingPage.html and echo the name of the pizza that was clicked onto the ShoppingCart.php.

I have tried creating a form, but I cannot create a form because the task requirement is that I cannot use a form and the user must click on the image. I have tried to use get and post but does not work without form.

OnlinePizzaOrderingPage.html

```<code> <!DOCTYPE html>
<html>
    <head>
        <title>Online Pizza Ordering Page</title>
    </head>
    <body>
        <h1>Online Pizza Ordering Page</h1>
        <a href="Detailedsauceandquantitypage.html"><img src="supreme.jpg"
        width="82" height="86" title="Detailed sauce and quantity page"
        alt="Supreme"></a>
        <a href="Detailedsauceandquantitypage.html"><img src="meatlover.jpg"
        width="82" height="86" title="Detailed sauce and quantity page"
        alt="Meatlover"></a>
        <a href="Detailedsauceandquantitypage.html"><img src="hawaii.jpg"
        width="82" height="86" title="Detailed sauce and quantity page"
        alt="Hawaii"></a>
        <a href="Detailedsauceandquantitypage.html"><img src="fourseasons.jpg"
        width="82" height="86" title="Detailed sauce and quantity page" alt="Four
        Seasons"></a>
        <a href="Detailedsauceandquantitypage.html"><img src="vege.jpg" width="82"
        height="86" title="Detailed sauce and quantity page" alt="Vege"></a>
    </body>
</html>
</code>```

ShoppingCart.php

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Shopping Cart page</title>
    </head>
    <body>
        <h1>Shopping Cart page</h1>
        <?php
        // define variables and set to empty values
        $bbqPizza = $tomatoPizza = $salsaPizza = "";

        if ( isset( $_POST['submit'] ) ) {
            $bbq = $_POST["bbqPizza"];
            $tomato = $_POST["tomatoPizza"];
            $salsa = $_POST["salsaPizza"];
            echo $bbq . " pizzas with bbq sauce, " . $tomato . " pizzas with tomato sauce and " . $salsa . " pizzas with salsa sauce.";
        }
        ?>
        <br>
        <a href="OnlinePizzaOrderingPage.html">Add more pizzas to cart</a>
        <a href="Checkoutpage.html">Go to checkout</a>
    </body>
</html>
</code>```

I expected the Checkoutpage.html to be able to echo the pizza name corresponding to the pizza image that the user clicked on in Online Pizza Ordering Page. The actual results is nothing.

答:
You can use jquery for this purpose

```<code>$(function(){
$('a').click(function(e) {
    e.preventDefault();
    var img_title = $('img', this).attr('title');
    alert(img_title);
 });
});
</code>```

For javascript you need to pass title in function in every img tag like this

```<code><img src="supreme.jpg"
width="82" height="86" title="Detailed sauce and quantity page"
alt="Supreme" onclick="imageTitle(this.title);">
</code>```

Then in javascript

```<code><script>
function imageTitle(title){
 alert(title);
 console.log(title);
}
</script>
</code>```

Body:
I am setting up a new website and I want to be able to detect which pizza the user clicked on the OnlinePizzaOrderingPage.html and echo the name of the pizza that was clicked onto the ShoppingCart.php.

I have tried creating a form, but I cannot create a form because the task requirement is that I cannot use a form and the user must click on the image. I have tried to use get and post but does not work without form.

OnlinePizzaOrderingPage.html

 <!DOCTYPE html>

        <title>Online Pizza Ordering Page</title>

Online Pizza Ordering Page

ShoppingCart.php

<!DOCTYPE html>

        <title>Shopping Cart page</title>

Shopping Cart page

        <?php
        // define variables and set to empty values
        $bbqPizza = $tomatoPizza = $salsaPizza = "";

        if ( isset( $_POST['submit'] ) ) {
            $bbq = $_POST["bbqPizza"];
            $tomato = $_POST["tomatoPizza"];
            $salsa = $_POST["salsaPizza"];
            echo $bbq . " pizzas with bbq sauce, " . $tomato . " pizzas with tomato sauce and " . $salsa . " pizzas with salsa sauce.";
        }
        ?>

        Add more pizzas to cart
        Go to checkout

I expected the Checkoutpage.html to be able to echo the pizza name corresponding to the pizza image that the user clicked on in Online Pizza Ordering Page. The actual results is nothing.

Body:
You can use jquery for this purpose

$(function(){
$('a').click(function(e) {
    e.preventDefault();
    var img_title = $('img', this).attr('title');
    alert(img_title);
 });
});

For javascript you need to pass title in function in every img tag like this

<img src="supreme.jpg"
width="82" height="86" title="Detailed sauce and quantity page"
alt="Supreme" onclick="imageTitle(this.title);">

Then in javascript

<script>
function imageTitle(title){
 alert(title);
 console.log(title);
}
</script>


问:
Select column name per row for max value in PySpark
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

```<code>data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+
</code>```

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

```<code>+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+
</code>```

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

答:
You can use the RDD API to add the new column:

```<code>df.rdd.map(lambda r: r.asDict())\
       .map(lambda r: Row(Max_col=max([i for i in r.items() if i[0] != 'ID'],
                                      key=lambda kv: kv[1])[0], **r) )\
       .toDF()
</code>```

Resulting in:

```<code>+---+-------+----+----+
| ID|Max_col|colA|colB|
+---+-------+----+----+
|ID1|   colB|   3|   5|
|ID2|   colB|   4|  12|
|ID3|   colA|   8|   3|
+---+-------+----+----+
</code>```

Body:
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

Body:
You can use the RDD API to add the new column:

df.rdd.map(lambda r: r.asDict())\
       .map(lambda r: Row(Max_col=max([i for i in r.items() if i[0] != 'ID'],
                                      key=lambda kv: kv[1])[0], **r) )\
       .toDF()

Resulting in:

+---+-------+----+----+
| ID|Max_col|colA|colB|
+---+-------+----+----+
|ID1|   colB|   3|   5|
|ID2|   colB|   4|  12|
|ID3|   colA|   8|   3|
+---+-------+----+----+


问:
How to write a long os.path.join chain while complying to PEP8
I am using a long chain of os.path.join() to generate a path (it ensures the path will work on any OS).

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',os.path.join('config', os.path.join('metadata',os.path.join('gmail_metadata.xml'))))),
```

<p>I would like to break it down into multiple lines the PEP8 way but I can't seem to make this happen.</p>

<p>I tried several things: </p>

<pre class="lang-py prettyprint-override"><code>"metadata": os.path.join(BASE_DIR,
            os.path.join('ServiceProvider',
            os.path.join('config',
            os.path.join('metadata',
            os.path.join('gmail_metadata.xml'))))),
</code>```

will get me the PEP8 error continuation line under-indented for visual indentpep8(E128)

and

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',
                                                    os.path.join('config', os.path.join('metadata',
                                                                                os.path.join('gmail_metadata.xml'))))),
```

which is actually what PEP8 autofix did, I'm getting the line too long error.

If it is not possible to fix the PEP8 errors in this case I would still like to know how you would do it !

答:
You can make a list of all paths you want to join, and use list-unpacking (more details in the PEP-3132 to unpack all your arguments and pass it to os.path.join

```<code>import os

#List of paths
li = [BASE_PATH,'ServiceProvider', 'config', 'metadata','gmail_metadata.xml']

#Join all paths by unpacking the list
path = os.path.join(*li)
print(path)
</code>```

Body:
I am using a long chain of os.path.join() to generate a path (it ensures the path will work on any OS).

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',os.path.join('config', os.path.join('metadata',os.path.join('gmail_metadata.xml'))))),

I would like to break it down into multiple lines the PEP8 way but I can't seem to make this happen.

I tried several things:

"metadata": os.path.join(BASE_DIR,
            os.path.join('ServiceProvider',
            os.path.join('config',
            os.path.join('metadata',
            os.path.join('gmail_metadata.xml'))))),

will get me the PEP8 error continuation line under-indented for visual indentpep8(E128)

and

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',
                                                    os.path.join('config', os.path.join('metadata',
                                                                                os.path.join('gmail_metadata.xml'))))),

which is actually what PEP8 autofix did, I'm getting the line too long error.

If it is not possible to fix the PEP8 errors in this case I would still like to know how you would do it !

Body:
You can make a list of all paths you want to join, and use list-unpacking (more details in the PEP-3132 to unpack all your arguments and pass it to os.path.join

import os

#List of paths
li = [BASE_PATH,'ServiceProvider', 'config', 'metadata','gmail_metadata.xml']

#Join all paths by unpacking the list
path = os.path.join(*li)
print(path)


问:
R - image of a pixel matrix?
How would you you make an image from a matrix in R?

Matrix values would correspond to pixel intensity on image (although I am just interested in 0,1 values white or black at the moment.), while column and row numbers correspond to vertical and horizontal location on the image.

By make an image I mean display it on the screen and save it as a jpg.

答:
I do a matrix (where the vertical axis increases going down) one of two ways.  Below is the first way using heatmap.2().  It has more control over how the numeric values are formatted in the plot (see the formatC statement below), but is a little harder to deal with when changing the layout.

```<code> library(gplots)

 #Build the matrix data to look like a correlation matrix
 x <- matrix(rnorm(64), nrow=8)
 x <- (x - min(x))/(max(x) - min(x)) #Scale the data to be between 0 and 1
 for (i in 1:8) x[i, i] <- 1.0 #Make the diagonal all 1's

 #Format the data for the plot
 xval <- formatC(x, format="f", digits=2)
 pal <- colorRampPalette(c(rgb(0.96,0.96,1), rgb(0.1,0.1,0.9)), space = "rgb")

 #Plot the matrix
 x_hm <- heatmap.2(x, Rowv=FALSE, Colv=FALSE, dendrogram="none", main="8 X 8 Matrix Using Heatmap.2", xlab="Columns", ylab="Rows", col=pal, tracecol="#303030", trace="none", cellnote=xval, notecol="black", notecex=0.8, keysize = 1.5, margins=c(5, 5))
</code>```

Title: R - image of a pixel matrix?

Body:
I do a matrix (where the vertical axis increases going down) one of two ways.  Below is the first way using heatmap.2().  It has more control over how the numeric values are formatted in the plot (see the formatC statement below), but is a little harder to deal with when changing the layout.

 library(gplots)

 #Build the matrix data to look like a correlation matrix
 x <- matrix(rnorm(64), nrow=8)
 x <- (x - min(x))/(max(x) - min(x)) #Scale the data to be between 0 and 1
 for (i in 1:8) x[i, i] <- 1.0 #Make the diagonal all 1's

 #Format the data for the plot
 xval <- formatC(x, format="f", digits=2)
 pal <- colorRampPalette(c(rgb(0.96,0.96,1), rgb(0.1,0.1,0.9)), space = "rgb")

 #Plot the matrix
 x_hm <- heatmap.2(x, Rowv=FALSE, Colv=FALSE, dendrogram="none", main="8 X 8 Matrix Using Heatmap.2", xlab="Columns", ylab="Rows", col=pal, tracecol="#303030", trace="none", cellnote=xval, notecol="black", notecex=0.8, keysize = 1.5, margins=c(5, 5))


问:
How to add a language to JSPDF?
I'm using JsPDF and there's some problem with special characters. I'm creating a web-site pdf page where text is in Azerbaijani language (such letters as Ə,Ş are visualized). How can I fix this? Please help me

I've tried to use some custom fonts which must support those characters but the problems stays

```<code>doc.text(20, 40, "gəlirəm şabalıd");
</code>```

output: glirm abalıd

答:
Try using a version of jsPDF >= 1.40 which supports UTF-8 characters. Which custom font are you using? I would suggest "Arial Unicode MS" or "Courier New", which can be found in system fonts. </p>

<p>As a final resort you could also try creating images with the problematic characters and replace the char with an image. </p>

Title: How to add a language to JSPDF?

Body:
I'm using JsPDF and there's some problem with special characters. I'm creating a web-site pdf page where text is in Azerbaijani language (such letters as Ə,Ş are visualized). How can I fix this? Please help me

I've tried to use some custom fonts which must support those characters but the problems stays

doc.text(20, 40, "gəlirəm şabalıd");

output: glirm abalıd

Body:
Try using a version of jsPDF >= 1.40 which supports UTF-8 characters. Which custom font are you using? I would suggest "Arial Unicode MS" or "Courier New", which can be found in system fonts.

As a final resort you could also try creating images with the problematic characters and replace the char with an image.


问:
How to remove global "use strict" added by babel
I'm using function form of "use strict" and don't want global form which Babel adds after transpilation. The problem is I'm using some libraries that aren't using "use strict" mode and it might throw error after scripts are concatenated</p>

答:
```<code>plugins: [
    [
        require("@babel/plugin-transform-modules-commonjs"),
        {
            strictMode: false
        }
    ],
]
</code>```


答:
It's preferable to use EventArgs.Empty for two reasons:

Checking if arguments are empty is convenient

```<code>EventArgs newArgs = new EventArgs();
EventArgs emptyArgs = EventArgs.Empty;
Console.WriteLine(newArgs == EventArgs.Empty); // false
Console.WriteLine(emptyArgs == EventArgs.Empty); // true
</code>```

No extra memory allocation because you essentially use the same class instance.

Title: what's the purpose of static read only 'Empty' in EventArgs

Body:
It's preferable to use EventArgs.Empty for two reasons:

Checking if arguments are empty is convenient

EventArgs newArgs = new EventArgs();
EventArgs emptyArgs = EventArgs.Empty;
Console.WriteLine(newArgs == EventArgs.Empty); // false
Console.WriteLine(emptyArgs == EventArgs.Empty); // true

No extra memory allocation because you essentially use the same class instance.


问:
Selenium Duplicate Elements marked with ==$0
How to handle duplicate elements in selenium, where duplicate elements comes marked with ==$0 ?

Go to www.google.com and search for google search button, I have tried iterator and creating list, but, is this correct way of handling ==$0

```<code>driver.findElements(By.xpath("//input[@aria-label='Google Search']"));
</code>```

I want to select second element.

答:
You are getting two values while using //input[@aria-label='Google Search']

One of the possible solution is to use: (//input[@aria-label='Google Search'])[ 2 ] (the value in the solid brackets i.e. 2 should be without spaces)

Eg - driver.findElement(By.xpath("(//input[@aria-label='Google Search'])[ 2 ]"); //(the value in the solid brackets i.e. 2 should be without spaces)

Body:
How to handle duplicate elements in selenium, where duplicate elements comes marked with ==$0 ?

Go to www.google.com and search for google search button, I have tried iterator and creating list, but, is this correct way of handling ==$0

driver.findElements(By.xpath("//input[@aria-label='Google Search']"));

I want to select second element.


问:
How to view PDF file before uploading
I'm implementing some code to to view a PDF file after selecting it from our computer, but I am getting some errors

I have tried with 'pdf.js' but I'm getting some error that 'PDFJS' or 'pdfjsLib' is not defined

```<code>function showInCanvas(url) {

                'use strict';

                var pdfAsArray = convertDataURIToBinary(url);

                pdfjsLib.getDocument(pdfAsArray).then(function (pdf) {

                    pdf.getPage(1).then(function (page) {
                        var scale = 1.5;
                        var viewport = page.getViewport(scale);

                        var canvas = document.getElementById('the-canvas');
                        var context = canvas.getContext('2d');
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;

                        var renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };
                        page.render(renderContext);
                    });
                });
            }
</code>```

The error message that I get is:

```<code>Uncaught ReferenceError: pdfjsLib is not defined
</code>```

答:
Why are you depend on external library to preview pdf file even you could do it using iframe object.you just need to read file from file control and assign file object to iframe.

```<code>   var file =document.getElementById("filecontrol").files[0];
   var url =URL.createObjectURL(file );
   $('#iframeid').attr('src',url);
</code>```

HTML :

```<code><iframe id="iframeid" width="x" height="y"></iframe>
</code>```

Title: How to view PDF file before uploading

Body:
I'm implementing some code to to view a PDF file after selecting it from our computer, but I am getting some errors

I have tried with 'pdf.js' but I'm getting some error that 'PDFJS' or 'pdfjsLib' is not defined

function showInCanvas(url) {

                'use strict';

                var pdfAsArray = convertDataURIToBinary(url);

                pdfjsLib.getDocument(pdfAsArray).then(function (pdf) {

                    pdf.getPage(1).then(function (page) {
                        var scale = 1.5;
                        var viewport = page.getViewport(scale);

                        var canvas = document.getElementById('the-canvas');
                        var context = canvas.getContext('2d');
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;

                        var renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };
                        page.render(renderContext);
                    });
                });
            }

The error message that I get is:

Uncaught ReferenceError: pdfjsLib is not defined

Body:
Why are you depend on external library to preview pdf file even you could do it using iframe object.you just need to read file from file control and assign file object to iframe.

   var file =document.getElementById("filecontrol").files[0];
   var url =URL.createObjectURL(file );
   $('#iframeid').attr('src',url);

HTML :

<iframe id="iframeid" width="x" height="y"></iframe>