问:
Applying multiple formats to same data in excel using perl
I have a situation where I am writing data to an Excel file using Excel::Writer::XLSX with Perl. I have records stored as comma delimited strings in an array. For example:

```<code>$array[0] = "col1_value,col2_value,col3_value,col4_value" # row 1
$array[1] = "col1_value,col2_value,col3_value,col4_value" # row 2
.
.
$array[$n]                                                # row n
</code>```

Now I have to display these data in Excel with center alignment,border and bg_color. So I have done the below:

```<code>my $general_format = $workbook->add_format(
border => 1,
bg_color => 31,
align => 'center'
);
</code>```

And then I have put a loop on the array and after splitting it, I am putting all columns of each record in excel as below:

```<code>Loop on array of records{
$worksheet->write_row( $i+2, 0, $recordRef, $general_format );
}
</code>```

But I am facing issue that col1 & col2 of each record has numbers whereas col3 & col4 are percentage/date, etc. I need the numbers to be formatted in comma-separated format. If I do the below, the output is fine but when we click the col3/col4 cell in Excel, it converts the percentage/date to number format:

```<code>my $general_format = $workbook->add_format(
border => 1,
bg_color => 31,
align => 'center',
num_format => '#,##0'
);
</code>```

Is there any way to apply the num_format => '#,##0' format specifically on col1 & col2 along with the rest of the formatting done on col1 & col2(the color/alignment/etc) as the data being written is row(record)-wise?

I need col1 and col2 to have below formats:

```<code>border => 1,
bg_color => 31,
align => 'center',
num_format => '#,##0'
</code>```

and col3 and col4 to have below formats:

```<code>border => 1,
bg_color => 31,
align => 'center'
</code>```

But I can write data record wise only(using write_row()), not column by column.

答:
You cannot pass multiple formats to the write_row method. However, you can set a default format for each column before you write the row with set_column.

Here's a short example.

```<code>use strict;
use warnings;
use Excel::Writer::XLSX;

my $workbook = Excel::Writer::XLSX->new( 'perl.xlsx' );
my $worksheet = $workbook->add_worksheet();

my $general_format = $workbook->add_format(
    border => 1,
    bg_color => 31,
    align => 'center',
);

my $num_format = $workbook->add_format();
$num_format->copy($general_format); # we have to copy the other format options
$num_format->set_num_format('#.##0');

# set column formats up front
$worksheet->set_column( 'A:B', undef, $num_format);
$worksheet->set_column( 'C:D', undef, $general_format);

my @records = (
    [qw/ 1.1 11.111 1% 2017-12-05/],
    [qw/ 2.2 22.222 2.2% 2017-12-05/],
    [qw/ 3.3 33.333 3.33% 2017-12-05/],
    [qw/ 4.4 44.444 4.444% 2017-12-05/],
);
my $i = 1;
foreach my $record ( @records) {
    $worksheet->write_row( $i, 0, $record ); # no more format here
    ++$i;
}
</code>```

This is what it will look like (with the Excel Viewer).

It's important to note that set_column only writes a format if there is no other format present in a cell.

The $format parameter will be applied to any cells in the column that don't have a format.

You also need to take care of the order in which formats are applied.

If you wish to define a column format in this way you should call the method before any calls to write(). If you call it afterwards it won't have any effect.

A default row format takes precedence over a default column format

Body:
I have a situation where I am writing data to an Excel file using Excel::Writer::XLSX with Perl. I have records stored as comma delimited strings in an array. For example:

$array[0] = "col1_value,col2_value,col3_value,col4_value" # row 1
$array[1] = "col1_value,col2_value,col3_value,col4_value" # row 2
.
.
$array[$n]                                                # row n

Now I have to display these data in Excel with center alignment,border and bg_color. So I have done the below:

my $general_format = $workbook->add_format(
border => 1,
bg_color => 31,
align => 'center'
);

And then I have put a loop on the array and after splitting it, I am putting all columns of each record in excel as below:

Loop on array of records{
$worksheet->write_row( $i+2, 0, $recordRef, $general_format );
}

But I am facing issue that col1 & col2 of each record has numbers whereas col3 & col4 are percentage/date, etc. I need the numbers to be formatted in comma-separated format. If I do the below, the output is fine but when we click the col3/col4 cell in Excel, it converts the percentage/date to number format:

my $general_format = $workbook->add_format(
border => 1,
bg_color => 31,
align => 'center',
num_format => '#,##0'
);

Is there any way to apply the num_format => '#,##0' format specifically on col1 & col2 along with the rest of the formatting done on col1 & col2(the color/alignment/etc) as the data being written is row(record)-wise?

I need col1 and col2 to have below formats:

border => 1,
bg_color => 31,
align => 'center',
num_format => '#,##0'

and col3 and col4 to have below formats:

border => 1,
bg_color => 31,
align => 'center'

But I can write data record wise only(using write_row()), not column by column.

Body:
You cannot pass multiple formats to the write_row method. However, you can set a default format for each column before you write the row with set_column.

Here's a short example.

use strict;
use warnings;
use Excel::Writer::XLSX;

my $workbook = Excel::Writer::XLSX->new( 'perl.xlsx' );
my $worksheet = $workbook->add_worksheet();

my $general_format = $workbook->add_format(
    border => 1,
    bg_color => 31,
    align => 'center',
);

my $num_format = $workbook->add_format();
$num_format->copy($general_format); # we have to copy the other format options
$num_format->set_num_format('#.##0');

# set column formats up front
$worksheet->set_column( 'A:B', undef, $num_format);
$worksheet->set_column( 'C:D', undef, $general_format);

my @records = (
    [qw/ 1.1 11.111 1% 2017-12-05/],
    [qw/ 2.2 22.222 2.2% 2017-12-05/],
    [qw/ 3.3 33.333 3.33% 2017-12-05/],
    [qw/ 4.4 44.444 4.444% 2017-12-05/],
);
my $i = 1;
foreach my $record ( @records) {
    $worksheet->write_row( $i, 0, $record ); # no more format here
    ++$i;
}

This is what it will look like (with the Excel Viewer).

It's important to note that set_column only writes a format if there is no other format present in a cell.

The $format parameter will be applied to any cells in the column that don't have a format.

You also need to take care of the order in which formats are applied.

If you wish to define a column format in this way you should call the method before any calls to write(). If you call it afterwards it won't have any effect.

A default row format takes precedence over a default column format


来源: stackexchange

问:
Is it possible to add more information/functionality than just a title in a marker in Google Maps?
Using the following line of code (with latlongVariable being coordinates for a location), I can add a marker to a map which will then produce a title of the location when clicked.

```<code>mMap.addMarker(new MarkerOptions().position(latlongVariable).title("Marker Location Title"))
</code>```

My question is, is it possible to add more than simply a title to the marker? For example, could I include a list view displaying more information about the location as well, maybe including a button that will send the user to another activity when clicked?

I've tried to research Android Google Map's onMapReady() method and it's functionality but I can't find the answers I'm looking for. Any suggestions?

答:
It's quite easy - one only has to listen to the OnMarkerClickListener and then show a custom PopupWindow above the marker. Some other guys here on StackOverflow suggested this solution and it actually looks quite good at first glance.

You can use github library as @Waleed Asim suggests for interactiveInfoWindow

ContentLicense: CC BY-SA 3.0

Body:
Using the following line of code (with latlongVariable being coordinates for a location), I can add a marker to a map which will then produce a title of the location when clicked.

mMap.addMarker(new MarkerOptions().position(latlongVariable).title("Marker Location Title"))

My question is, is it possible to add more than simply a title to the marker? For example, could I include a list view displaying more information about the location as well, maybe including a button that will send the user to another activity when clicked?

I've tried to research Android Google Map's onMapReady() method and it's functionality but I can't find the answers I'm looking for. Any suggestions?


问:
Scrapy response.css /xpath with broken HTML. Any tips?
I am still learning scrapy and am trying to scrape some information from this page: Schlotzskys store

However, after parsing the page with scrapy through the scrapy shell I run into some issues specifically with parsing the address on the site.

First I run the following in the shell:

```<code>pipenv run scrapy shell https://www.schlotzskys.com/find-your-schlotzskys/arkansas/fayetteville/2146/
</code>```

All turns out well with this. Then I make an attempt at scraping the address.
I tried the following ways:

```<code>response.css('div.col-xs-12 col-sm-6 col-md-6')
response.css('div.container locations-mid-container')
response.xpath('//div[@class="locations-info"]')
response.css('div.locations-address')
</code>```

The first two inputs above return:

[]

The second two inputs return:

Selector xpath="descendant-or-self::div[@class and contains(concat('
  ', normalize-space(@class), ' '), ' locations-address ')]/text()"
  data='\n\t\t\t\t\t131 N. McPherson Church Rd.\t\t\t\t'

or a variant of that.

Now I looked at the HTML from:

```<code>print(response.text)
</code>```

The HTML I am interested in does show up, but just does not seem to parse in scrapy. It seems it might be broken HTML, I am wondering if there is any way around this?

I appreciate anybodies help very very much!

答:
I couldn't find element on page by CSS selector given in first expression. All your expressions are missing the extract() or extract_first() method call, so you are working with Selectors.

Try this:

```<code>address = [
    response.xpath('normalize-space(//div[@class="locations-address"])').extract_first(),
    response.xpath('normalize-space(//div[@class="locations-address-secondary"])').extract_first(),
    response.xpath('normalize-space(//div[@class="locations-state-city-zip"])').extract_first()
]
</code>```

The normalize-space() XPath function removes the annoying whitespaces.

Body:
I am still learning scrapy and am trying to scrape some information from this page: Schlotzskys store

However, after parsing the page with scrapy through the scrapy shell I run into some issues specifically with parsing the address on the site.

First I run the following in the shell:

pipenv run scrapy shell https://www.schlotzskys.com/find-your-schlotzskys/arkansas/fayetteville/2146/

All turns out well with this. Then I make an attempt at scraping the address.
I tried the following ways:

response.css('div.col-xs-12 col-sm-6 col-md-6')
response.css('div.container locations-mid-container')
response.xpath('//div[@class="locations-info"]')
response.css('div.locations-address')

The first two inputs above return:

[]

The second two inputs return:

Selector xpath="descendant-or-self::div[@class and contains(concat('
  ', normalize-space(@class), ' '), ' locations-address ')]/text()"
  data='\n\t\t\t\t\t131 N. McPherson Church Rd.\t\t\t\t'

or a variant of that.

Now I looked at the HTML from:

print(response.text)

The HTML I am interested in does show up, but just does not seem to parse in scrapy. It seems it might be broken HTML, I am wondering if there is any way around this?

I appreciate anybodies help very very much!

Body:
I couldn't find element on page by CSS selector given in first expression. All your expressions are missing the extract() or extract_first() method call, so you are working with Selectors.

Try this:

address = [
    response.xpath('normalize-space(//div[@class="locations-address"])').extract_first(),
    response.xpath('normalize-space(//div[@class="locations-address-secondary"])').extract_first(),
    response.xpath('normalize-space(//div[@class="locations-state-city-zip"])').extract_first()
]

The normalize-space() XPath function removes the annoying whitespaces.


问:
Show user specific data from database based on LoginID username
I am attempting to convert an online game i have written in ASP into ASP.NET,, but I am failing at a very early and probably a very amateurish stage.

I am using a Sample ASPX project.
There is an ASPNETDB database included, when i register my username is added to the DB along with a userID and various other fields.   This is stored in a table called aspnet_Users.

The Login Control is stored in a Site.Master file

```<code><div class="loginDisplay">
            <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false"
                onviewchanged="HeadLoginView_ViewChanged">
                <AnonymousTemplate>
                    [ <a href="~/Account/Login.aspx" ID="HeadLoginStatus" runat="server">Log In</a> ]
                </AnonymousTemplate>
                <LoggedInTemplate>
                    Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /></span>!
                    [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
                </LoggedInTemplate>
            </asp:LoginView>
</code>```

I have created a new table called tblClubs, which stores information such as ClubName, StadiumCapacity etc
I added a field called 'Owner' and this is directly related to the UserName field in the aspnet_Users table

What I am trying to solve is to show user specific information from the database, based on their LoginID.

i.e

My username is Laclerque and my club is called Racing Mongoose, the stadium capacity is 9500..  the information for each User needs to be different and just show the information that is relevant to them.

obviously in the longer term, there is going to be 100's of these associations required for the full game, but not until i can get my head around the basics of how to set this information.  I tend to work better when i can see a working sample, and then adapt things to suit my needs.

Hope this is enough information, and thanks in advance if anyone can help.

答:
You can take a look at asp.net's online example: Here

Hope that helps!

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to convert an online game i have written in ASP into ASP.NET,, but I am failing at a very early and probably a very amateurish stage.

I am using a Sample ASPX project.
There is an ASPNETDB database included, when i register my username is added to the DB along with a userID and various other fields.   This is stored in a table called aspnet_Users.

The Login Control is stored in a Site.Master file

            <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false"
                onviewchanged="HeadLoginView_ViewChanged">
                <AnonymousTemplate>
                    [ Log In ]
                </AnonymousTemplate>
                <LoggedInTemplate>
                    Welcome <asp:LoginName ID="HeadLoginName" runat="server" />!
                    [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
                </LoggedInTemplate>
            </asp:LoginView>

I have created a new table called tblClubs, which stores information such as ClubName, StadiumCapacity etc
I added a field called 'Owner' and this is directly related to the UserName field in the aspnet_Users table

What I am trying to solve is to show user specific information from the database, based on their LoginID.

i.e

My username is Laclerque and my club is called Racing Mongoose, the stadium capacity is 9500..  the information for each User needs to be different and just show the information that is relevant to them.

obviously in the longer term, there is going to be 100's of these associations required for the full game, but not until i can get my head around the basics of how to set this information.  I tend to work better when i can see a working sample, and then adapt things to suit my needs.

Hope this is enough information, and thanks in advance if anyone can help.


问:
didSelectRowAtIndexPath not being called because of UI tap Gesture Swift Solution?
I have written my own function to scroll text fields up when the keyboard shows up. In order to dismiss the keyboard by tapping away from the text field, I've created a UITapGestureRecognizer that takes care of resigning first responder on the text field when tapping away.

However, when selecting one of the entries in the auto completed table, didSelectRowAtIndexPath does not get called. Instead, it seems that the tap gesture recognizer is getting called and just resigns first responder.

I'm guessing there's some way to tell the tap gesture recognizer to keep passing the tap message on down to the UITableView, but I can't figure out what it is. There are only solutions for this in objc and posts from over 9 years ago on stack overflow , I was wondering if there was an updated solution to this! Thank you , Here is my code if you would like to see whats going on :

```<code>class ChatLogController : UIViewController, UITextFieldDelegate , UITableViewDelegate , UITableViewDataSource, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate ,UINavigationControllerDelegate  {

var messages = [Message]()

var user : User?{
    didSet{
     observeMessages()
    }
}

@IBOutlet weak var tabelView: UITableView!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var currentMessageRecieverImage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    configureTableView()

    currentMessageRecieverImage.translatesAutoresizingMaskIntoConstraints = false;
    currentMessageRecieverImage.layer.cornerRadius = 30;
    currentMessageRecieverImage.layer.masksToBounds = true
    currentMessageRecieverImage.contentMode = .scaleAspectFill
    if let currentMessageRecieverUser = user{
        currentMessageRecieverImage.loadImageUsingCacheWithUrlString(urlString: currentMessageRecieverUser.picURL!);
        print(currentMessageRecieverUser.userName!)
    }

    tabelView.delegate = self;
    tabelView.dataSource = self;
    messageTextField.delegate = self;

    let dragAwayFromTextGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    dragAwayFromTextGesture.direction = UISwipeGestureRecognizerDirection.down
    dragAwayFromTextGesture.delegate = self;
    tabelView.addGestureRecognizer(dragAwayFromTextGesture)

    let dragBackToMessages = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeBackToMessages))
    dragBackToMessages.direction = UISwipeGestureRecognizerDirection.right
    dragBackToMessages.delegate = self;
    tabelView.addGestureRecognizer(dragBackToMessages)

    let TapAwayFromTextEditTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    tabelView.addGestureRecognizer(TapAwayFromTextEditTapGesture)
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

@objc func handleSwipeBackToMessages(){
    dismiss(animated: false, completion: nil)
}

func observeMessages(){
    guard let uid = Auth.auth().currentUser?.uid else{
        return;
    }
    // ref gets user that is logged in
    let ref = Database.database().reference().child("user-messages").child(uid)
    ref.observe(.childAdded) { (snapshot) in
        // gets needed messages
        let messageId = snapshot.key
        let messagesRef = Database.database().reference().child("messages").child(messageId)

        messagesRef.observe(.value, with: { (snapshot) in
            guard let dict = snapshot.value as? [String : AnyObject] else{
                return
            }
            let message = Message()
            message.imageUrl = dict["imageurl"] as? String
            message.fromId = dict["fromid"] as? String
            message.text = dict["text"] as? String
            message.timestamp = dict["timestamp"] as? String
            message.toId = dict["toid"] as? String

            if message.chatPartnerId() == self.user?.toId{
            self.messages.append(message)
            }
            DispatchQueue.main.async {
                self.tabelView.reloadData()
            }

        })
    }

}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return messages.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellid" , for: indexPath) as! CustomChatTableViewCell;
    let gray = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    let red = UIColor(red:1.00, green:0.22, blue:0.37, alpha:1.0)

    let message = messages[indexPath.item]

    if message.toId == user?.toId{

    cell.messageBackground.backgroundColor = red
        cell.messageLabel.textColor = UIColor.white
    }
    else{
        cell.messageBackground.backgroundColor = gray
        cell.messageLabel.textColor = UIColor.black
    }

    cell.messageLabel.text = message.text
    if message.imageUrl != nil{
        //print(message.imageUrl!)
       // cell.messageImageView.image = UIImage(named : "user.jpg")
        cell.messageImageView.loadImageUsingCacheWithUrlString(urlString: message.imageUrl!)
        //print(cell.messageImageView.image.debugDescription)
        cell.messageImageView.isHidden = false;
        cell.messageImageView.translatesAutoresizingMaskIntoConstraints = false;
        cell.messageImageView.contentMode = .scaleAspectFill
        cell.messageLabel.isHidden = true
        cell.messageBackground.isHidden = true;
    }
    else
    {
        cell.messageImageView.isHidden = true;
        cell.selectionStyle = UITableViewCellSelectionStyle.none

        cell.messageLabel.isHidden = false
        cell.messageBackground.isHidden = false;
    }
    return cell;
}

@objc func handleTapAwayFromTextEdit(){
    //print("handle tap away from text edit running ")
    messageTextField.endEditing(true)

}

@IBAction func backToMessageListPressed(_ sender: Any) {
    dismiss(animated: false, completion: nil)
}

@IBAction func infoButtonPressed(_ sender: Any) {

}
// saves text to fire base

@IBAction func sendButtonPressed(_ sender: Any) {

  handleSendMessageToDataBase()
}

func handleSendMessageToDataBase(){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

    if messageTextField.text == ""{
        return
    }

    if let message = messageTextField.text{

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["text" : message , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

    }

    messageTextField.text = ""
    messageTextField.endEditing(true)
}

@IBAction func sendImageButtonPressed(_ sender: Any) {

    handleSendImage()

}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    print("You selected cell #\(indexPath.row)!")
}

func handleSendImage(){

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)

}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var selectedImageFromPicker : UIImage?

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage{
        selectedImageFromPicker = editedImage
    }
    else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage{
        selectedImageFromPicker = originalImage
    }
    if let selectedImage = selectedImageFromPicker{
        uploadToFireBaseUsingSelectedImage(selectedImage : selectedImage)
    }

    dismiss(animated: true, completion: nil)

}

   private func uploadToFireBaseUsingSelectedImage(selectedImage :
UIImage){
    let imageName = NSUUID().uuidString
    let refToStorage = Storage.storage().reference().child("message_images").child(imageName)

if let uploadData = UIImageJPEGRepresentation(selectedImage, 0.2){
    refToStorage.putData(uploadData, metadata: nil, completion: { (metaData, error) in
        if error != nil{
            print("failed to upload firebase image when sending in chatlogcontroller")
            print(error!)
            return
        }
        if let imageURL = metaData?.downloadURL()?.absoluteString{
            self.sendMessageWithImageURL(imageURL: imageURL)
        }

    })

}

}

private func sendMessageWithImageURL(imageURL : String){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["imageurl" : imageURL , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

}

func textFieldDidBeginEditing(_ textField: UITextField) {

    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 308;
        self.view.layoutIfNeeded()
    })

}

func textFieldDidEndEditing(_ textField: UITextField) {
    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 50;
        self.view.layoutIfNeeded()

    })
}

func configureTableView()
{
    tabelView.delegate = self;
    tabelView.dataSource = self;
    tabelView.register(UINib(nibName: "MessageCell" , bundle : nil), forCellReuseIdentifier: "customMessageCell");
    tabelView.allowsSelection = true;

}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self);

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let message = messages[indexPath.item]

    if message.imageUrl != nil{
        return 200
    }

    return (CGFloat((message.text?.count)! + 70) )
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return 80
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    handleSendMessageToDataBase()
    return true
}
</code>```

}

答:
Two other methods:

In yourUITextViewDelegate, enable the gesture recogniser when starting editing and disable it when ending editing. You could also enable it in the keyboard event handling method and disable it in the method the gesture recogniser calls.

Assign the gesture recogniser a delegate, and check if the keyboard is up when asked in the delegate if the gesture recogniser should receive the touch event.

ContentLicense: CC BY-SA 4.0

Body:
I have written my own function to scroll text fields up when the keyboard shows up. In order to dismiss the keyboard by tapping away from the text field, I've created a UITapGestureRecognizer that takes care of resigning first responder on the text field when tapping away.

However, when selecting one of the entries in the auto completed table, didSelectRowAtIndexPath does not get called. Instead, it seems that the tap gesture recognizer is getting called and just resigns first responder.

I'm guessing there's some way to tell the tap gesture recognizer to keep passing the tap message on down to the UITableView, but I can't figure out what it is. There are only solutions for this in objc and posts from over 9 years ago on stack overflow , I was wondering if there was an updated solution to this! Thank you , Here is my code if you would like to see whats going on :

class ChatLogController : UIViewController, UITextFieldDelegate , UITableViewDelegate , UITableViewDataSource, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate ,UINavigationControllerDelegate  {

var messages = [Message]()

var user : User?{
    didSet{
     observeMessages()
    }
}

@IBOutlet weak var tabelView: UITableView!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var currentMessageRecieverImage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    configureTableView()

    currentMessageRecieverImage.translatesAutoresizingMaskIntoConstraints = false;
    currentMessageRecieverImage.layer.cornerRadius = 30;
    currentMessageRecieverImage.layer.masksToBounds = true
    currentMessageRecieverImage.contentMode = .scaleAspectFill
    if let currentMessageRecieverUser = user{
        currentMessageRecieverImage.loadImageUsingCacheWithUrlString(urlString: currentMessageRecieverUser.picURL!);
        print(currentMessageRecieverUser.userName!)
    }

    tabelView.delegate = self;
    tabelView.dataSource = self;
    messageTextField.delegate = self;

    let dragAwayFromTextGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    dragAwayFromTextGesture.direction = UISwipeGestureRecognizerDirection.down
    dragAwayFromTextGesture.delegate = self;
    tabelView.addGestureRecognizer(dragAwayFromTextGesture)

    let dragBackToMessages = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeBackToMessages))
    dragBackToMessages.direction = UISwipeGestureRecognizerDirection.right
    dragBackToMessages.delegate = self;
    tabelView.addGestureRecognizer(dragBackToMessages)

    let TapAwayFromTextEditTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    tabelView.addGestureRecognizer(TapAwayFromTextEditTapGesture)
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

@objc func handleSwipeBackToMessages(){
    dismiss(animated: false, completion: nil)
}

func observeMessages(){
    guard let uid = Auth.auth().currentUser?.uid else{
        return;
    }
    // ref gets user that is logged in
    let ref = Database.database().reference().child("user-messages").child(uid)
    ref.observe(.childAdded) { (snapshot) in
        // gets needed messages
        let messageId = snapshot.key
        let messagesRef = Database.database().reference().child("messages").child(messageId)

        messagesRef.observe(.value, with: { (snapshot) in
            guard let dict = snapshot.value as? [String : AnyObject] else{
                return
            }
            let message = Message()
            message.imageUrl = dict["imageurl"] as? String
            message.fromId = dict["fromid"] as? String
            message.text = dict["text"] as? String
            message.timestamp = dict["timestamp"] as? String
            message.toId = dict["toid"] as? String

            if message.chatPartnerId() == self.user?.toId{
            self.messages.append(message)
            }
            DispatchQueue.main.async {
                self.tabelView.reloadData()
            }

        })
    }

}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return messages.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellid" , for: indexPath) as! CustomChatTableViewCell;
    let gray = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    let red = UIColor(red:1.00, green:0.22, blue:0.37, alpha:1.0)

    let message = messages[indexPath.item]

    if message.toId == user?.toId{

    cell.messageBackground.backgroundColor = red
        cell.messageLabel.textColor = UIColor.white
    }
    else{
        cell.messageBackground.backgroundColor = gray
        cell.messageLabel.textColor = UIColor.black
    }

    cell.messageLabel.text = message.text
    if message.imageUrl != nil{
        //print(message.imageUrl!)
       // cell.messageImageView.image = UIImage(named : "user.jpg")
        cell.messageImageView.loadImageUsingCacheWithUrlString(urlString: message.imageUrl!)
        //print(cell.messageImageView.image.debugDescription)
        cell.messageImageView.isHidden = false;
        cell.messageImageView.translatesAutoresizingMaskIntoConstraints = false;
        cell.messageImageView.contentMode = .scaleAspectFill
        cell.messageLabel.isHidden = true
        cell.messageBackground.isHidden = true;
    }
    else
    {
        cell.messageImageView.isHidden = true;
        cell.selectionStyle = UITableViewCellSelectionStyle.none

        cell.messageLabel.isHidden = false
        cell.messageBackground.isHidden = false;
    }
    return cell;
}

@objc func handleTapAwayFromTextEdit(){
    //print("handle tap away from text edit running ")
    messageTextField.endEditing(true)

}

@IBAction func backToMessageListPressed(_ sender: Any) {
    dismiss(animated: false, completion: nil)
}

@IBAction func infoButtonPressed(_ sender: Any) {

}
// saves text to fire base

@IBAction func sendButtonPressed(_ sender: Any) {

  handleSendMessageToDataBase()
}

func handleSendMessageToDataBase(){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

    if messageTextField.text == ""{
        return
    }

    if let message = messageTextField.text{

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["text" : message , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

    }

    messageTextField.text = ""
    messageTextField.endEditing(true)
}

@IBAction func sendImageButtonPressed(_ sender: Any) {

    handleSendImage()

}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    print("You selected cell #\(indexPath.row)!")
}

func handleSendImage(){

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)

}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var selectedImageFromPicker : UIImage?

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage{
        selectedImageFromPicker = editedImage
    }
    else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage{
        selectedImageFromPicker = originalImage
    }
    if let selectedImage = selectedImageFromPicker{
        uploadToFireBaseUsingSelectedImage(selectedImage : selectedImage)
    }

    dismiss(animated: true, completion: nil)

}

   private func uploadToFireBaseUsingSelectedImage(selectedImage :
UIImage){
    let imageName = NSUUID().uuidString
    let refToStorage = Storage.storage().reference().child("message_images").child(imageName)

if let uploadData = UIImageJPEGRepresentation(selectedImage, 0.2){
    refToStorage.putData(uploadData, metadata: nil, completion: { (metaData, error) in
        if error != nil{
            print("failed to upload firebase image when sending in chatlogcontroller")
            print(error!)
            return
        }
        if let imageURL = metaData?.downloadURL()?.absoluteString{
            self.sendMessageWithImageURL(imageURL: imageURL)
        }

    })

}

}

private func sendMessageWithImageURL(imageURL : String){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["imageurl" : imageURL , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

}

func textFieldDidBeginEditing(_ textField: UITextField) {

    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 308;
        self.view.layoutIfNeeded()
    })

}

func textFieldDidEndEditing(_ textField: UITextField) {
    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 50;
        self.view.layoutIfNeeded()

    })
}

func configureTableView()
{
    tabelView.delegate = self;
    tabelView.dataSource = self;
    tabelView.register(UINib(nibName: "MessageCell" , bundle : nil), forCellReuseIdentifier: "customMessageCell");
    tabelView.allowsSelection = true;

}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self);

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let message = messages[indexPath.item]

    if message.imageUrl != nil{
        return 200
    }

    return (CGFloat((message.text?.count)! + 70) )
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return 80
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    handleSendMessageToDataBase()
    return true
}

}


问:
Targeted for iPad option in Xcode
In Xcode when creating a subclass of UIViewController, an checkbox named "Targeted for iPad" exists among others.

What if I want to create an app that runs on iPhone and iPad (I think it is called universal application)? should I check it?

If I checked it, what is happening under the hood?

答:
I tried both with and without and diffed the generated files.

The only difference it makes is whether the pre-built shouldAutorotate: method returns YES to all orientations (normal for iPad apps) or just for portrait (normal for iPhone apps). It also changes the dimensions of the UIView in the generated XIB file (if you tick the option to create one) from iPhone to iPad screen size.

So just choose whichever one sounds like the best starting point for the class you're about to create. Both things are trivial to edit later.

Title: Targeted for iPad option in Xcode


问:
Error 500 Call to undefined function thrive_get_theme_options() when trying to get to customize in WP
My site uninstalled all plugins so I reactivated and since then I have been greeted by Error 500 everytime I try to get to Customise (WP).

I checked out error_log and it's pointing to the funtions.php line 659 (starts 3rd line down):

```<code>function thrive_exclude_category($query)
{
    $hide_cat_option = thrive_get_theme_options('hide_cats_from_blog');

    if (!is_string($hide_cat_option)) {
        $hide_cat_option = "";
    }

    $hide_categories = is_array(json_decode($hide_cat_option)) ? json_decode($hide_cat_option) : array();
    $temp_query_string_part = "";
    foreach ($hide_categories as $temp_cat_id) {
        $temp_query_string_part .= "-" . $temp_cat_id . " ";
    }
</code>```

This is probably simple stuff, however, I suck. I have been lumbered with maintaining the sites and really have no say in the matter. Thanks in advance

答: Try reactivate all plugins required by Thrive theme because of Fatal: Call to undefined function thrive_get_theme_options()</p>

Body:
My site uninstalled all plugins so I reactivated and since then I have been greeted by Error 500 everytime I try to get to Customise (WP).

I checked out error_log and it's pointing to the funtions.php line 659 (starts 3rd line down):

function thrive_exclude_category($query)
{
    $hide_cat_option = thrive_get_theme_options('hide_cats_from_blog');

    if (!is_string($hide_cat_option)) {
        $hide_cat_option = "";
    }

    $hide_categories = is_array(json_decode($hide_cat_option)) ? json_decode($hide_cat_option) : array();
    $temp_query_string_part = "";
    foreach ($hide_categories as $temp_cat_id) {
        $temp_query_string_part .= "-" . $temp_cat_id . " ";
    }

This is probably simple stuff, however, I suck. I have been lumbered with maintaining the sites and really have no say in the matter. Thanks in advance


问:
My app won't run on LG G5. USB debugging & OEM driver are OK
I'm struggling to get my stock standard Android application ("hello world") running on my LG G5. My device is just not picked up by Android studio's deployment target window ("No USB devices or running emulators detected").

Can not understand why though because I do not pick up any usb driver issues in computer manager (G5 SE identified under portable devices without shown driver problem), and my phone's development option with USB debugging is enabled as shown by Android instructions.

Some additional guidance would help please.

答:
First of all run adb devices (located in android sdk>platform-tools>) from command line / terminal and check if your phone is listed.

If not restart adb :

adb kill-server

adb start-server

If it doesn't work try changing USB Configuration on your phone: select MTP or PTP. You can change this from top panel when your phone is connected.

If this will show confirmation dialog with MAC address confirm it.

Your phone has to be visible by ADB before it can be visible by Android Studio.


问:
How to store JDBC server, database, username and password in a notesdocument
I am using JDBC from ExtLib in my xpages application to connect to SQL and have a JDBC connection file in the Webcontent/WEB-INF/JDBC/mssql.jdbc

Looks something like this and works great

```<code><jdbc>
  <driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver>
    <url>jdbc:sqlserver://server:1433;databaseName=db</url>
    <user>sa</user>
  <password></password>
</jdbc>
</code>```

I have a need to make this more dynamic by storing the servername, database, username and password in a notesdocument, is this possible, if so how?

if this is not possible, Is it possible to update the JDBC file programmatically or use other features in ExtLib for making this possible?

答:
We have done this at our company by copying the setup of the JDBCProvider from within the Extension Library, and modifying it so that instead of searching for configuration in xml documents, it will instead search for configuration in Notes documents in using a pre-defined View and Form.

I've just shared it via the jdbcprovider branch in  my fork of the ExtLibX project, with the hope to eventually do a pull request to get it into the official OpenNTF ExtLibX, and maybe finally into the core Extension library project.

I have created an 'alpha' release that you can test out, or you can have a browse in the com.ibm.xsp.extlibx.core plugin to see the source code

Here is a blog post that I have written about the first release and there is a short demo video in there as well

http://camerongregor.com/2017/12/05/jdbcnotesdocuments/

Body:
I am using JDBC from ExtLib in my xpages application to connect to SQL and have a JDBC connection file in the Webcontent/WEB-INF/JDBC/mssql.jdbc

Looks something like this and works great

<jdbc>
  <driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver>
    <url>jdbc:sqlserver://server:1433;databaseName=db</url>
    <user>sa</user>
  <password></password>
</jdbc>

I have a need to make this more dynamic by storing the servername, database, username and password in a notesdocument, is this possible, if so how?

if this is not possible, Is it possible to update the JDBC file programmatically or use other features in ExtLib for making this possible?


问:
How to use flatMapValues on Kafka
I am getting an error when using flatMapValues in Scala with Kafka library. Here is my code:

```<code>val builder: KStreamBuilder = new KStreamBuilder()
val textLines: KStream[String, String] = builder.stream("streams-plaintext-input")
import collection.JavaConverters.asJavaIterableConverter
val wordCounts: KTable[String, JLong] = textLines
  .flatMapValues(textLine => textLine.toLowerCase.split("\\W+").toIterable.asJava)
  .groupBy((_, word) => word)
  .count("word-counts")
</code>```

and I am getting the error missing parameter type for textLine inside flatMapValues. If I replace for flatMapValues((textLine: String) => textLine.toLowerCase.split("\\W+").toIterable.asJava) it still does not work.

Anyone have some idea?
Thanks, Felipe

答:
Working with Scala 2.12.4 I solved like this:</p>

```<code>  val props = new Properties
  props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-wordcount")
  props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
  props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String.getClass.getName)
  props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String.getClass.getName)

  val stringSerde: Serde[String] = Serdes.String()
  val longSerde: Serde[Long] = Serdes.Long()

  val builder = new StreamsBuilder()
  val textLines: KStream[String, String] = builder.stream("streams-plaintext-input")

  val topology: Topology = builder.build()

  println(topology.describe())

  val wordCounts: KTable[String, Long] = textLines
    .flatMapValues { textLine =>
      println(textLine)
      println(topology.describe())
      textLine.toLowerCase.split("\\W+").toIterable.asJava
    }
    .groupBy((_, word) => word)
    // this is a stateful computation config to the topology
    .count("word-counts")

  wordCounts.to(stringSerde, longSerde, "streams-wordcount-output")

  val streams = new KafkaStreams(topology, props)
  streams.start()
</code>```

Title: How to use flatMapValues on Kafka

Body:
I am getting an error when using flatMapValues in Scala with Kafka library. Here is my code:

val builder: KStreamBuilder = new KStreamBuilder()
val textLines: KStream[String, String] = builder.stream("streams-plaintext-input")
import collection.JavaConverters.asJavaIterableConverter
val wordCounts: KTable[String, JLong] = textLines
  .flatMapValues(textLine => textLine.toLowerCase.split("\\W+").toIterable.asJava)
  .groupBy((_, word) => word)
  .count("word-counts")

and I am getting the error missing parameter type for textLine inside flatMapValues. If I replace for flatMapValues((textLine: String) => textLine.toLowerCase.split("\\W+").toIterable.asJava) it still does not work.

Anyone have some idea?
Thanks, Felipe

Body:
Working with Scala 2.12.4 I solved like this:

  val props = new Properties
  props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-wordcount")
  props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
  props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String.getClass.getName)
  props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String.getClass.getName)

  val stringSerde: Serde[String] = Serdes.String()
  val longSerde: Serde[Long] = Serdes.Long()

  val builder = new StreamsBuilder()
  val textLines: KStream[String, String] = builder.stream("streams-plaintext-input")

  val topology: Topology = builder.build()

  println(topology.describe())

  val wordCounts: KTable[String, Long] = textLines
    .flatMapValues { textLine =>
      println(textLine)
      println(topology.describe())
      textLine.toLowerCase.split("\\W+").toIterable.asJava
    }
    .groupBy((_, word) => word)
    // this is a stateful computation config to the topology
    .count("word-counts")

  wordCounts.to(stringSerde, longSerde, "streams-wordcount-output")

  val streams = new KafkaStreams(topology, props)
  streams.start()


问:
Opening a popup from code throws exception
I am working on an app within Xamarin Android on VS Community 2017. I want to launch a Popup from FAB - FloatingActionButton. I created the popup xml layout separately and when I launch the popup the debugger throws an exception but there is no error code displayed so I dont know what is causing the issue.

My best guess is something is wrong with the xml layout file for the popup. I have checked it numerous times but everything seems okay to me. The RelativePanel in android works awfully different than in UWP and maybe I am doing something wrong there.

Anyway, here is the code...
Popup layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
    android:text="Sort By:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:id="@+id/moviesSortByText"
    android:minHeight="28dp"
    android:gravity="left|center_vertical" />
<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/moviesSortSpinner"
    android:minWidth="120dp"
    android:minHeight="28dp"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@id/moviesSortByText" />
<TextView
    android:text="Genre:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:id="@+id/moviesGenresText"
    android:layout_below="@id/moviesSortByText"
    android:minHeight="28dp"
    android:gravity="left|center_vertical" />
<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/moviesSortByText"
    android:id="@+id/moviesGenresSpinner"
    android:minWidth="120dp"
    android:minHeight="28dp"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@id/moviesGenresText" />
<TextView
    android:text="Country:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:id="@+id/moviesCountryText"
    android:layout_below="@id/moviesGenresText"
    android:minHeight="28dp"
    android:gravity="left|center_vertical" />
<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/moviesGenresText"
    android:id="@+id/moviesCountrySpinner"
    android:minWidth="120dp"
    android:minHeight="28dp"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@id/moviesCountryText" />
</RelativeLayout>
</code>```

The code behind in the activity:

```<code>moviesOptionsBtn = FindViewById<FloatingActionButton>(Resource.Id.moviesOptionsFAB);
moviesOptionsBtn.Click += MoviesOptionsBtn_Click;

    private void MoviesOptionsBtn_Click(object sender, EventArgs e)
    {
        // create a flyout with 3 spinners for sorting, genres and countries
        var popupView = LayoutInflater.Inflate(Resource.Layout.moviesOptionsPopupLayout, null);
        var popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, true)
        {
            Touchable = true,
            Focusable = true,
            OutsideTouchable = true
        };
        // find spinners and fill them with values
        sortSpinner = popupView.FindViewById<Spinner>(Resource.Id.moviesSortSpinner);
        genreSpinner = popupView.FindViewById<Spinner>(Resource.Id.moviesGenresSpinner);
        countrySpinner = popupView.FindViewById<Spinner>(Resource.Id.moviesCountrySpinner);
        sortSpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.SortList);
        genreSpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.GenresList);
        countrySpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.CountryList);
        // register selections
        sortSpinner.ItemSelected += MoviesOptionsSpinner_ItemSelected;
        genreSpinner.ItemSelected += MoviesOptionsSpinner_ItemSelected;
        countrySpinner.ItemSelected += MoviesOptionsSpinner_ItemSelected;

        popupWindow.ShowAsDropDown(moviesOptionsBtn);
    }
</code>```

The FAB is displayed okay and the exception is only thrown after the last line. All the other code appears to be working fine.

Can someone look at my code and tell me if there is something that i am doing wrong?

答:
Thanks for the comments, I found out the source of my problem.

In Android, the Spinner's adapter property is rather different. As what I did, one of the 2nd and 3rd parameters in

```<code>sortSpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.SortList);
</code>```

is a resource for TextView but I was passing it a style from Android framework and that was causing the exception. To make it right, I had to use only one style for the closed Spinner and after that set the 2nd resource for the opened list.

```<code>var spinnerAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, ViewHelper.SortList);
spinnerAdapter.SetDropdownResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
sortSpinner.Adapter = spinnerAdapter;
</code>```

That solved the problem so I thought I should put it here for future reference. Thanks for the effort though.

Body:
I am working on an app within Xamarin Android on VS Community 2017. I want to launch a Popup from FAB - FloatingActionButton. I created the popup xml layout separately and when I launch the popup the debugger throws an exception but there is no error code displayed so I dont know what is causing the issue.

My best guess is something is wrong with the xml layout file for the popup. I have checked it numerous times but everything seems okay to me. The RelativePanel in android works awfully different than in UWP and maybe I am doing something wrong there.

Anyway, here is the code...
Popup layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
    android:text="Sort By:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:id="@+id/moviesSortByText"
    android:minHeight="28dp"
    android:gravity="left|center_vertical" />
<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/moviesSortSpinner"
    android:minWidth="120dp"
    android:minHeight="28dp"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@id/moviesSortByText" />
<TextView
    android:text="Genre:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:id="@+id/moviesGenresText"
    android:layout_below="@id/moviesSortByText"
    android:minHeight="28dp"
    android:gravity="left|center_vertical" />
<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/moviesSortByText"
    android:id="@+id/moviesGenresSpinner"
    android:minWidth="120dp"
    android:minHeight="28dp"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@id/moviesGenresText" />
<TextView
    android:text="Country:"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:id="@+id/moviesCountryText"
    android:layout_below="@id/moviesGenresText"
    android:minHeight="28dp"
    android:gravity="left|center_vertical" />
<Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/moviesGenresText"
    android:id="@+id/moviesCountrySpinner"
    android:minWidth="120dp"
    android:minHeight="28dp"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@id/moviesCountryText" />
</RelativeLayout>

The code behind in the activity:

moviesOptionsBtn = FindViewById<FloatingActionButton>(Resource.Id.moviesOptionsFAB);
moviesOptionsBtn.Click += MoviesOptionsBtn_Click;

    private void MoviesOptionsBtn_Click(object sender, EventArgs e)
    {
        // create a flyout with 3 spinners for sorting, genres and countries
        var popupView = LayoutInflater.Inflate(Resource.Layout.moviesOptionsPopupLayout, null);
        var popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, true)
        {
            Touchable = true,
            Focusable = true,
            OutsideTouchable = true
        };
        // find spinners and fill them with values
        sortSpinner = popupView.FindViewById<Spinner>(Resource.Id.moviesSortSpinner);
        genreSpinner = popupView.FindViewById<Spinner>(Resource.Id.moviesGenresSpinner);
        countrySpinner = popupView.FindViewById<Spinner>(Resource.Id.moviesCountrySpinner);
        sortSpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.SortList);
        genreSpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.GenresList);
        countrySpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.CountryList);
        // register selections
        sortSpinner.ItemSelected += MoviesOptionsSpinner_ItemSelected;
        genreSpinner.ItemSelected += MoviesOptionsSpinner_ItemSelected;
        countrySpinner.ItemSelected += MoviesOptionsSpinner_ItemSelected;

        popupWindow.ShowAsDropDown(moviesOptionsBtn);
    }

The FAB is displayed okay and the exception is only thrown after the last line. All the other code appears to be working fine.

Can someone look at my code and tell me if there is something that i am doing wrong?

Body:
Thanks for the comments, I found out the source of my problem.

In Android, the Spinner's adapter property is rather different. As what I did, one of the 2nd and 3rd parameters in

sortSpinner.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Android.Resource.Layout.SimpleSpinnerDropDownItem, ViewHelper.SortList);

is a resource for TextView but I was passing it a style from Android framework and that was causing the exception. To make it right, I had to use only one style for the closed Spinner and after that set the 2nd resource for the opened list.

var spinnerAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, ViewHelper.SortList);
spinnerAdapter.SetDropdownResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
sortSpinner.Adapter = spinnerAdapter;

That solved the problem so I thought I should put it here for future reference. Thanks for the effort though.


问:
PHP Header adding multiple times
I have this query:

```<code>$get_ids = "SELECT unique_id FROM products GROUP BY unique_id LIMIT 10";
$id_results = mysql_query($get_ids);
while($id_row = mysql_fetch_array($id_results))
{
    extract($id_row);
    $all_prods_link[] = $id_row['unique_id'];
}
</code>```

This will create an array of integers. For each item in the array, I append this to a string, following by a comma:

```<code>foreach($all_prods_link as $all_prods)
{
    $query_string .= $all_prods.',';
}
</code>```

The result is like: 1,2,3,4,5,6, which is working as intended.

The problem I am having is I am trying to add this to the end of the current URI, and then redirect to this URI eg:

```<code>$link = $_SERVER['REQUEST_URI'] . '&product_options=' . $query_string;
</code>```

The $link variable looks good:

```<code>sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,
</code>```

This is exactly what I want, however when I then try to redirect to this link, eg:

```<code>header("Location: $link");
</code>```

The actual URI I end up with has the $query_string, appended to it multiple times, like so:

```<code>sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,
</code>```

As you can see, "&product_options" appears multiple times, followed by the list of integers!

Can the header() function be used this way? or am I doing something horribly wrong!

答:
This is because of multiple redirect each time you load the page, php will append product_options rather than replacing it.

```<code><?php

// Parse all request components
$request = parse_url($_SERVER['REQUEST_URI']);

// Parse incoming query sting to array
parse_str($request['query'], $queryArray);

// replace or add product_options
$queryArray['product_options'] = $query_string;

// rebuild the query
$newQueryString = http_build_query($queryArray);

$link = $request['path']. '?' . $newQueryString;

header("Location: $link");
</code>```

Title: PHP Header adding multiple times

Body:
I have this query:

$get_ids = "SELECT unique_id FROM products GROUP BY unique_id LIMIT 10";
$id_results = mysql_query($get_ids);
while($id_row = mysql_fetch_array($id_results))
{
    extract($id_row);
    $all_prods_link[] = $id_row['unique_id'];
}

This will create an array of integers. For each item in the array, I append this to a string, following by a comma:

foreach($all_prods_link as $all_prods)
{
    $query_string .= $all_prods.',';
}

The result is like: 1,2,3,4,5,6, which is working as intended.

The problem I am having is I am trying to add this to the end of the current URI, and then redirect to this URI eg:

$link = $_SERVER['REQUEST_URI'] . '&product_options=' . $query_string;

The $link variable looks good:

sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,

This is exactly what I want, however when I then try to redirect to this link, eg:

header("Location: $link");

The actual URI I end up with has the $query_string, appended to it multiple times, like so:

sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,

As you can see, "&product_options" appears multiple times, followed by the list of integers!

Can the header() function be used this way? or am I doing something horribly wrong!

Body:
This is because of multiple redirect each time you load the page, php will append product_options rather than replacing it.

<?php

// Parse all request components
$request = parse_url($_SERVER['REQUEST_URI']);

// Parse incoming query sting to array
parse_str($request['query'], $queryArray);

// replace or add product_options
$queryArray['product_options'] = $query_string;

// rebuild the query
$newQueryString = http_build_query($queryArray);

$link = $request['path']. '?' . $newQueryString;

header("Location: $link");


问:
jQuery : Find prev element from current element
How to get a prev element from current element Like this.

```<code><p class='target'>Target</p>

<ol>
  <li>start</li>
  <ul>
    <li class='start'>mid</li>
  </ul>
</ol>
</code>```

For now, I'm in the start element.And I want to find the target element.

I try the below code to do this.

```<code> $('.start').prev('.target');
</code>```

But it didn't get the target DOM.

How can I do this?Any advice.

Update ::

My scenario is a bit complicated.

```<code>  <p>
  <ins>asdf</ins>
  </p>

<div>div (great-grandparent)
  <ul>
     <li><del>(second ancestor - second grandparent)</del></li>
     <ul>
       <li>
         <span>span</span>
       </li>
     </ul>
   </ul>
</div>
</code>```

Just assume I'm in the span and I try to find the "DEL and INS"
tags.What am I going to do?

And I try the below one.But it's not working.

```<code>$('span').closest('del');
$('span').closest('ins');
</code>```

And the structure of the HTML is changing every time.That's why I'm afraid of.

答:
```<code>$('.start').closest('ol').prev('.target');
</code>```

For traversing elements, it's important to understand their hierarchy. If you read the above code, you should be able to make out why it works.

It can be broken down like this:

Select element with class .start =>
mid

Get the closest (traverses up the tree) element of type ol in relation to .start =>

Get the previous element with class .target in relation to the previously selected ol element, which is the intended element =>
Target

Hope that helps.

Read about closest from jQuery API.

Body:
How to get a prev element from current element Like this.

Target

start

mid

For now, I'm in the start element.And I want to find the target element.

I try the below code to do this.

 $('.start').prev('.target');

But it didn't get the target DOM.

How can I do this?Any advice.

Update ::

My scenario is a bit complicated.

  asdf

div (great-grandparent)

(second ancestor - second grandparent)

         span

Just assume I'm in the span and I try to find the "DEL and INS"
tags.What am I going to do?

And I try the below one.But it's not working.

$('span').closest('del');
$('span').closest('ins');

And the structure of the HTML is changing every time.That's why I'm afraid of.

Body:
$('.start').closest('ol').prev('.target');

For traversing elements, it's important to understand their hierarchy. If you read the above code, you should be able to make out why it works.

It can be broken down like this:

Select element with class .start => <li class='start'>mid</li>

Get the closest (traverses up the tree) element of type ol in relation to .start => <ol>

Get the previous element with class .target in relation to the previously selected ol element, which is the intended element => <p class='target'>Target</p>

Hope that helps.

Read about closest from jQuery API.


问:
Reading multiple txt files with generator in loop, using Python
The program calls the function and opens it only once at the loop. Do you have any solution about how I can make it call the function in the loop all the times? (I mean for every j)</p>

```<code>def list_spectra(interpolated, txt):
    return (f for f in listdir(interpolated) if f.endswith("." + txt))

wl = []
fl = []
er = []

flux  = []
error = []

med_flux = []
med_err  = []

spectra_all = list_spectra("C:\\..my path here..\\interpolated","txt")
path = "C:\\..my path here..\\interpolated\\"

for j in range(0,len(wavelength)):
   for f in spectra_all:
        data = np.loadtxt(path+f)
        for ii in range(0,len(data)):

            wl = data[:,0]
            fl = data[:,1]
            er = data[:,2]

            for i in range(0,len(wl)):
                if wl[i] == wavelength[j]:
                    flux.append(fl[i])
                    error.append(er[i])

    med_flux.append(np.median(flux))
    med_err.append(np.median(error))
</code>```

答:
Do you mean this:</p>

```<code>for j in range(0,len(wavelength)):
    spectra_all = list_spectra("C:\\..my path here..\\interpolated","txt")
    for f in spectra_all:
        data = np.loadtxt(path+f)
        # etc
</code>```

Body:
The program calls the function and opens it only once at the loop. Do you have any solution about how I can make it call the function in the loop all the times? (I mean for every j)

def list_spectra(interpolated, txt):
    return (f for f in listdir(interpolated) if f.endswith("." + txt))

wl = []
fl = []
er = []

flux  = []
error = []

med_flux = []
med_err  = []

spectra_all = list_spectra("C:\\..my path here..\\interpolated","txt")
path = "C:\\..my path here..\\interpolated\\"

for j in range(0,len(wavelength)):
   for f in spectra_all:
        data = np.loadtxt(path+f)
        for ii in range(0,len(data)):

            wl = data[:,0]
            fl = data[:,1]
            er = data[:,2]

            for i in range(0,len(wl)):
                if wl[i] == wavelength[j]:
                    flux.append(fl[i])
                    error.append(er[i])

    med_flux.append(np.median(flux))
    med_err.append(np.median(error))

Body:
Do you mean this:

for j in range(0,len(wavelength)):
    spectra_all = list_spectra("C:\\..my path here..\\interpolated","txt")
    for f in spectra_all:
        data = np.loadtxt(path+f)
        # etc


问:
Rails Nested Singular Resource Routing
I have a simple User model with a singular nested Profile resource so in my routes.rb I have:

```<code>resources :users do
  resource :profile, :only => [:edit, :update, :show]
end
</code>```

This generates the expected routes:

```<code>edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}
</code>```

I've created a simple controller update method that updates the model and then redirects upon successful update:

```<code>def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end
</code>```

The problem is that once the form is submitted, the form redirects to mydomain.com/users/4/profile.22 where 22 happens to be the id of the profile.  Clearly this confuses the controllers since the routing interprets the '22' as the format.

My question is, how do I get this to redirect to mydomain.com/users/4/profile instead?  I've tried the following variations on the redirect_to statement to no effect, they all result in the same incorrect url:

```<code>redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )
</code>```

What's more, using 'user_profile_path(@user)' elsewhere produces the correct url.

Any ideas?  Oh, and I'm using Rails 3.0.0 and Ruby 1.9.2 if that helps.

答: user_profile_path(@user) should be correct. You're sure that one is returning mydomain.com/users/4/profile.22?

Title: Rails Nested Singular Resource Routing

Body:
I have a simple User model with a singular nested Profile resource so in my routes.rb I have:

resources :users do
  resource :profile, :only => [:edit, :update, :show]
end

This generates the expected routes:

edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}

I've created a simple controller update method that updates the model and then redirects upon successful update:

def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end

The problem is that once the form is submitted, the form redirects to mydomain.com/users/4/profile.22 where 22 happens to be the id of the profile.  Clearly this confuses the controllers since the routing interprets the '22' as the format.

My question is, how do I get this to redirect to mydomain.com/users/4/profile instead?  I've tried the following variations on the redirect_to statement to no effect, they all result in the same incorrect url:

redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )

What's more, using 'user_profile_path(@user)' elsewhere produces the correct url.

Any ideas?  Oh, and I'm using Rails 3.0.0 and Ruby 1.9.2 if that helps.


问:
IDENTITY_INSERT is set to OFF(can't find where is the error)
I am trying to run my program in Visual Studio 2015. I created a .mdf database and a table in it. When I try to run it, I get this the following error:

```<code>cannot insert explicit value for identity column in table tblinfo when IDENTITY_INSERT is set to OFF".
</code>```

Hope someone can help me. Thanks.

答:
You should not insert your IDENTITY column. Instead, let SQL Server assign the value for you and return it back to your application code, with scope_identity</p>

```<code>create procedure dbo.addorupdate
...
begin
  if @node = 'add'
  begin
    insert into tblinfo (firstname, lastname, age, gender) values (@firstname, @lastname, @age, @gender)
    return scope_identity()
  end
</code>```

Body:
I am trying to run my program in Visual Studio 2015. I created a .mdf database and a table in it. When I try to run it, I get this the following error:

cannot insert explicit value for identity column in table tblinfo when IDENTITY_INSERT is set to OFF".

Hope someone can help me. Thanks.

Body:
You should not insert your IDENTITY column. Instead, let SQL Server assign the value for you and return it back to your application code, with scope_identity

create procedure dbo.addorupdate
...
begin
  if @node = 'add'
  begin
    insert into tblinfo (firstname, lastname, age, gender) values (@firstname, @lastname, @age, @gender)
    return scope_identity()
  end


问:
Plotting squares of colored pixels from the Gaussian distribution
I would like to generate an image like this:

where the pixel colors are determined by the value of the multivariate normal distribution. In other words, I have the following dataframe:

```<code>images <- data.frame(x = rnorm(256*256*20), image = rep(c(1:20), each = 256*256))
</code>```

And I would like to plot each of the 20 vectors of draws from the multivariate normal, as colored squares. The squares should be aligned on a 2x10 grid. It doesn't matter if they are separated by black lines or not, but there must be some kind of separation between different squares. The value 0 should correspond to a grayish or white color (grey would be better). How can I do that? I would like a ggplot solution, but base R or something else is good too, as long as the code is reasonably flexible and readable (performance is not an issue).

EDIT the squares don't have to be 256*256, 64*64 would be fine too.

答:
Here is an attempt:

generate r, g, b channels:

```<code>library(tidyverse)

images <- data.frame(r = rnorm(256*256*20),
                     g = rnorm(256*256*20),
                     b = rnorm(256*256*20),
                     image = rep(c(1:20), each = 256*256))
</code>```

function to convert rgb to hex:

```<code>rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 255)
</code>```

convert the rnorm with 0 mean and 1 sd to r, g, b channels by rescaling to 0-1 range and multiplying by 255 and finally converting to hex

```<code>images %>%
  group_by(image) %>%
  mutate(y = rep(1:256, each = 256), #x coords
         x = rep(1:256, times = 256), #y coords
         r = round(scales::rescale(r) * 255, 0),
         g = round(scales::rescale(g) * 255, 0),
         b = round(scales::rescale(b) * 255, 0),
         hex = rgb2hex(r, g, b)) -> for_plot

  ggplot(for_plot) +
       geom_raster(aes(x = x, y = y), fill = for_plot$hex)+
       facet_wrap(~image, ncol = 10) +
       coord_equal()
</code>```

Simplification:

```<code>rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 1)

images %>%
  group_by(image) %>%
  mutate(y = rep(1:256, each = 256),
         x = rep(1:256, times = 256),
         r = scales::rescale(r),
         g = scales::rescale(g),
         b = scales::rescale(b),
         hex = rgb2hex(r, g, b)) -> for_plot
</code>```

EDIT: DeltaIV requested clipping the darker tones in the comments here is an approach:

```<code>n = 0.2

images %>%
  group_by(image) %>%
  mutate(y = rep(1:256, each = 256),
         x = rep(1:256, times = 256),
         r = scales::rescale(r) + n,
         g = scales::rescale(g) + n,
         b = scales::rescale(b) + n,
         hex = rgb(r, g, b, maxColorValue = 1 + n)) -> for_plot

ggplot(for_plot) +
  geom_raster(aes(x = x, y = y), fill = for_plot$hex)+
  facet_wrap(~image, ncol = 10) +
  coord_equal()
</code>```

increasing n = 0.5 results in lighter images

Body:
I would like to generate an image like this:

where the pixel colors are determined by the value of the multivariate normal distribution. In other words, I have the following dataframe:

images <- data.frame(x = rnorm(256*256*20), image = rep(c(1:20), each = 256*256))

And I would like to plot each of the 20 vectors of draws from the multivariate normal, as colored squares. The squares should be aligned on a 2x10 grid. It doesn't matter if they are separated by black lines or not, but there must be some kind of separation between different squares. The value 0 should correspond to a grayish or white color (grey would be better). How can I do that? I would like a ggplot solution, but base R or something else is good too, as long as the code is reasonably flexible and readable (performance is not an issue).

EDIT the squares don't have to be 256*256, 64*64 would be fine too.

Body:
Here is an attempt:

generate r, g, b channels:

library(tidyverse)

images <- data.frame(r = rnorm(256*256*20),
                     g = rnorm(256*256*20),
                     b = rnorm(256*256*20),
                     image = rep(c(1:20), each = 256*256))

function to convert rgb to hex:

rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 255)

convert the rnorm with 0 mean and 1 sd to r, g, b channels by rescaling to 0-1 range and multiplying by 255 and finally converting to hex

images %>%
  group_by(image) %>%
  mutate(y = rep(1:256, each = 256), #x coords
         x = rep(1:256, times = 256), #y coords
         r = round(scales::rescale(r) * 255, 0),
         g = round(scales::rescale(g) * 255, 0),
         b = round(scales::rescale(b) * 255, 0),
         hex = rgb2hex(r, g, b)) -> for_plot

  ggplot(for_plot) +
       geom_raster(aes(x = x, y = y), fill = for_plot$hex)+
       facet_wrap(~image, ncol = 10) +
       coord_equal()

Simplification:

rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 1)

images %>%
  group_by(image) %>%
  mutate(y = rep(1:256, each = 256),
         x = rep(1:256, times = 256),
         r = scales::rescale(r),
         g = scales::rescale(g),
         b = scales::rescale(b),
         hex = rgb2hex(r, g, b)) -> for_plot

EDIT: DeltaIV requested clipping the darker tones in the comments here is an approach:

n = 0.2

images %>%
  group_by(image) %>%
  mutate(y = rep(1:256, each = 256),
         x = rep(1:256, times = 256),
         r = scales::rescale(r) + n,
         g = scales::rescale(g) + n,
         b = scales::rescale(b) + n,
         hex = rgb(r, g, b, maxColorValue = 1 + n)) -> for_plot

ggplot(for_plot) +
  geom_raster(aes(x = x, y = y), fill = for_plot$hex)+
  facet_wrap(~image, ncol = 10) +
  coord_equal()

increasing n = 0.5 results in lighter images


问:
how to show json data in yii2 gridview
I want to display json data in gridview.I get data in console window. and I want to display in gridview.how to do that. below givencode

In controller

```<code>public function actionCompanyinfo(){

    $text_in_search = $_GET['text_in_search'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if($left_items_cat == "Companies"){

         $query = (new \yii\db\Query())
                ->select(['c.name', 'c.id'])
                ->from(['companies as c'])
                ->where('c.name LIKE :query')
                ->addParams([':query'=>'%'.$text_in_search.'%'])
                ->all();

        $response['comapnies_matching'] = $query;
            return \yii\helpers\Json::encode([
        $response
    ]);

    }
}
</code>```

In view

```<code>$form = ActiveForm::begin();
 $typeahead = $form->field($model, 'name')->textInput(['maxlength' => true]);

$getinfobtn = Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ;
   ActiveForm::end();
</code>```

In Js file

```<code>$("#getinfo").click(function(){
        var text_in_search = $("#companies-name").val();
        var left_items_cat = $('#left-items li.active').text();
        var url = "index.php?r=companies/companyinfo";

        $.ajax({
        url: url,
        dataType: 'json',
        method: 'GET',
        data: {text_in_search,left_items_cat},
        success: function (data, textStatus, jqXHR) {
             // $( "#country"+id ).html(data[0].countries);
             console.log(data[0]);
           // **want to show this data in yii2 grid view**
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });
</code>```

console.log

```<code>comapnies_matching
:
Array(3)
0
:
{name: "ADC Therapeutics Sarl", id: "402"}
1
:
{name: "ADC Therapeutics Sarl", id: "407"}
2
:
{name: "ADC Therapeutics Sarl", id: "412"}
</code>```

In console window I get required output but I want it to display that array in grid view .. how to do that?

答:
You can achive this by using Pjax widget of the framework.

In your view: (if you not use model don't use ActiveForm)

```<code><?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

//Get active filters from request GET
$get = Yii::$app->request->get();
$name = isset($get['name']) ? $get['name'] : '';
$left_items_cat = isset($get['left_items_cat']) ? $get['left_items_cat'] : '';
?>

<?php Pjax::begin(); ?>
<?= Html::beginForm(['companies/companyinfo'], 'get', ['data-pjax' => '',]); ?>
<?= Html::dropDownList('left_items_cat', $left_items_cat,
    ['' => '', 'Companies' => 'Companies', 'Other' => 'Other'], ['class' => 'form-control']) ?>
<?= Html::input('text', 'name', $name, ['class' => 'form-control']) ?>
<?= Html::submitButton('Get Info', ['class' => 'btn btn-success', 'name' => 'getInfo']) ?>
<?= Html::endForm() ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
    ],
]); ?>
<?php Pjax::end(); ?>
</code>```

And in your controller:

```<code>public function actionCompanyinfo()
{
    // Init DataProvider empty
    $dataProvider = new ArrayDataProvider(['allModels' => []]);
    // Manage the params send in request GET
    $text_in_search = $_GET['name'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if ($left_items_cat == "Companies") {
        // Query rows and populate DataProvider
        $query = (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query')
            ->addParams([':query'=>'%'.$text_in_search.'%'])
            ->all();

        $dataProvider->allModels = $query;
    }

    return $this->render('view', ['dataProvider' => $dataProvider]);
}
</code>```

Title: how to show json data in yii2 gridview

Body:
I want to display json data in gridview.I get data in console window. and I want to display in gridview.how to do that. below givencode

In controller

public function actionCompanyinfo(){

    $text_in_search = $_GET['text_in_search'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if($left_items_cat == "Companies"){

         $query = (new \yii\db\Query())
                ->select(['c.name', 'c.id'])
                ->from(['companies as c'])
                ->where('c.name LIKE :query')
                ->addParams([':query'=>'%'.$text_in_search.'%'])
                ->all();

        $response['comapnies_matching'] = $query;
            return \yii\helpers\Json::encode([
        $response
    ]);

    }
}

In view

$form = ActiveForm::begin();
 $typeahead = $form->field($model, 'name')->textInput(['maxlength' => true]);

$getinfobtn = Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ;
   ActiveForm::end();

In Js file

$("#getinfo").click(function(){
        var text_in_search = $("#companies-name").val();
        var left_items_cat = $('#left-items li.active').text();
        var url = "index.php?r=companies/companyinfo";

        $.ajax({
        url: url,
        dataType: 'json',
        method: 'GET',
        data: {text_in_search,left_items_cat},
        success: function (data, textStatus, jqXHR) {
             // $( "#country"+id ).html(data[0].countries);
             console.log(data[0]);
           // **want to show this data in yii2 grid view**
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });

console.log

comapnies_matching
:
Array(3)
0
:
{name: "ADC Therapeutics Sarl", id: "402"}
1
:
{name: "ADC Therapeutics Sarl", id: "407"}
2
:
{name: "ADC Therapeutics Sarl", id: "412"}

In console window I get required output but I want it to display that array in grid view .. how to do that?

Body:
You can achive this by using Pjax widget of the framework.

In your view: (if you not use model don't use ActiveForm)

<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

//Get active filters from request GET
$get = Yii::$app->request->get();
$name = isset($get['name']) ? $get['name'] : '';
$left_items_cat = isset($get['left_items_cat']) ? $get['left_items_cat'] : '';
?>

<?php Pjax::begin(); ?>
<?= Html::beginForm(['companies/companyinfo'], 'get', ['data-pjax' => '',]); ?>
<?= Html::dropDownList('left_items_cat', $left_items_cat,
    ['' => '', 'Companies' => 'Companies', 'Other' => 'Other'], ['class' => 'form-control']) ?>
<?= Html::input('text', 'name', $name, ['class' => 'form-control']) ?>
<?= Html::submitButton('Get Info', ['class' => 'btn btn-success', 'name' => 'getInfo']) ?>
<?= Html::endForm() ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
    ],
]); ?>
<?php Pjax::end(); ?>

And in your controller:

public function actionCompanyinfo()
{
    // Init DataProvider empty
    $dataProvider = new ArrayDataProvider(['allModels' => []]);
    // Manage the params send in request GET
    $text_in_search = $_GET['name'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if ($left_items_cat == "Companies") {
        // Query rows and populate DataProvider
        $query = (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query')
            ->addParams([':query'=>'%'.$text_in_search.'%'])
            ->all();

        $dataProvider->allModels = $query;
    }

    return $this->render('view', ['dataProvider' => $dataProvider]);
}


问:
How to convert a byte array to two long values?
I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long values. How can I do that?

This is the code I have tried, but I probably didn't use ByteBuffer correctly.

```<code>byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"

ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);

// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
</code>```

I stored the byte array to the database using:

```<code>byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();
</code>```

答:
```<code>long getLong(byte[] b, int off) {
    return ((b[off + 7] & 0xFFL) << 0) +
           ((b[off + 6] & 0xFFL) << 8) +
           ((b[off + 5] & 0xFFL) << 16) +
           ((b[off + 4] & 0xFFL) << 24) +
           ((b[off + 3] & 0xFFL) << 32) +
           ((b[off + 2] & 0xFFL) << 40) +
           ((b[off + 1] & 0xFFL) << 48) +
           (((long) b[off + 0]) << 56);
}

long leastSignificant = getLong(bytes, 0);
long mostSignificant = getLong(bytes, 8);
</code>```

Body:
I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long values. How can I do that?

This is the code I have tried, but I probably didn't use ByteBuffer correctly.

byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"

ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);

// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();

I stored the byte array to the database using:

byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();


问:
Dynamically view inflation error
I am creating view via XML.

But after adding view it is throwing error -

The specified child already has a parent. You must call removeView() on the child's parent first.

I am using below code -

```<code>LinearLayout main = new LinearLayout(mContext);
main.setId(R.id.main);
main.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
main.setLayoutParams(layoutParams);

LinearLayout sub1 = new LinearLayout(mContext);
sub1.setId(R.id.sub1);
sub1.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_662 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub1.setLayoutParams(layout_662);

LinearLayout sub2 = new LinearLayout(mContext);
sub2.setId(R.id.sub2);
sub2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_943 = new  LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub2.setLayoutParams(layout_943);

for(int i=0;i<=4);i++) {

    sub1.addView(imageView[i]);
    main.addView(sub1);

    sub2.addView(imageView1[i]);
    main.addView(sub2);
}
</code>```

Any kind of help will be appreciated.

答:
Use it like below.</p>

```<code> for(int i=0;i<=4);i++) {
        sub1.addView(imageView[i]);
        sub2.addView(imageView1[i]);
    }
    main.addView(sub1);
    main.addView(sub2);
</code>```

Title: Dynamically view inflation error

Body:
I am creating view via XML.

But after adding view it is throwing error -

The specified child already has a parent. You must call removeView() on the child's parent first.

I am using below code -

LinearLayout main = new LinearLayout(mContext);
main.setId(R.id.main);
main.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
main.setLayoutParams(layoutParams);

LinearLayout sub1 = new LinearLayout(mContext);
sub1.setId(R.id.sub1);
sub1.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_662 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub1.setLayoutParams(layout_662);

LinearLayout sub2 = new LinearLayout(mContext);
sub2.setId(R.id.sub2);
sub2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_943 = new  LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub2.setLayoutParams(layout_943);

for(int i=0;i<=4);i++) {

    sub1.addView(imageView[i]);
    main.addView(sub1);

    sub2.addView(imageView1[i]);
    main.addView(sub2);
}

Any kind of help will be appreciated.

Body:
Use it like below.

 for(int i=0;i<=4);i++) {
        sub1.addView(imageView[i]);
        sub2.addView(imageView1[i]);
    }
    main.addView(sub1);
    main.addView(sub2);


问:
Fancybox Pop Up Always Display On Top of The Page On Tablet or Mobile Device
The Fancybox pop up work as expected on desktop, but while accessing via mobile or tablet device, the pop up always shows at the top of the page.

Say, I scroll the page down, then I click a link that can display the pop up, but the pop up doesn't show, coz it display on top, so I need to scroll up the page.

This is my code

```<code>jQuery("#popup").fancybox({
    "titlePosition"     : "inside",
    "transitionIn"      : "none",
    "transitionOut"     : "none",
    "centerOnScroll"    : true
});
</code>```

Any help would be apreciated.

答:
Try this,

```<code>jQuery('.fancy_ajax_close_btn').fancybox({
    minWidth  : '43%',
    maxWidth  : '60%',
    afterLoad : function() {

        var top = ($(window).height() / 2) - ($(".fancybox-wrap").outerHeight() / 2);
        var left = ($(window).width() / 2) - ($(".fancybox-wrap").outerWidth() / 2);
        $(".fancybox-wrap").css({ top: top, left: left});
    }

});
</code>```

and in jquery.fancybox.css

```<code>.fancybox-wrap {
 left: 0;
 z-index: 8020;
 position: absolute;
 width: 200px;
 margin: 0 auto;
}
</code>```

Not a perfect solution but for V2.0 its the best one.

Body:
The Fancybox pop up work as expected on desktop, but while accessing via mobile or tablet device, the pop up always shows at the top of the page.

Say, I scroll the page down, then I click a link that can display the pop up, but the pop up doesn't show, coz it display on top, so I need to scroll up the page.

This is my code

jQuery("#popup").fancybox({
    "titlePosition"     : "inside",
    "transitionIn"      : "none",
    "transitionOut"     : "none",
    "centerOnScroll"    : true
});

Any help would be apreciated.

Body:
Try this,

jQuery('.fancy_ajax_close_btn').fancybox({
    minWidth  : '43%',
    maxWidth  : '60%',
    afterLoad : function() {

        var top = ($(window).height() / 2) - ($(".fancybox-wrap").outerHeight() / 2);
        var left = ($(window).width() / 2) - ($(".fancybox-wrap").outerWidth() / 2);
        $(".fancybox-wrap").css({ top: top, left: left});
    }

});

and in jquery.fancybox.css

.fancybox-wrap {
 left: 0;
 z-index: 8020;
 position: absolute;
 width: 200px;
 margin: 0 auto;
}

Not a perfect solution but for V2.0 its the best one.