text:
Q: How to study for hard math proofs? Most of the content is new to me and there are a lot of theorems and proofs that I am learning; not that I need to know all of them but I enjoy to learn more. Some of the concepts (like open sets) or some of the proofs are quite time consuming; for instance, it takes me about 45 minutes to understand a hard proof. Is this normal?

A: Regarding remembering lengthy proofs, my technique is always to take that proof through a certain process:

*

*Write the proof on a piece of paper or a board.

*Make rather detailed guidelines for how to reconstruct the proof where you break it into parts. Those may contain a substantial excerpt of the actual equations and arguments.

*Reconstruct the proof using your guidelines.

*Distill your guidelines into more brief hints.

*Reconstruct the proof using only the hints, and you should be good to go.

It does require work, but there is no shortcut. This is not as time consuming as it may sound compared to the outcome.

As others have mentioned, do not go into this much detail with every tiny proof you stumble upon. You have to consider each time if it is relevant and serves a goal.

Regarding reconstructing proofs at a much later date, I must say that the mind works in mysterious ways. Over time you internalize techniques and even theorems on a higher level, so that these become readily available for tackling other problems. That has already happened to you with some of the techniques from previous courses. Otherwise you would not enjoy math so much by now.
I have taught at Danish Upper Secondary Schools for years now, and all those proofs have become so simple now, that I do not have to remember much to reconstruct them. I just apply the techniques I know and my general idea of what needs to be done, and in that manner I can reconstruct pretty much three volumes from memory at any date, I think. But these are simple things like basic proofs in differential calculus and vector calculus and the like.

Finally, just two words about my hero, Leibniz. He thought that the use of well suited language and notation was key to widening your understanding. He invented the notation $dx$ and $\int$ which to some degree shows this trademark. I too like re-phrasing proofs to try and make the language and notation a better vehicle for understanding!

A: The key is to understand the reasoning for each step of the proof. Most steps of a proof are simply the application of identities intrinsic to that field of mathematics.  Each academic level of a mathematics relies on a finite number of techniques that make up all proofs at that level; so by understanding them all you will understand the topic in much more detail (and have some tools for other branches of mathematics). Some steps of a proof may seem less natural, and those techniques are techniques that are intrinsic to another branch of mathematics you may not be familiar with. But, if you can comprehend why the mathematician did those kind of steps, you are widening mathematical capacity to understand other branches. I think the best way to understand a proof is to to try and prove something yourself.
Direct proofs are easy to understand. Start by using the identities intrinsic to your field and see what results you can come up with. Then compare your attempt with others to gain some understanding of the advantages of the steps you missed.
Sometimes a proof has more than one part. Consider the result of each part as a separate theorem and see if you can prove any part of it.  Compound proofs are usually more difficult because one part may seem unnecessary and so the proof of the apparently unnecessary theorem may not seem natural. The two main ways I know  to make those sub-theorems of a compound theorem more natural, is 1) by playing with the other sub-theorems to try and show  things (and failing) or 2) have somebody (like your lecturer) break down the theorem into those sub-theorems and explain why we need both sub-theorems!
Don't worry about the amount of time you spend playing/research understanding proofs. It is important! Once you grasp them, you will find that it clarifies other uncertainties in other proofs. So don't think of the situation as spending time to understand a single proof, in fact you are spending time to understand multiple proofs, as well as building an understanding of deeper concepts that derive from those concepts that you don't fully understand, because the reason you are not understanding a proof is because you are not grasping some concept!
Other types of proof are just as easy, and can be learned in a similar way. Sometimes you will be presented a theorem whose proof relies on many unique techniques compared with the proofs of other theorems at your level. Think of  understanding these as understanding the mindset of mathematicians in some other branch of mathematics you are not yet familiar with. It can be difficult, and perhaps even unenjoyable but by discovering a new mindset, proving things 4 years later is possible because you have the mindset to think of theorems in the required way and thus create the proofs by playing. Try and find the vocabulary that categorises proofs, and you will have resource to many techniques. Lastly, with those seemingly more unique proofs, see if you can use those techniques or the mindset itself to prove any other theorems of your course. If not, try and specify conditions when using the categorised approach is appropiate.


text:
Q: A problem about Multivariate Normal Distribution $(X,Y,Z)$ is a multivariate normal distribution. Calculate  $E[X^2YZ]$
I'm finding an approach for this problem. I'm not sure if it is possible to assume
$E[X^2YZ] = E[X^2]E[Y]E[Z]$

redpajama_set_name: RedPajamaStackExchange


text:
Q: React state variable -> undefined vs false Question is about what would be the best approach ->
For example : There is a termsAndCondition acceptance checkbox in a react component. If the user submits the next button on that component, there should be an error shown if user didn't selected the checkbox.
To handle this what I am doing is -> create a state variable, which is set to undefined on the component load, set to true when user selects and false if not selected and pressed the button. The condition to show the error message is when that state variable is false
so it's like if(termsAccepted === false) {
    console.log("show error message");
}
I really hate to check for false state variable here, also
I can't simply do if(!termsAccepted) {
    console.log("show error message");
}
because then it would show error message on the component load, which should not be the case
So what should be best way to handle this. There are many such situation when one has to decide between undefined and false.


text:
Q: Display lastName and name in application after retrieve value key in token Swift 4 I come back with my problem and I still find no answer
according to the previous solutions I had to develop the function to retrieve information (lastname, name) on the token
func loadMemberProfil(completion: ((_ sub : [String: AnyObject]) -> Void)!) {
    // get API profile and Bearer token
    let token = HPWSLoginManager.shared().saveSuccessResponse.token
    let url = URL(string: "http://51.38.36.76:40/api/v1/profile")
    var request = URLRequest(url: url!)
    request.httpMethod = "GET"
    request.addValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
    //get information in token
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        guard let data = data else { return }
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
            let sub = json["sub"] as! [String: AnyObject]
            if completion != nil{
              completion(sub)
            }
        } catch {
            print("error")

        }
        }.resume()
}

And in this function (that I call in viewDidLoad()) I want to display the name and lastname but nothing is displayed when I run the emulator
func initTableViewModel() {
    self.loadMemberProfil { (sub) in
        let headerMenu = HPMenuHeaderViewModel.init(firstName: "\(sub["firstname"])", lastName: "\(sub["lastname"])")
        let tableViewModel = HPMenuViewModel(titlePage: "Menu", array: arrayCellModel, headerMenuViewModel: headerMenu)
        self.tableViewModel = tableViewModel

    }
}

but i recover the values in the console please hep me

A: You are fetching but not reloading the data. You might want to read the documentation to understand the problem.
After you initTableViewModel you need to use the code below to reload the data. Note that the DispatchQueue.main.async is for doing that in the main thread.
DispatchQueue.main.async {
    self.tableView.reloadData()
}

A: in HPMenuHeaderViewModel class
class HPMenuHeaderViewModel: NSObject {
    var imageName: UIImage?
    var firstName: String?
    var lastName: String?
    var numberString: String?
    var name: String {
        return String.safe(firstName) + " " + String.safe(lastName)
    }
    var nameInitials: String {
        let arrayName = self.name.components(separatedBy: " ")
        return  arrayName.reduce("") { $0.safePrefix(1)  + $1.safePrefix(1)}
    }
    @objc init(firstName: String, lastName: String, numberString: String) {
        super.init()
        self.firstName = firstName
        self.lastName =  lastName
        self.numberString = numberString
    }
}

in HPMenuViewModel class
class HPMenuViewModel: NSObject {
    var titlePage: String?
    var accountTableViewCellModel: [HPMenuTableViewCellModel]?
    var headerMenuViewModel: HPMenuHeaderViewModel?
    init(titlePage: String, array accountTableViewCellModel: [HPMenuTableViewCellModel]?, headerMenuViewModel: HPMenuHeaderViewModel ) {
      super.init()
      self.titlePage = titlePage
      self.accountTableViewCellModel = accountTableViewCellModel
      self.headerMenuViewModel = headerMenuViewModel
    }
}

I use MVVM architecture


text:
Q: User selects multiple items using check_box form helper; POSTs data as array Trying to convert a form where previously only one option could be selected from multiple items using radio_button, to a form where multiple options can be selected using check_box.
Original code:
 <% @inventory.each do |category, list| %>

 <%="#{category.upcase}"%>

             <% list.each do |thing| %>
             <%= f.radio_button(:item, "#{thing}") %>
             <%= f.label(:item, "#{thing}") %>

             <% end %>

 <% end %>

If all the nested each|dos seem confusing, basically what's happening is there are multiple categories of items being generated from an inventory hash. Each category looks distinct on the form, but a radio_button check on any item in any category counts as the one item you're selecting.
The class is "Request" and the column that this data posts to is "Item":
class Request < ActiveRecord::Base
    validates :item, presence: true

I need to now make it so that a user can check any item in any category, and all of those items are POSTed as an array. I tried replacing the radio_button line with:
<%= f.check_box(:item, {:multiple => true}, "#{thing}") %>

It seems as though it's working, since I just tested and the Rails debugger shows the following:
request: !ruby/hash:ActionController::Parameters
  item:
  - '0'
  - '0'
  - Sleeping bag
  - '0'
  - Sleeping pad

However when I click the submit button, I get the error message that "Item cannot be blank."
Help?
EDIT: add controller code:
  def new
    @requestrecord = Request.new
    inventory #This calls a private method that lists all the items by category and list
    @pagetitle = "What would you like to borrow?"
  end

  def create
    @requestrecord = Request.new(request_params)
    inventory
    @pagetitle = "What would you like to borrow?"

    if @requestrecord.save
      flash[:success] = "Thanks, we'll respond in a few hours. Below is the information you submitted in case you need to change anything."
      @requestrecord.save_spreadsheet
      RequestMailer.confirmation_email(@requestrecord).deliver
      redirect_to edit_request_path(@requestrecord.edit_id)
    else
      render 'new'
    end
  end

  private
    def request_params
      params.require(:request).permit(:email, :item, :detail, :rentdate, :edit_id)
    end

A: You are making a typical mistake when handling array type of form parameters and strong parameters.
You need to tell the controller that it's ok to accept an array of "items".
So, change your definition of request_params liike this:
def request_params
    params.require(:request).permit(:email, {:item => []}, :detail, :rentdate, :edit_id)
end

And it should be over with this error.


text:
Q: How do I boot back into my MacOS? I had a 32GB partition for Ubuntu and then the rest for MacOS. I no longer wanted my Ubuntu partition so I formatted the partition on my MacOS.
I think the boot loader must've been on that partition because I can no longer boot into anything but a live Ubuntu USB.
when I run efibootmgr -v it can see my macOS partition (see http://paste.ubuntu.com/p/DXFzrz5zny/)
But how can I boot back into my MacOS? :S

A: My Mac knowledge is very sketchy, but since you've had such a hard time getting an answer I thought I'd tell you what I can see...
What's happened
I'm not convinced that you have destroyed your original boot loader, just the Ubuntu one.  The nice thing about EFI is that bootloaders can be stored side by side where previously you could have only one.
From your pastebin (line 279), the Ubuntu bootloader is set as first boot, with OS X second:
Boot0000* ubuntu    HD(1,GPT,4d8fdbeb-d6f8-4cce-86f9-f9dff8695276,0x28,0x64000)/File(EFIubuntushimx64.efi)
Boot0080* Mac OS X  PciRoot(0x0)/Pci(0x1c,0x5)/Pci(0x0,0x0)/Sata(0,0,0)/HD(2,GPT,cf2dd05b-2789-4d07-83c7-018ae532d035,0x64028,0xe19bfb0)/VenMedia(be74fcf7-0b7c-49f3-9147-01f4042e6842,c005e716a459d9459d1475bbdc249c88)/File(C78C0B9E-B1FA-38E2-8591-C135881B3B4ASystemLibraryCoreServicesboot.efi)
Boot0081* Recovery OS   PciRoot(0x0)/Pci(0x1c,0x5)/Pci(0x0,0x0)/Sata(0,0,0)/HD(2,GPT,cf2dd05b-2789-4d07-83c7-018ae532d035,0x64028,0xa60d400)/VenMedia(be74fcf7-0b7c-49f3-9147-01f4042e6842,1be0b02a55ba594f91a1f6008c00aa5c)/File(C78C0B9E-B1FA-38E2-8591-C135881B3B4Aboot.efi)
Boot0082*   PciRoot(0x0)/Pci(0x1c,0x5)/Pci(0x0,0x0)/Sata(0,0,0)/HD(2,GPT,cf2dd05b-2789-4d07-83c7-018ae532d035,0x64028,0xa60d400)/VenMedia(be74fcf7-0b7c-49f3-9147-01f4042e6842,c005e716a459d9459d1475bbdc249c88)/File(C78C0B9E-B1FA-38E2-8591-C135881B3B4ASystemLibraryCoreServicesboot.efi)
BootFFFF*   PciRoot(0x0)/Pci(0x1c,0x5)/Pci(0x0,0x0)/Sata(0,0,0)/HD(3,GPT,d8d6f046-d9e2-4b48-a5ae-0e225f7926b3,0x7dbffd8,0x4000000)/File(SystemLibraryCoreServicesboot.efi)

Ubuntu uses Grub which stores some files (in /boot/grub) on Ubuntu's file system.  So when you destroyed Ubuntu, you killed Grub.  But when you installed Ubuntu in the first place you probably didn't overwrite OS X.
Check if I'm right
You can check if I'm right using your Ubuntu Live USB browse your EFI partiton.  Double check which partition it is (I think /dev/sdb2).  Even if it's not labled "EFI" a FAT file system will be the right one:
sudo blkid | grep -i fat
/dev/sdb2: UUID="2641-087E" TYPE="vfat" PARTLABEL="EFI system partition" PARTUUID="27141f73-5de4-4785-8894-3c774fae7e79"

Mount the partiton, eg:
sudo mkdir /mnt/efi
sudo mount /dev/sdb2 /mnt/efi

Then search for "*.efi" files:
sudo find /mnt/efi/ -type f -iname '*.efi'

Hopefully you will find your bootloader there as well as grub.
How to fix it
Best Option - Reconfigure you mac's BIOS / Firmware to boot OSX directly
If you've got this far and shown your old EFI entry exists then this should be simple but ... Sorry I'm not a mac user.  I'll keep searching and update this answer if I find it.
Backup Option - Fix grub
Grub needs its config files to work and you've blown them away.  You can try to rebuild them by taking the files from your live USB.  First update the config on your live USB so that it knows about your system:
sudo update-grub

The output should mention Mac OS X if all is fine with OS X
Now you can either create a new partition to store the config files on, or you can  experiment to see if installing them directly on the EFI partition will work:
sudo mkdir /mnt/efi/boot
sudo cp -r /boot/grub /mnt/efi/boot/grub

Once you've installed them on the hard disk, you can then set grub to find them.  Find the PARTUUID for the partition containing these config files using  sudo blkid.  Then  Edit /mnt/efi/EFI/ubuntu/grub.cfg:

*

*replace the UUID for the PARTUUID you just found.

*change the partition number from to the correct gpt<partition number>.  Eg /dev/sdb6 should be gpt6:

Example:
search.fs_uuid 77b2d888-07e2-4d80-be84-ef1a584a194c root hd0,gpt6
set prefix=($root)'/boot/grub'
configfile $prefix/grub.cfg


text:
Q: The first item uploaded is deleted from mysql database when delete button is pressed in php page I have made a page where i can delete item. It seems like it's working good but when i press the delete button it always deletes the first item uploaded by that user not the one i chose... Here is the code:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Produktai</title>
<link href="CSS/stilius.css" rel="stylesheet" type="text/css"/>
<link href="CSS/menu.css" rel="stylesheet" type="text/css"/>

<?php require("includes/validate.php");?>
<?php require("includes/stilius.php");?>

<?php
$rec_limit = 4;
require("includes/connection_to_db.php");
$sql = "SELECT COUNT(P_ID) FROM prekės";
$retval = mysql_query($sql);
if(! $retval)
{ die('13 line. Nepavyko gauti duomenų: ' . mysql_error()); }
$row = mysql_fetch_array($retval, MYSQL_NUM);
$rec_count = $row[0];

if( isset($_GET{'page'} ) )
{
    $page = $_GET{'page'} + 1;
    $offset = $rec_limit * $page;
}
else
{
    $page = 0;
    $offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);

$sql = "SELECT prekės.* , CONCAT(vartotojai.name) as v_name
                    FROM prekės
                LEFT JOIN vartotojai
                    ON vartotojai.V_ID=prekės.V_ID
                ORDER BY prekės.date
        DESC LIMIT $offset, $rec_limit";
$retval = mysql_query($sql);
if(! $retval )
{
    die('38 line. Nepavyko gauti duomenų: ' . mysql_error());
}
?>
<?php
if(isset($_POST['deleteItem']))
{
$P_ID = $_POST['P_ID'];
if(mysql_query("DELETE
                FROM prekės
                WHERE P_ID = '$P_ID'"))
{
    header("Location: products.php");
}
else {echo "Prekės nepavyko ištrinti: " .mysql_error();}

}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<?php while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) : ?>

    <?php $image = '	' ?>

            <?php $pav = $row['name']; echo "$pav" ?>
            Prekės savininkas: <?php echo $row['v_name']?>
        <?php if($row['V_ID'] != $_SESSION['user_id']) : ?>
            <select name="mano_prekės" value="<?php echo $m_product;?>">
            <option value="">Pasiūlykite savo prekę</option>
            <option disabled>---------------------------------</option>
            <?php require ("includes/exchange.php") ?>
            </select>
            <input type="button" name="exchange" id="exchange" value="Mainyti">

        <?php elseif($row['V_ID'] = $_SESSION['user_id']) : ?>

            <input name="P_ID" type="hidden" id="P_ID" value=<?php echo $row['P_ID']?>>
            <input type="button" value="Redaguoti" id="edit_item">
            <input type="submit" name="deleteItem" id="deleteItem" value="Ištrinti" onclick="return confirm('Ar tikrai norite ištrinti šią prekę?')">

        <?php endif; ?>

            <?php echo $image?>
            <textarea disabled style="resize:none; background-color:white" name="about" rows="12" cols="65"><?php echo $row['specs']?></textarea>

<?php endwhile; ?>
</form>

<?php
if( $page > 0 )
{
    $last = $page - 2;
    echo "Atgal";
    echo "Pirmyn";
}
else if( $page == 0 )
{
    echo "Pirmyn";
}
else if( $left_rec < $rec_limit )
{
    $last = $page - 2;
    echo "Atgal";
}
mysql_close();
?>

If you see what i have made wrong, please tell me, cause it makes me a headache..

A: The problem is that your form encompasses all of the items, so when submitted it sends the last one of the IDs (which is the first uploaded item since you're ordering them in descending order).
You will need to wrap each individual set of inputs in their own form.

A: you a lot of P_ID in a single form you can try two solutions
Solution -1 : separate form for each item. (in each while)
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

            <?php $pav = $row['name']; echo "$pav" ?>
            Prekės savininkas: <?php echo $row['v_name']?>
        <?php if($row['V_ID'] != $_SESSION['user_id']) : ?>
            <select name="mano_prekės" value="<?php echo $m_product;?>">
            <option value="">Pasiūlykite savo prekę</option>
            <option disabled>---------------------------------</option>
            <?php require ("includes/exchange.php") ?>
            </select>
            <input type="button" name="exchange" id="exchange" value="Mainyti">

        <?php elseif($row['V_ID'] = $_SESSION['user_id']) : ?>

            <input name="P_ID" type="hidden" id="P_ID" value=<?php echo $row['P_ID']?>>
            <input type="button" value="Redaguoti" id="edit_item">
            <input type="submit" name="deleteItem" id="deleteItem" value="Ištrinti" onclick="return confirm('Ar tikrai norite ištrinti šią prekę?')">

        <?php endif; ?>

            <?php echo $image?>
            <textarea disabled style="resize:none; background-color:white" name="about" rows="12" cols="65"><?php echo $row['specs']?></textarea>

</form>

Solution 2 :  make delete as simple button and apply onclick event on it.
<input type="button" name="deleteItem" id="deleteItem" value="Ištrinti" onclick="if(confirm('Ar tikrai norite ištrinti šia preke?')){window.location.href='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>?deleteItem=true&P_ID=<?php echo $row['P_ID']?>';}">


text:
Q: How to vertically center image, text in materializecss btn creating a button using btn class,
and add image, text with in that
here both are vertically center if the image size is small,  ( like 40% )
but if the image size is 90% of the btn
text is not vertically center
can any one help me, to create a button, with a text and an image
and text will be vertically center.
please check the demo
html:

  Testing

css :
img {
  height: 90%;
}

A: try this i've added the svg inside an i tag and controlled the height of the svg inside it, see the code snippet

i{
width:auto; text-align:center;
}
i svg {
width:auto;height:40%;display:block;float:left;margin-right:10px;position:relative;top:33%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="384" height="448" viewBox="0 0 384 448">
<path fill="#000" d="M246.25 243.5c4.25 0 45 21.25 46.75 24.25 0.5 1.25 0.5 2.75 0.5 3.75 0 6.25-2 13.25-4.25 19-5.75 14-29 23-43.25 23-12 0-36.75-10.5-47.5-15.5-35.75-16.25-58-44-79.5-75.75-9.5-14-18-31.25-17.75-48.5v-2c0.5-16.5 6.5-28.25 18.5-39.5 3.75-3.5 7.75-5.5 13-5.5 3 0 6 0.75 9.25 0.75 6.75 0 8 2 10.5 8.5 1.75 4.25 14.5 38.25 14.5 40.75 0 9.5-17.25 20.25-17.25 26 0 1.25 0.5 2.5 1.25 3.75 5.5 11.75 16 25.25 25.5 34.25 11.5 11 23.75 18.25 37.75 25.25 1.75 1 3.5 1.75 5.5 1.75 7.5 0 20-24.25 26.5-24.25zM195.5 376c86.5 0 157-70.5 157-157s-70.5-157-157-157-157 70.5-157 157c0 33 10.5 65.25 30 92l-19.75 58.25 60.5-19.25c25.5 16.75 55.75 26 86.25 26zM195.5 30.5c104 0 188.5 84.5 188.5 188.5s-84.5 188.5-188.5 188.5c-31.75 0-63.25-8-91.25-23.5l-104.25 33.5 34-101.25c-17.75-29.25-27-63-27-97.25 0-104 84.5-188.5 188.5-188.5z"></path>
</svg>

  Testing

A: In your plunker add below css line:
img{width:20px;height:20px;vertical-align:middle}
span{padding-left:7px;}

A: Put to the image css a new atributte vertical-align:middle;


text:
Q: How to change font color inside the doughnut chart using Chart.js? I rendered Text inside the doughnut chart, I am using ChartJs. But I can not find a way to change the font color of the text.
   Chart.pluginService.register({
        beforeDraw: function(chart) {
            if(chart.canvas.id === "myChart") {
                var width = chart.chart.width,
                    height = chart.chart.height,
                    ctx = chart.chart.ctx;

                ctx.restore();
                var fontSize = (height / 114).toFixed(2);
                ctx.font = fontSize + "em sans-serif";
                ctx.textBaseline = "middle";
                ctx.fontColor = "red";
                var text = "75%",
                    textX = Math.round((width -
                ctx.measureText(text).width) / 2),
                    textY = height / 2;

                ctx.fillText(text, textX, textY);
                ctx.save();
            }
        }
    });

A: You need to define a fillStyle before fillText like below.
 Chart.pluginService.register({
        beforeDraw: function(chart) {
            if(chart.chart.canvas.id === "myChart") {
                var width = chart.chart.width,
                    height = chart.chart.height,
                    ctx = chart.chart.ctx;

                ctx.restore();
                var fontSize = (height / 114).toFixed(2);
                ctx.font = fontSize + "em sans-serif";
                ctx.textBaseline = "middle";
                ctx.textColor = "red";
                var text = "75%",
                    textX = Math.round((width -
                ctx.measureText(text).width) / 2),
                    textY = height / 2;
                ctx.fillStyle = 'rgba(0, 0, 255, 1)';
                ctx.fillText(text, textX, textY);

                ctx.save();
            }
        }
    });

I also noticed in the if statement where i checked for chart.canvas.id === "myChart"
I had to change it to chart.chart.canvas.id === "myChart"


text:
Q: Trying to make a simple entry widget but keep getting an error I'm just trying to make a very simple entry widget and grid it on the window but I keep getting an error. Anyway I can fix it?
code:
e = tk.Entry(root, borderwidth=5, width=35)
e.grid(root, row=0,column=0, columnspan=3, padx=10, pady=10)

Error:
Traceback (most recent call last):
  File "C:\Users\mosta\PycharmProjects\pythonProject\main.py", line 298, in <module>
    e.grid(root, row=0, column=0, columnspan=3, padx=10, pady=10)
  File "C:\Users\mosta\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2522, in grid_configure
    self.tk.call(
_tkinter.TclError: bad option "-bd": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky

A: You need to remove the argument root from the grid command.
e.grid(row=0,column=0, columnspan=3, padx=10, pady=10)

A: By using the .place() method instead of the .grid() method, I have successfully gotten the Entry widget to work.
from tkinter import *
root = Tk()
e = Entry(root, borderwidth=5)
e.place(x=10, y=10, height=25, width=180)

I hope that this helps :-)


text:
Q: Replace LiveData with EventBus in multi activity Currently my project used EventBus to post event and I am trying to replace LiveData with EventBus. In theory, they work similarly. I migrated without no pain in the beginning. But it comes up a scenario I have no idea how to deal with it.
And here's is the scenario.
LaunchActivity -> PersonInfoActivity -> UpdateInfoActivity
Currently We use EventBus to subscribe UserInfoEvent in LaunchActivity and PersonInfoActivity
LaunchActivity.java
public class LaunchActivity{
     @Subscribe(threadMode = ThreadMode.MAIN)
     public void onEvent(UserInfoEvent event){

     }
}

PersonInfoActivity.java
public class PersonInfoActivity{
     @Subscribe(threadMode = ThreadMode.MAIN)
     public void onEvent(UserInfoEvent event){

     }
}

UpdateInfoActivity.java
public class UpdateInfoActivity{
     public void onSubmit(){
          EventBus.getDefault().post(new UserInfoEvent());
     }
}

And the question is , I want to use LiveData to replace this scenario
What I have done?
I have read about the question about singleton usage with livedata Room - LiveData observer does not trigger when database is updated, I want to try to use the same way but no luck. The Event is fire everytime in onChanged() when I started the Activity

A: You can achieve it with the use of viewModel implementation. Like,
public class UserViewModel extends AndroidViewModel {
private UserRepository userRepository;
private LiveData<List<UserData>> getUser;

public UserViewModel(@NonNull Application application) {
    super(application);
    userRepository = new UserRepository(application);
    getUser= userRepository.getUser();
}

public LiveData<List<UserData>> getUser() {
    return getUser;
}
}

After creating this class, Update your PersonalInfoActivity and LaunchActivity like,
private UserViewModel userViewModel;

    userViewModel.getUser().observe(this, new Observer<List<UserData>>() {
    @Override
public void onChanged(@Nullable final List<UserData> user) {
//write code to set data of user to show using list of user
}
});

Kindly leave commnet if you find any query regarding this.

A: I think there is some misinterpretation regarding LiveData. You can have a look here
It might help you.Also you can check this for event bus implementation with LiveData event bus with liveData
Hope it helps!!!

A: I created a library called LivedataBus from the tutorial
.You can use it like this:
 //Subscribe
 LiveDataBus.subscribe("event_name", this, Observer {
        it.runAndConsume {
            Toast.makeText(this, "Hello ${it.value}", Toast.LENGTH_LONG).show()
        }
    })

 //Publish
 val obj = SomeEvent()
 LiveDataBus.publish("event_name", ConsumableEvent(value = obj))

The magic is that I used the ConsumableEvent, which can be consumed after firing event, prevent to get the last data from the static Bus.
I use it in my current project, and it works well on multiple activities & fragments.
The benefit of this lib is that it works on Livedata, and you don't need to care about activity or fragment lifecycle.

A: You can declare and initialize the live data instance in the singleton class. And can use the same instance in all three different activities.


text:
Q: prevent hashchange on back button I have an application which uses backbone hash routing. When the page reloads I use the onbeforeunload event to tell the user that there are unsaved changes and prevent the page load. This does not work on hash change; so if the user presses back the dialog does not tell them there are changes pending and just goes back.
Is there anyway to detect the hash change and prevent it happening? something like onbeforehashchange

A: Nope, you can detect the hashchange as it happens with something like below, but you can't really detect it before it happens. If you need the hash before it changes you can just store it somewhere.
var myHash = document.location.hash;

$(document).on('hashchange', function() {
    if (myHash != document.location.hash) {
        //do something
    }
});

You can't really detect the back button either, and if it does'nt trigger a reload, onbeforeunload won't work either.
If this functionality is essential, you should consider trying the haschange plugin or the history plugin, as one of those would make this a lot easier, and let you control the browser history and back/forth.

A: I ended up creating a function in my router. This is run before each route and puts up a jquery ui dialog and waits for a reply to run the route. This is quite messy code a I stripped out the application specific stuff.
close: function(callback) {
    var hash = window.location.hash;

    if (this.afterHash && this.afterHash == hash) {
        this.dialog.dialog("close");
        return;
    }

    callback = callback || function () {};
    if (window.onbeforeunload) {
        var text = window.onbeforeunload();
        if (text) {
            if (!this.dialog) {
                var t = this;
                this.afterHash = this.previous;
                this.dialog = $("

" + text + "

Are you sure you want to close the dialog?

").dialog({
                    modal: true,
                    width: 420,
                    title: "Confirm Navigation",
                    close: function() {
                        t.dialog.dialog("destroy");
                        if (t.afterHash) {
                            t.navigate(t.afterHash, {
                                trigger: false
                            });
                            t.afterHash = null;
                        }
                        t.dialog = null;
                    },
                    buttons: {
                        'Leave this Page': function() {
                            t.afterHash = null;
                            t.dialog.dialog("close");

                            closeViewer();
                            callback.apply(t);
                        },
                        'Stay on this Page': function() {
                            t.dialog.dialog("close");
                        }
                    }
                });
            }
            return;
        }
    }
    this.previous = window.location.hash;
    callback.apply(this);
},

on initialize you must add this.previous = window.location.hash;


text:
Q: How is Angular 2 lighter than Angular 1? I'm new to Angular 2. I've just created new starter project using angular-cli and done ng build --prod. I've got a dist folder 8.2 Mb.
Here's the output:

I have three questions:

*

*What files do I actually need?

*What else can be done to minimize the size?

*Is it possible to fetch gzipped files in HTML page as if they
were regular scripts? I mean, would it be valid <script  src='...script.gz'></script>?

A: *

*Don't measure the number of files loaded during development. With Angular2 and TS you have a build step and for size measurement, only the output of the build step is relevant

*A big difference between A1 and A2 is that A1 can work without loading an Angular library into the browser. When AoT (ahead of time compilation) is used, the Angular2 components templates are processed and JS generated for bindings, therefore no Angular library that loads, parses and compiles, and processes components templates is necessary.

*

*This build step and AoT also allow tree-shaking across the whole code base

*Change detection is working completely different.

*

*Through the use of zones, Angular2 is much more efficienct in detecting when change detection needs to be done.

*Because of the unidirectional data flow Angular can limit the scope of where change detection needs to happen within the DOM tree.

*Using ChangeDetectionStrategy.OnPush and other measures allow the developer to further restrict where and when change detection needs to run

The Angular2 team is still working on further optimize all kinds of things and I'm sure there is quite some room for further improvements.


text:
Q: Comparing inside of elements from 2 different arrays and gives actions? Is there any ways to compare index numbers from 2 different arrays?
Here's what I want to do:
if i[0] == k[0] {
    //give some action to k[0]
} else if i[1] == k[1] {
    // give some action to k[1]
}

...and so on.
I could've made each functions 0 to 4 to fix my problem like that, but then the code would've been too long and unreadable. I want to optimize my code as much as I can.
I wrote the code like this but this doesn't work what I want. All the k keeps getting action when I hover one of the box group.

And this is my code:
var i = $('#boxgroup').children()
var k = $('#panelgroup').children()
  $(i).each(function() {
    $(this).hover(function() {
      if($(i == k)){
         $(k).stop().animate({height: '500px'})}
    }, function(){
         $(k).stop().animate({height: '200px'})
    })
})

  #boxgroup{
    width: 600px;
    height: 200px;
    border: 1px solid black;
    clear: both;
  }
  .box {
    width: 200px;
    height: 50px;
    border: 1px solid black;
    float: left;
    position: relative;
    top: 0px;
    margin: 10px;
    }
  .panelgroup {
    clear: both;
  }
  .panel {
    width: 200px;
    height: 200px;
    border: 1px solid gray;
    top: 400px;
    float: left;
  }

1

2

3

4

panel1

panel2

panel3

panel4

A: It sounds like you want hovering over a child in #boxgroup to make the equivalent child in #panelgroup larger. If so, you don't need a series of ifs, you just need the index of the element:
$('#boxgroup > *').hover(
    function() {
        var index = $(this).index(); // Returns its index within boxgroup
        $("#panelgroup > *:eq(" + index + ")").stop().animate({height: '500px'});
    },
    function() {
        var index = $(this).index(); // Returns its index within boxgroup
        $("#panelgroup > *:eq(" + index + ")").stop().animate({height: '200px'});
    }
);

Live Example:

$('#boxgroup > *').hover(
    function() {
        var index = $(this).index(); // Returns its index within boxgroup
        $("#panelgroup > *:eq(" + index + ")").stop().animate({height: '500px'});
    },
    function() {
        var index = $(this).index(); // Returns its index within boxgroup
        $("#panelgroup > *:eq(" + index + ")").stop().animate({height: '200px'});
    }
);
#boxgroup{
    width: 600px;
    height: 200px;
    border: 1px solid black;
    clear: both;
  }
  .box {
    width: 200px;
    height: 50px;
    border: 1px solid black;
    float: left;
    position: relative;
    top: 0px;
    margin: 10px;
    }
  .panelgroup {
    clear: both;
  }
  .panel {
    width: 200px;
    height: 200px;
    border: 1px solid gray;
    top: 400px;
    float: left;
  }

1

2

3

4

panel1

panel2

panel3

panel4

See:

*

*index

*:eq


text:
Q: Send parameters to php with ajax call I have a html select list that I want to use to filter data in an li list. When user selects a list option the li list gets filtered based on the selection. all this data is stored in database. What I am trying to do is on change event in jquery check the value of selected option and then send that data to the server to use as a parameter for a query to the database.
HTML:
<select id="universeList">
   <option data-id="1">DC</option>
   <option data-id="2">Marvel</option>
</select>

Superman

Iron Man

SpiderMan

Captain America

Hulk

Batman

Flash

JS:
$(document).on("ready", function() {

  //ajax call to populate dropdown
   $.ajax({
        type: "GET",
        url: "getUniverseList.php",
        dataType: 'json',
        cache: false,
        success: function(results) {
            console.log(results);
            $.each(results, function(index, result) {
                console.log(result);

                $('#universeList').append('<option data-id="'+result.universeID+'">'+result.universe+'</option>');

            });
        }
    });

    //ajax call populate heroes list
    $.ajax({
        type: "GET",
        url: "getheroesList.php",
        dataType: 'json',
        cache: false,
        success: function(results) {
            console.log(results);
            $.each(results, function(index, result) {
                console.log(result);

                $('#heroesList').append('
'+result.heroes+'
');

            });
        }
    });

$(document).on('change', '#universeList', function(){
    var universeSel = $('#universeList option:selected').data('id');
    $('#heroesList li').each( function() {
        $(this).remove();
    });

    console.log(manikinSel);
    $.ajax({
        type:"GET",
        url:"getheroesFilter.php",
        dataType: 'json',
        data: ( {name: universeSel} ),
        cache: false,
        success: function(results) {

            console.log(results);

    }

});

});

});

PHP:
<?php

//db information

$mid = $_POST['manikinSel'];

$sql = "Select universeID, heroesID From heroesmanikins bm
    INNER JOIN heroesList b
    ON bm.heroesId=b.heroesId
    INNER join heroessList m
    ON bm.universeID=m.universeId
    WHERE heroesID=`$mid`
    ";

 try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$stmt->execute();
$employee = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo  json_encode($employee) ;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}

?>

fiddle
I am using ID to match the tables and have ID as a data attribute to the option list. I want to send the ID for Universe back to php so it can be used to query matching ID's from the db tables.
I cannot figure out why my 'data: ( {name: universeSel} )' is not sending the data to the server.


text:
Q: Open ssh in terminal by clicking on "ssh://user@host" links in browser I found a nice way to open a terminal with SSH to user@host if you click on a link that looks like this:
ssh://user@host

I guess the above solution works. It is great.
I need to get this working on many PCs. Is there already a package which does the enable SSH URLs?

A: No, there is no package for this because there is already support for it, you just have to enable it.
To enable it in a gnome desktop: (How to open ssh://username@hostname link)
gconftool-2 --set --type=bool /desktop/gnome/url-handlers/ssh/enabled true
gconftool-2 --set --type=string /desktop/gnome/url-handlers/ssh/command 'gnome-terminal -e "%s"'
gconftool-2 --set --type=bool /desktop/gnome/url-handlers/ssh/needs_terminal false

My script to install the handler application:

#!/bin/bash
# We need root to install
if [ "$(id -u)" != "0" ]; then
  echo "This script must be run as root" 1>&2
  exit 1
fi

# In case file exists
if [ -f "/usr/local/bin/ssh-url-handler" ]
then
  echo "Found an old install, moving to ssh-url-handler.old"
  mv /usr/local/bin/ssh-url-handler /usr/local/bin/ssh-url-handler.old
fi

# Install handler file
touch /usr/local/bin/ssh-url-handler
echo '#!/bin/sh' >> /usr/local/bin/ssh-url-handler
echo 'd=${1#ssh://}' >> /usr/local/bin/ssh-url-handler
echo 'x-terminal-emulator -x bash -c "ssh $d" &' >> /usr/local/bin/ssh-url-handler
chmod a+x /usr/local/bin/ssh-url-handler

# Check that it is there
type ssh-url-handler >/dev/null 2>&1 || echo "Warning: the ssh-url-handler could not be found! Please check that /usr/local/bin is in the PATH"

# Now for the desktop piece:
if [ -f "/usr/share/applications/ssh-url-handler.desktop" ]
then
  echo "Found an old desktop handler, moving to .old"
  mv /usr/share/applications/ssh-url-handler.desktop /usr/share/applications/ssh-url-handler.desktop.old
fi

touch /usr/share/applications/ssh-url-handler.desktop
echo "[Desktop Entry]" >> /usr/share/applications/ssh-url-handler.desktop
echo "Type=Application" >> /usr/share/applications/ssh-url-handler.desktop
echo "Name=SSH URL Handler" >> /usr/share/applications/ssh-url-handler.desktop
echo "Exec=ssh-url-handler %u" >> /usr/share/applications/ssh-url-handler.desktop
echo "Icon=utilities-terminal" >> /usr/share/applications/ssh-url-handler.desktop
echo "StartupNotify=false" >> /usr/share/applications/ssh-url-handler.desktop
echo "MimeType=x-scheme-handler/ssh;" >> /usr/share/applications/ssh-url-handler.desktop
chmod a+x /usr/share/applications/ssh-url-handler.desktop

Just drop that into the install.sh of any debian package. You can easily do this using https://github.com/jordansissel/fpm/wiki to make your own package and distribute that.


text:
Q: Button ng drop down- how to choose the item using webdriver with java I have a button with drop down item,
if i click the button it's open the list and choose the item
below is the html
<button id="btn-append-to-body" class="btn btn-primary mobile-quick-button dropdown-toggle" type="button" uib-dropdown-toggle="" aria-haspopup="true" aria-expanded="false">

   Select one

</button>

frame number

serial number

I want to choose any one of the item from this list,
public void lookupSearch (String item){
driver.findElement(By.xpath("//*[@id='btn-append-to-body']")).click();
//then i choose/click the parameter item (i.e frame number or serial number)
}

passing the item as parameter
please guide me how should i choose the item

A: To click on the button with drop down item and choose any one of the item from this list you can use the following code block :
public void lookupSearch (String item)
{
    driver.findElement(By.xpath("//button[@id='btn-append-to-body']/div/span[contains(.,'Select one')]")).click();
    WebDriverWait wait4elements = new WebDriverWait(driver, 10);
    List<WebElement> myElements = wait4elements.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//ul[@class='uib-dropdown-menu dropdown-menu']/li/a/div/span"), 2));
    for(WebElement elem:myElements)
        if(elem.getAttribute("innerHTML").contains(item))
        {
            elem.click();
            break;
        }
    System.out.println("Element with text as "+ item +" is selected");
}

A: below is the answer from ul find the Li count, then getting each li text and compare with item string
WebElement uList = driver.findElement(By.xpath("//*[@id='quick-search-dropdown']/ul"));
            List<WebElement> listCount = uList.findElements(By.tagName("li"));
            for (int i = 1; i <= listCount.size(); i++) {
                WebElement lookupItem = driver.findElement(By.xpath("(//li[@id='quickOption']/a/div/span[1])[" + i + "]"));
                String lookupItemValue = lookupItem.getText();
                if (lookupItemValue.equalsIgnoreCase(Item)) {
                    lookupItem.click();
                }
            }


text:
Q: Python BeautifulSoup Automatically tracking content table rows andcolumns First let me say that I am new to Stack and to Python. I just started working with it last week. I am however a seasoned PHP/C++/Pascal/ADA/B/Forth (showing my age) programmer.
I have written a script that pulls product pages from a website and stores them in my local MySQL database. I did this so that I can crawl the site late at night when the load is light. I now need to sort through the html of each page and get the product descriptions. These are placed in tables. However, each page may have the needed values in different rows/columns.
The things I can be sure of are:

*

*Each table has a heading that defines the data in the rows/columns below it.

*The heading text is consistent for each value i.e. 'Part' always describes the part type and 'Part No.' always describes a part number.

*Not all pages will contain all the data desired. So If not located it must save what it finds.

In the section below it is the second part, getting the data values that I am having trouble with. How do I select the nth column from a row?

My current approach is:
 To Get Desired Columns

*

*Get html doc from db

*Grab the table (my table is always contained in the only div on the page.

*Grab all the rows (really only need to do this for the first row)

*For each row grab the row and column index' when I find a desired field names.

 To Get Data Values

*

*For each row:

*Skip the row if it was a header (save the row counts for those with header fields)

*for each column grab the text value.

*Save the values to db

The important part of my page looks like this:

   ...

 	Item	 	Description	 	Part No.	 	Color

 	Toaster	 	2-Slice	 	#25713	 	Chorme

   ...

A Big thank you to anyone who responds.

A: Here's how I'd tackle it:
from BeautifulSoup import BeautifulSoup

doc = '''

 	Item	 	Description	 	Part No.	 	Color

 	Toaster	 	2-Slice	 	#25713	 	Chorme

'''

soup = BeautifulSoup(doc)
# find the table element in the HTML document
table = soup.find("table")
# grabs the top row
firstRow = table.contents[0]
# find how many columns there are
numberOfColumns = len(firstRow.contents)
restOfRows = table.contents[1:]
for row in restOfRows:
  for x in range(0,numberOfColumns):
    print "column data: %s" % row.contents[x].string

That will extract the table element from any document. Then find the number of columns based on the first row. Finally, it will loop through the rest of the rows printing out the data in the row.
Useful link to BS docs: http://www.crummy.com/software/BeautifulSoup/documentation.html

A: Here is how you do it with HTQL:
import htql;
doc = '''

 	Item	 	Description	         	Part No.	 	Color

 	Toaster	 	2-Slice	 	#25713	 	Chorme

''';

query = "
.
.
{item=&tx; desc=&tx | item<>'Item'}";

for item, desc in htql.HTQL(doc, query):
    print(item, desc);


text:
Q: Playing .mov .mp4 in diffent resolution size in iPhone I have to develop a player in iPhone that play videos. I have not much background in video encoding and signal encoding. When I test some .mp4 and .mov file I see that only the video with resolution that fits the iPhone screen size can be played and larger size cannot be played. Are there any solutions to play all the movie size on iPhone in that case. Please give me some instruction. Many thanks in advance. The code to play the video is below:
NSURL *url = [NSURL URLWithString:@"http://192.65.123.108/test1.mov"];

//this movie has size of 480x272 can be played, other larger resolution cannot be played

_moviePlayer =  [[MPMoviePlayerController alloc]
                 initWithContentURL:url];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlayBackDidFinish:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:_moviePlayer];

_moviePlayer.controlStyle = MPMovieControlStyleDefault;
_moviePlayer.shouldAutoplay = YES;
[self.view addSubview:_moviePlayer.view];
[_moviePlayer setFullscreen:YES animated:YES];

A: I don't think there is a way to do this, unless you can scale the video down before you play it. It would probably be inefficient though.


text:
Q: How to set spinner values in android those are coming from list? I have a spinner like below
final Spinner spinner = (Spinner) findViewById(R.id.primary_game_spinner);

primary_games = (Spinner) findViewById(R.id.primary_game_spinner);
ArrayAdapter<String> games_adapter = new ArrayAdapter<String>(SignupActivity.this,
                    android.R.layout.simple_spinner_item, allNames);
primary_games.setAdapter(games_adapter);

and the xml is ...
<Spinner
            android:id="@+id/primary_game_spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginLeft="100dp" />

now i would like to set the values upon data. Meaning that if i select one item in spinner it has to give id of that spinner item.
That values i have in ListArray()...
How can i achieve this?
Thanks & Regards


text:
Q: How to remove an element from an array in Python I have an array named 'a' with the numbers 1 to 10,000 in it. I would like jump through the list in 2s, which I have managed successfully. However, I want the program to remove every second number, like the number '2' for example, which would be assigned to 'x'. I have tried functions such as .pop() but I don't seem to be getting anywhere. Please can someone help. Am i just using the function wrong?
for x in range(0,9999,2):
    a.pop()

A: Why not just create a list of the values you do want. It is a lot more efficient:
a = range(1,10000)

a = a[1::2]     #will contain all the even numbers

By the way, the reason your code is not working is because you are (in a sense) modifying your list while iterating through it. You should avoid it thoroughly unless you are absolutely sure that that is what you want.
The syntax above uses the list[start:end:step] syntax. Therefore, [1::2] will get every second element of the list starting at the second element. Similarly, [::2] will get every second element of the list starting at the default 1st element since no start index was specified.

A: Using list comprehension
a = [i for i in range(10000) if not i%2]


text:
Q: Go graceful shutdown negative WaitGroup I have tried to implement a graceful shutdown of the go server, as described in this blog post http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/. The main bits are the following.
Custom listener:
var httpWg sync.WaitGroup  // initialised in the other part

type gracefulListener struct {
    net.Listener
    stop    chan error
    stopped bool
}

func newGracefulListener(l net.Listener) (gl *gracefulListener) {
    gl = &gracefulListener{Listener: l, stop: make(chan error)}
    go func() {
        _ = <-gl.stop
        gl.stopped = true
        gl.stop <- gl.Listener.Close()
    }()
    return
}

func (gl *gracefulListener) Accept() (c net.Conn, err error) {
    c, err = gl.Listener.Accept()
    if err != nil {
        return
    }

    c = gracefulConn{Conn: c}  // wrap using our custom connection

    httpWg.Add(1)  // increase the counter
    return
}

func (gl *gracefulListener) Close() error {
    if gl.stopped {
        return syscall.EINVAL
    }
    gl.stop <- nil
    return <-gl.stop
}

func (gl *gracefulListener) File() *os.File {
    tl := gl.Listener.(*net.TCPListener)
    fl, _ := tl.File()
    return fl
}

Custom Conn:
type gracefulConn struct {
    net.Conn
}

func (w gracefulConn) Close() error {
    httpWg.Done()  // <- panics sometimes
    return w.Conn.Close()
}

The idea is when the program receives SIGTERM, it stops serving new connections and just waits for the httpWg.Wait() for existing connections to finish.
This approach works locally, but when I deploy it, sometimes I receive a panic in the gracefulConn.Close() at httpWg.Done() line:
panic: sync: negative WaitGroup counter

The panic happens not when I stop the server but just during routine serving.
How is it possible, that there are more Close() calls then Accept() calls? Or am I missing something?
P.S. I have tried to add stopped property and a mutex to gracefullConn, so in Close it locks the mutex and checks stopped to ensure we stop it only once. However, I still received the same panic.

A: Close() can be called multiple times so you definitely need to check for that in func (w gracefulConn) Close() error.

P.S. I have tried to add stopped property and a mutex to gracefullConn, so in Close it locks the mutex and checks stopped to ensure we stop it only once. However, I still received the same panic.

Keep in mind that gracefulConn if passed as a value not a reference so any mutexes/flags will not work as expected. So be sure to turn c = gracefulConn{Conn: c} into c = &gracefulConn{Conn: c}.

A: I think this is the wrong approach.
You don't really care about whether the connection is open or not - what about persistent connections?
What you care about is whether you are actively using those connections.  You'd be better off putting your WaitGroup into a custom ServeMux into the ServeHTTP method I think. You can then have the WaitGroup around a function call.


text:
Q: how to send multiple json objects /data to server using volley in android i am using volley for the http request... to pass multip data to the server .the code is working fine ,but only one json object is passing to the server..
    this is what i want to pass to the server to store in server's database.
 "usernname":"username1","email":"email1","password":"password1"
"usernname":"username2","email":"email2","password":"password2"
"usernname":"username3","email":"email3","password":"password3"

is it right to loop through the Map<String, String>??

***protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<>();
            for(int i=0;i<3;i++){
                params.put("username", username+i); //post variable in the php code.."username""email","password"
                params.put("email", email+i);
                params.put("password", password+i);
                //registerUser();

            }
            return params;***

**here is the full function that i am using..**

private void registerUser() {

   final String email = "user1";
   final String username = "user1";
  final String password = "user1";

    StringRequest stringRequest = new StringRequest(Request.Method.POST,Constants.URL_REGISTER,new Response.Listener<String>() {
        @Override
        public void onResponse(String response) { /

            try {

                JSONObject jsonObject = new JSONObject(response);

                Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                // Handle error
                public void onErrorResponse(VolleyError error) {
                   // progressDialog.hide();
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {

        @Override

        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<>();
            for(int i=0;i<3;i++){
                params.put("username", username+i); //post variable in the php code.."username""email","password"
                params.put("email", email+i);
                params.put("password", password+i);
                //registerUser();

            }
            return params;

        }
    };

    RequestHandler.getInstance(this).addToRequestQueue(stringRequest);

}

Kindly please help!!

A: Create class User with required fields : username, email, password
Then create List userList with your user data
Use Gson to convert List to Json String .
String rawUser  = new Gson().toJson(userList )

Then you can put single raw user data to params as
params.put("raw_user_data", rawUser)

Now in server you can decode Json Array and get all data through iteration.


text:
Q: How to find rows where a set of numbers is between two numbers? I have a query which returns a set of numbers:
SELECT Sequence FROM Table1 WHERE Hash=2783342

Returns:
578
642
313

Now, I want to find all rows in the first table where any of that set of numbers is between two other columns. For the purpose of illustration, I am just picking 578, but I also want all of the rest:
SELECT * FROM Table1 WHERE 578 BETWEEN Sequence AND SequenceEnd

A: Using a JOIN, but risks duplicates:
SELECT t.*
  FROM TABLE1 t
  JOIN (SELECT Sequence FROM Table1 WHERE Hash=2783342) x ON x.sequence BETWEEN t.sequence
                                                                            AND t.sequenceend

Using EXISTS, no duplicate risk:
SELECT t.*
  FROM TABLE1 t
 WHERE EXISTS(SELECT NULL
                FROM TABLE1 x
               WHERE x.hash = 2783342
                 AND x.sequence BETWEEN t.sequence
                                    AND t.sequenceend)


text:
Q: Problems when uploading image to server nginx php 7.4 UPLOAD_ERR_NO_TMP_DIR with same req I'm trying to upload an image with postman to my server. The problem is that it sometimes works and sometimes it does not.
I'm using exactly the same request every time. Is this some kind of protection within nginx or php?
When it works:
 [image] => Array
        (
            [name] => 9.jpeg
            [type] => image/jpeg
            [tmp_name] => /home/test/tmp/php9LDwAL
            [error] => 0
            [size] => 351162
        )

When it fails:
[image] => Array
        (
            [name] => 9.jpeg
            [type] =>
            [tmp_name] =>
            [error] => 6
            [size] => 0
        )

PHP 7.4.29
edit 1: found some error logs:

File(/tmp) is not within the allowed path(s): (/home/test/web/site.com/public_html:
/home/test/tmp) in Unknown on line 0

[Fri May 20 19:56:02.661312 2022] [php7:warn] [pid 15995] PHP Warning:
File upload error - unable to create a temporary file in Unknown on line 0

edit 2:
I think i found the problem.
When uploading a file to the server it uses sometimes
sys_temp_dir and sometimes upload_tmp_dir as upload_dir
i first changed sys_temp_dir to /home/test/tmp without luck. After changing it to /home/test/web/site.com/public_html/tmp/ it is now working, but still does not feel like a proper solution.
Can someone please explain why the upload occasionally uses different paths? sys_temp_dir / upload_tmp_dir


text:
Q: Is it odd that my SQLAlchemy MySQL connection always ends up sleeping? I have a Flask web application using SQLAlchemy with MySQL, and I have set up a scopedsession(). I also have a teardown_request handler that calls session.remove() after every request is finished. For some odd reason, if no requests are made on the web app for a day or more, the app gets "Operationalerror: MySQL Server has gone away".
In my debugging  mission, I looked at SHOW PROCESSLIST and saw the following:
39817253 | sqladmin | my_host | kb_dev   | Sleep   |  174 |

The 174 is the number of seconds the connection from my application has been "sleeping". It keeps counting up if the application doesn't make another request.
It seems like my application holds on to the connection to MySQL even after my request has finished! And there is usually only one process no matter how many requests I make with my application, simultaneously or not.
My question is if it is normal for the connection to be "sleeping" this long? I'm pretty sure the extended sleeping is causing MySQL to cut the connection after a certain timeout which in turn is causing the "OperationalError: Mysql has gone away" error.

A: SQLAlchemy's default behavior is to pool connections within the Engine:
http://www.sqlalchemy.org/docs/core/engines.html
http://www.sqlalchemy.org/docs/core/pooling.html
As far as the disconnect overnight thing, this is a known MySQL behavior, SQLAlchemy provides the pool_recycle flag to work around it.   Here are many links which describe it:
http://www.sqlalchemy.org/docs/dialects/mysql.html#connection-timeouts
http://www.sqlalchemy.org/docs/core/pooling.html#setting-pool-recycle
http://www.sqlalchemy.org/docs/core/engines.html#sqlalchemy.create_engine (pool_recycle)
http://www.sqlalchemy.org/trac/wiki/FAQ#MySQLserverhasgoneaway
Blog post from just a few days ago:
http://douglatornell.ca/blog/2012/01/08/staying-alive/


text:
Q: Why do I need evaluation contexts in Redex? It's perfectly possible to write the evaluation rules for my language without using evaluation contexts.  My semantics are entirely call by value and do not permit the term to be stepped forwards inside of lambdas.  Despite this, all the resources I've seen use reduction contexts in some way.  Is there a good reason to use contexts that I am missing?

A: Short answer: You don't, but its much easier with them.
Long answer: Pretty much everything you would use an evaluation context for, you can do yourself with a different reduction rule in your reduction relation, it just becomes much more obnoxious, especially as you model anything but the smallest of languages.
Let's say you want to model the call by value lambda calculus. The language for it (without evaluation contexts) would be:
(define-language Lv
  (v (λ (x) e))
  (e v
     (e e))
  (x variable-not-otherwise-mentioned)
  #:binding-forms
  (λ (x) e #:refers-to x))

(here, the last two lines are used to take advantage of Redex's capture avoiding substitution.
Now, lets try making the semantics for this language without using evaluation contexts. There are two places we can expand sub-expressions, the operator and the operand of function application. So, including that with normal beta-reduction gives us:
(define red
  (reduction-relation
   Lv
   (--> (e_1 e_2)
        (v_1 e_2)
        (where v_1 ,(first (apply-reduction-relation red (term e_1)))))
   (--> (v_1 e_2)
        (v_1 v_2)
        (where v_2 ,(first (apply-reduction-relation red (term e_2)))))
   (--> ((λ (x) e) e_2)
        (substitute e x e_2))))

This isn't too bad, but remember that we have to add an additional rule for every place that a sub-expression can be evaluated. So let would need its own rule, if would need its own rule, etc. And remember that this is on top of the rules for each of these forms.
A much easier way to do this is just with evaluation contexts, which allows us to specify which expressions have sub-expressions that can take a step, and what order they should happen in. So let's try rewriting our Lv language with evaluation contexts:
(define-language Lv2
  (v (λ (x) e))
  (e v
     (e e))
  (x variable-not-otherwise-mentioned)
  (E hole
     (E e)
     (v E))
  #:binding-forms
  (λ (x) e #:refers-to x))

It's three lines longer now, but this tells redex that we'll be evaluating our expressions in an evaluation context, E, and when its done evaluating the expression, place it into the context (where hole is the top-level context so to speak). Thus, we can reduce our reduction relation down to just one rule, beta reduction:
(define red2
  (reduction-relation
   Lv2
   (--> (in-hole E ((λ (x) e) e_2))
        (in-hole E (substitute e x e_2)))))

Here we use in-hole to say that we are in a hole that follows E as shown above. This follows call by value semantics because holes can only appear from left to right in applications.
You can imagine that if you had a much larger calculi with many sub-expressions that this would save you from writing a very large amount of reduction rules.
So, to recap, you don't need to, it just makes your model much much shorter.


text:
Q: Scale image for canvas use in the browser I am building a website in which the user can upload an image, and edit it in a canvas. Right now this is my code:
Upload:
const handleChange = async e => {
    const {files} = e.target;
    const file = files[0];
    setImage(file);
};

<input id={'fileInput'} value={filePath}
   onChange={handleChange} type="file" accept=".jpeg, .jpg" capture="camera"/>

Taking the size:
componentDidMount() {
    const reader = new FileReader();
    reader.onload = async (e) => {
        const {result} = e.target;
        const {setEditedImage, setCanvasWidth, setCanvasHeight, setOriginalImage} = this.props;
        const image = document.getElementById('image');
        setOriginalImage(result);
        setEditedImage(result);
        if (image) {
            const {naturalHeight, naturalWidth} = image;
            setCanvasWidth(naturalWidth);
            setCanvasHeight(naturalHeight);
        }
    };
    try {
        reader.readAsDataURL(this.props.image);
    } catch (e) {
        console.log('caught', e);
    }
}

<img style={{display: 'block', width: '100%'}} id={'image'} src={this.props.originalImage} alt={''}/>

So here, I am taking the dataURL and putting it into the Redux state, along with the width and height.
Canvas:
componentWillReceiveProps(nextProps) {
    this.drawImage(nextProps.width, nextProps.height, nextProps.editedImage)
}

drawImage = (width, height, image) => {
    this.ctx = document.getElementById('canvas').getContext('2d');
    const img = new Image();
    img.onload = () => {
        this.ctx.drawImage(img, 0, 0, width, height);
    };
    img.src = image
};

handleClick = (e) => {
    const makeDrawing = (canvas) => {
        this.Draw(e.pageX - 305  - canvas.offsetLeft, e.pageY-100 - canvas.offsetTop);
    };
    const {textLength, tasks} = this.props;
    const canvas = document.getElementById('canvas');
    if (textLength === 'over200' || textLength === 'under200') {
        if (tasks !== 0) {
            return null;
        }
    }
    makeDrawing(canvas);
    this.props.setTasks(tasks + 1);

    const img = new Image();
    img.src = canvas.toDataURL();
    this.props.setImageURL(canvas.toDataURL());
    this.props.setEditedImage(img);
};

Draw = (x, y) => {
    this.ctx.beginPath();
    this.ctx.strokeStyle = 'red';
    this.ctx.lineWidth = 5;
    // x, y are the cords, 5 is the radius of the circle and the last 2 things specify full circle.
    this.ctx.arc(x, y, 5, 0, 2 * Math.PI);
    this.ctx.stroke();
    this.lastX = x;
    this.lastY = y;
};

<canvas onClick={this.handleClick} width={this.props.width} height={this.props.height} id={'canvas'}/>

The problem is this:

The smaller image on the top is the <ImageContainer/>. The one below is the <CanvasContainer/>. As you can see, even though I set the width to 100% of the modal, canvas ignores this and goes with the width and height found in the base image.
If I set the canvas width to 100% of the parent, it cuts part of the image of. How can I get the canvas to draw scaled images? Always having 100% of the parent's width?

A: I ended up just changing naturalHeight to offsetHeight and naturalWidth to offsetWidth


text:
Q: php - create ics file dynamically and email as attachment I need to create a calendar invite dynamically and email the ics file as an attachment. I'm using sendgrid to send emails.
This is my php script currently:
include("/Users/path/sendgrid-php.php");
$sendgrid = new SendGrid("uname", "pass");
$email    = new SendGrid\Email();

$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@test.com
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:New event
END:VEVENT
END:VCALENDAR";

header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=invite.ics');

$email->addTo("test@test.com")
    ->setFrom("test2@test2.com")
    ->setSubject("Test-Subject")
    ->setHtml("Test-Body")
    ->setAttachment($ical);

$sendgrid->send($email);

Now, whenever I run this script, instead of sending the ics file as an attachment to the email address provided, my browser automatically downloads the ics file, closes the page, and doesn't do anything (no email is sent).
Can you all please tell me where am I going wrong here? I've just started with PHP so chances are likely that I must have made some silly error.
Thanks.

A: The behavior you are seeing is being triggered by your header() calls.
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=invite.ics');

Those 2 lines are sending headers to the client browser and triggering the download.
In the SendGrid PHP examples I don't see them setting headers like that at all.


text:
Q: Enumerating Network Resources WNetOpenEnum returning ERROR_BAD_NETPATH(error 53) After a Long Time I am trying to get all the shared PCs using the code present at
http://msdn.microsoft.com/en-us/library/windows/desktop/aa385341(v=vs.85).aspx
The problem I am facing is that the method WNetOpenEnum is taking huge amount of time while opening "Microsoft Windows Network" resource and returning the error ERROR_BAD_NETPATH.
I have noticed that the Windows explorer is able to access the shared PCs and their folders.
I also have noticed that WNetConnectionDialog also working fine.
If I select Browse button,its able to refresh the net connections and able to see the shared PCs and their folders.
Strangely the code present works fine for Point to Point connection.

*

*Can some one help me in solving this issue?

*Also can some one suggest me how to refresh the shared resources using windows API?

*Are there any methods in QT/boost which can find shared PCS?


text:
Q: Problem with dates imported from Excel into R I have a date column in Microsoft Excel with dates in two different formats. Some dates have a year in the 1800s (e.g., 12/05/1888; whereas, all the other have a date after the 1900s (e.g., 3/6/59). I have thousands of dates.
I need to import the dates into R, but when I do each date is appearing as a five-digit number. My search of StackOverflow did not find a post that matched my situation.
When I format the column in Excel as "short date," here is what I see with the dates in the 1800s left-justified and the year shown as four digits in Excel and the dates after the 1800s right-justified with the year shown as two digits. Each date is on a separate line.
BIRTHDATE
12/05/1888
3/6/59
8/23/01
06/07/1888
11/19/77
6/23/52
07/09/1893
4/22/59
10/31/43
6/12/14
12/17/35
10/18/1869

When I convert the Excel column to text, here is what I see (each date is on a separate line):
BIRTHDATE
12/05/1888
21615
601
06/07/1888
28448
19168
07/09/1893
21662
16010
5277
13135
10/18/1869
17413

What can I do so that all the dates appear in correct date format in R?


text:
Q: how to call activity from inputmethodservice and get response I have a soft keyboard as a inputmethodservice calling an activity.  A button is pressed and a scanner is activated. The scanner activity captures a set of data then returns the data to the inputmethodservice for filling in a text field on a browser.
How do I return the scan value of the activity back to the inputmethodservice?
Thanks for any help.

A: You generally can't do this from a Service.  Because a Service is not an Activity, it can not receive results from an Activity, and thus does not have startActivityForResult().
In fact you probably don't want to do this.  Starting an activity is at best going to be a clunky experience -- a user doing input into a field doesn't really want to context switch out to another application's activity as part of their input.
Worse, this opens the door to a lot of ugly interactions.  For example, if they press home or use a notification or recent apps to switch to another application, what will happen to your activity?  Probably nothing good.
Instead I would recommend just showing a dialog as part of the IME -- use the Dialog class and set its window type to TYPE_INPUT_METHOD_DIALOG.  This will display on top of your IME, allowing you to interact with the user without disrupting the editing session.  For example, you'll want to set this dialog to not take input focus with FLAG_NOT_FOCUSABLE so the text editing session where the user is performing input is not disrupted.
And honestly the best thing to do is to have your UI incorporated into the IME itself.

A: Here is a code to test the solution using Dialog:
// 1. CREATE THE DIALOG
val builder: AlertDialog.Builder = AlertDialog.Builder(this, R.style.Theme_AppCompat_Light)
builder.setTitle("Title").setMessage("This is the message for the user. ")
val mDialog = builder.create()

// 2. SET THE IME WINDOW TOKEN ATTRIBUTE WITH THE TOKEN OF THE KEYBOARD VIEW
mDialog.window?.attributes?.token = this.mKeyboardView.windowToken

// 3. SET THE TYPE OF THE DIALOG TO TYPE_APPLICATION_ATTACHED_DIALOG
mDialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG)

// 4. SHOW THE DIALOG
mDialog.show()

A: What you want is startActivityForResult(yourIntent, SCAN_VALUE). Your IME will launch the activity, which will then return a value to the IME.
So your service will do something like the following:
Intent yourIntent = new Intent(this , YourActivity.class);
this.startActivityForResult(yourIntent, SCAN_VALUE);

Also in your Service, you'll have to call onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data)
  {
  switch(requestCode) {
  case SCAN_VALUE:
        if (resultCode == RESULT_OK) {

//TODO: Create some functionality here!

            break;
        }

Okay, so now let's tackle your launched activity. You'll have to modify this to fit your purposes, but here's how you would send a value back from, say, a ListAdapter. You didn't post your code, so it's tough to know exactly what you're doing.
  Object o = this.getListAdapter().getItem(position);
  String scanValue = o.toString();
  Intent returnIntent = new Intent();
  returnIntent.putExtra("ScanValue", scanValue);
  setResult(RESULT_OK,returnIntent);
  finish();

This will return a value to the IME launching the activity as a string. Again, if you post your code, I can give you more exact instructions. I hope this helps you wrap your mind around startActivityForResult() in the meantime, though.


text:
Q: How would I create and manage a .txt file with Terminal How would I create a .txt file, customize what it says, and open it. All with Terminal. [OSX Yosemite]

A: For personal use (ie, not in scripts) I recommend nano. A somewhat controversial choice among frequent terminal users, but unlike viand vim, nano isn't modal (ie, it's going to work the way you would expect a graphical text editor to work). Using nano will let you perform all three actions (create the file, edit the text, and view it) all with one command. Your syntax will be nano /path/to/file.txt. Of course, you can also use vi or vim, but if you choose to you definitely need to read about how first (if you're coming from a graphical background you've almost certainly never even heard of a modal editor before).
To create the file without opening the editor, use touch. This creates an empty file. The syntax would be touch /path/to/file.txt. If you need to make  a new folder to put the file in, use mkdir. The syntax is mkdir /path/to.
To view the file without opening the editor, use cat (syntax cat /path/to/file.txt) if it's short. This will just print the whole file to the terminal. If the file is longer, use less or more, which will each allow some navigation (eg, they'll let you scroll). By this point, you can probably guess the syntax. They're very similar commands: more or less, less is more, but more (less lets you scroll backward, more does not). Of course, you can also just look at the file in nano and then not write any changes.
Finally, if you cd into your working directory first, you can just refer to the file with its name without the path (eg, nano file.txt, and similar for the other commands I mentioned). It stands for "current directory" and the syntax is cd /path/to.
Hope this helps!

A: There are several text editors that come with terminal on OS X.  VI, emacs, and nano are probably the most well known.
Try running man nano, man vi, and man emacs or just googling those three items as well as 'OS X Terminal Text Editor' to learn more about them.
They will give you the ability to create files, name files, save files, and edit existing files.

A: Using Vim editor:
`vi text.txt` would create a file.
You may edit it and save it use `[Esc]:wq`

Using cat command:
cat > file.txt <<EOF
>some text
>to save
>EOF

Using redirection:
echo "Some text here." > file.txt


text:
Q: Best way to do a case insensitive replace but match the case of the word to be replaced? So far I've come up with the method below but my question is is there a shorter method out there that has the same result?
My Code :
input_str       = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
replace_str     = "stuff"
replacer_str    = "banana"

print input_str
# prints: myStrIngFullOfStUfFiWannAReplaCE_StUfFs

if replace_str.lower() in input_str.lower():            # Check if even in the string
    begin_index = input_str.lower().find( replace_str )
    end_index   = begin_index + len( replace_str )

    replace_section = input_str[ begin_index : end_index ]

    case_list = []
    for char in replace_section:                        # Get cases of characters in the section to be replaced
        case_list.append( char.istitle() )

    while len( replacer_str ) > len(case_list):
        case_list += case_list

    sameCase_replacer_str   = ""                        # Set match the replacer string's case to the replace
    replacer_str            = replacer_str.lower()
    for index in range( len(replacer_str) ):
        char = replacer_str[ index ]
        case = case_list[ index ]
        if case == True:
            char = char.title()

        sameCase_replacer_str += char

    input_str = input_str.replace( replace_section , sameCase_replacer_str )

print input_str
# prints: myStrIngFullOfBaNaNAiWannAReplaCE_BaNaNAs

A: I'd use something like this:
import re

def replacement_func(match, repl_pattern):
    match_str = match.group(0)
    repl = ''.join([r_char if m_char.islower() else r_char.upper()
                   for r_char, m_char in zip(repl_pattern, match_str)])
    repl += repl_pattern[len(match_str):]
    return repl

input_str = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
print re.sub('stuff',
             lambda m: replacement_func(m, 'banana'),
             input_str, flags=re.I)

Example output:

myStrIngFullOfBaNaNaiWannAReplaCE_BaNaNas

Notes:

*

*This handles the case in which the different matches have different upper/lower case combinations.

*It's assumed that the replacement pattern is in lower case (that's very easy to change, anyway).

*If the replacement pattern is longer than the match, the same case as in the pattern is used.

A: You can pass flags=re.I to re.sub() to ignore-case
>>> input_str       = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
>>> replace_str     = "stuff"
>>> replacer_str    = "banana"
>>>
>>> import re
>>> from itertools import zip_longest
>>> tr = lambda x, y: ''.join([i[0].upper() if i[1] else i[0].lower() for i in zip_longest(y, [c.isupper() for c in x], fillvalue=(lambda : '' if len(x)>len(y) else x[-1].isupper())())])
>>> re.sub(replace_str, lambda m: tr(m.group(0), replacer_str), input_str, flags=re.I)
'myStrIngFullOfBaNaNaiWannAReplaCE_BaNaNas'

A: From the code it's obvious that the case pattern for replacement is made from the match case pattern by repeating it over (so StufF -> BanaNA). Bearing this in mind I would first find case pattern for the whole string, and then bring the string to desired case:
def to_case(s, cmap):
    'returns string cased according to map'
    return ''.join([c.upper() if m else c for (c,m) in zip(s,cmap)])

input_str       = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
replace_str     = "stuff"
replacer_str    = "banana"

case_map = [c.istitle() for c in input_str] # initial case map
input_str_lower = input_str.lower()

while replace_str.lower() in input_str_lower:            # Check if even in the string
    ind = input_str_lower.find(replace_str)  # find index
    cases = [case_map[(ind + i % len(replace_str))] for i in range(len(replacer_str))] # replacement case pattern
    case_map = case_map[:ind] + cases + case_map[ind + len(replace_str):]
    input_str_lower = input_str_lower.replace(replace_str, replacer_str, 1)

print to_case(input_str_lower, case_map)
# prints: myStrIngFullOfBaNaNAiWannAReplaCE_BaNaNAs


text:
Q: Advance to next Column I am using the following code to edit some Data in an Excel File
Dim SF1 As Long
Dim EF1 As Long
Dim MaxRows As Long
SF1 = 2
MaxRows = Range("A1").End(xlDown).Row
EF1 = MaxRows

While SF1 <= MaxRows
If Range("D" & SF1) <> "" Then
    Range("A" & EF1).Value = Range("A" & SF1).Value
    Range("B" & EF1).Value = Range("B" & SF1).Value
    Range("C" & EF1).Value = Range("D" & SF1).Value
    SF1 = SF1 + 1
    EF1 = EF1 + 1
Else
    SF1 = SF1 + 1
End If
Wend
End Sub

However I would like to increment the column of D to E to...(ideally)ZZ after the MaxRows is reached. Can you provide me any input on this?
I tried something like this:
Dim SF1 As Long
Dim EF1 As Long
Dim MaxRows as Long
Column As String
SF1=2
MaxRows = Range("A1").End(xlDown).Row
EF1 = MaxRows
Col = "D"

While Col <>"ZZ"
    While SF1 <= MaxRows
        If Range("D" & SF1) <> "" Then
            Range("A" & EF1).Value = Range("A" & SF1).Value
            Range("B" & EF1).Value = Range("B" & SF1).Value
            Range("C" & EF1).Value = Range("D" & SF1).Value
            SF1 = SF1 + 1
            EF1 = EF1 + 1
        Else
            SF1 = SF1 + 1
        End If
    Wend
    Col = Col+1
Wend
End Sub

which doesn't work as this is not compatible (string and +1 as this is something for a number). So how can I advance the Column here especially taking into account that after Z AA follows in Excels column names.
Thanks for your help and Best regards!

A: Found the solution Code now looks as follows:
Dim SF1 As Long
Dim EF1 As Long
Dim MaxRows As Long
Dim ColNumber As Long
Dim ColLetter As String
Dim FinalColLetter As String
FinalColLetter = "BB"
ColNumber = 4
SF1 = 2
MaxRows = Range("A1").End(xlDown).Row
EF1 = MaxRows + 1

While ColNumber <= Range(FinalColLetter & 1).Column
    ColLetter = Split(Cells(1, ColNumber).Address, "$")(1)
        While SF1 <= MaxRows
            If Range(ColLetter & SF1) <> "" Then
                Range("A" & EF1).Value = Range("A" & SF1).Value
                Range("B" & EF1).Value = Range("B" & SF1).Value
                Range("C" & EF1).Value = Range(ColLetter & SF1).Value
                SF1 = SF1 + 1
                EF1 = EF1 + 1
            Else
                SF1 = SF1 + 1
        End If
        Wend
        SF1 = 2
    ColNumber = ColNumber + 1
Wend

Does what I need


text:
Q: How to print out multiple If Statement in Visual Basic I have been trying to display this if statement in my VB form application with no luck. Below is the code I have attempted.
 Dim iNumber1 As Double
    Dim iNumber2 As Double
    Dim iNumber3 As Double
    Dim iNumber4 As Double
    Dim iNumber5 As Double
    Dim iNumber6 As Double
    Dim iNumber7 As Double
    Dim iAns As Double
    Dim overall As Double

    iNumber1 = TextBox1.Text
    iNumber2 = TextBox2.Text
    iNumber3 = TextBox3.Text
    iNumber4 = TextBox7.Text
    iNumber5 = TextBox6.Text
    iNumber6 = TextBox5.Text
    iNumber7 = TextBox8.Text

    iAns = iNumber1 + iNumber2 + iNumber3 + iNumber4 + iNumber5 + iNumber6 + iNumber7
    overall = (Math.Round(Val(iAns / 7), 1))

    If iNumber1 <= 1.9 Then
        TextBox4.Text = $"Comprehension: {iNumber1} Entering"
    ElseIf iNumber1 >= 2.9 And iNumber1 >= 2 Then
        TextBox4.Text = $"Comprehension: {iNumber1} Emerging"
    ElseIf iNumber1 >= 3.9 And iNumber1 >= 3 Then
        TextBox4.Text = $"Comprehension: {iNumber1} Developing"
    ElseIf iNumber1 >= 4.9 And iNumber1 >= 4 Then
        TextBox4.Text = $"Comprehension: {iNumber1} Expanding"
    ElseIf iNumber1 >= 5.9 And iNumber1 >= 5 Then
        TextBox4.Text = $"Comprehension: {iNumber1} Bridging"
    ElseIf iNumber1 >= 6.9 And iNumber1 >= 6 Then
        TextBox4.Text = $"Comprehension: {iNumber1} Reaching"
    End If

Any suggestions on how to get this to come out? I am totally stuck. Thanks.


text:
Q: Package has no installation candidate I have an Ubuntu 15.04 and every time I try to download something (using sudo apt-get install), it says:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package <packagename> is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package '<packagename>' has no installation candidate

I have tried "sudo apt-get update" and it said at the end:
W: Failed to fetch http://ppa.launchpad.net/irie/blender/ubuntu/dists/vivid/main/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://ppa.launchpad.net/irie/blender/ubuntu/dists/vivid/main/binary-i386/Packages  404  Not Found

E: Some index files failed to download. They have been ignored, or old ones used instead.

I have also checked whether all of the checkboxes from "Ubuntu Software" tab of the "Software and Updates" window have been selected, and tried "sudo apt-get upgrade", but none of them worked.
Also, here is my sources.list file, which seems fine:
# deb cdrom:[Ubuntu 15.04 _Vivid Vervet_ - Release amd64 (20150422)]/ vivid main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://old-releases.ubuntu.com/ubuntu vivid main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://old-releases.ubuntu.com/ubuntu vivid-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://old-releases.ubuntu.com/ubuntu vivid universe
deb http://old-releases.ubuntu.com/ubuntu vivid-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://old-releases.ubuntu.com/ubuntu vivid multiverse
deb http://old-releases.ubuntu.com/ubuntu vivid-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://old-releases.ubuntu.com/ubuntu vivid-backports main restricted universe multiverse

deb http://old-releases.ubuntu.com/ubuntu vivid-security main restricted
deb http://old-releases.ubuntu.com/ubuntu vivid-security universe
deb http://old-releases.ubuntu.com/ubuntu vivid-security multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu vivid partner
# deb-src http://archive.canonical.com/ubuntu vivid partner
deb http://www.openprinting.org/download/printdriver/debian/ lsb3.2 contrib

Also, I know that there are other questions similar to this one, but none of the solutions worked for me.
Edit:
As I saw, many people in the comments suggested that I change the 'archives.ubuntu.com' lines in the sources.list to 'old-releases.ubuntu.com' because I have an outdated Ubuntu version. I tried that and the same message pops up when I type 'sudo apt-get update' (some index files failed to download), and when I try to install a package the same thing happens.
Some other people in the comments suggested that I upgrade to a newer Ubuntu version, which I tried also (sudo do-release-upgrade), but at the end it says:
Cannot upgrade, an upgrade from 'vivid' to 'xenial' is not supported with this tool.

I've also tried upgrading using sudo do-release upgrade -d, but then it says:
Checking for a new Ubuntu release
No new release found

A: I fixed it by myself. I followed a bunch of people in the comments' advice by replacing 'archives.ubuntu.com' links in the sources.list file with 'old-releases.ubuntu.com' and also deleted a bunch of out of date repositories that were preventing me from executing 'sudo apt-get update'.


text:
Q: how to set up AsyncStorage onPress in React-Natvie I have a problem I want to type in Input field and then hit button to set AsyncStorage. But actually what i have by this code is like this.
When i type AsyncStore is setting item and state is set also. How to make it to be set not when i type but when i hit button?
import React, { Component } from "react";
import { Text, View, TextInput, Button, StyleSheet } from "react-native";
import { AsyncStorage } from "react-native";
export class SetLocation extends Component {
  constructor() {
    super();
    this.state = {};
  }
  saveData = value => {
    AsyncStorage.setItem("myKey", value);
    this.setState({ myKey: value });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.saved}>{this.state.myKey}</Text>
        <View>
          <TextInput
            style={styles.formInput}
            onChangeText={text => this.saveData(text)}
          />
          <Button
            title="Learn More"
            color="#841584"
            accessibilityLabel="Learn more about this purple button"
          />
        </View>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    padding: 30,
    flex: 1,
    justifyContent: "center",
    alignItems: "stretch",
    backgroundColor: "#F5FCFF"
  },
  formInput: {
    height: 26,
    fontSize: 13,
    borderWidth: 1,
    borderColor: "#555555"
  },
  saved: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5,
    marginTop: 5
  }
});

export default SetLocation;

A: You should make use of onSubmitEditing and onPress for the Button to set value in AsyncStorage
As mentioned in the docs

onSubmitEditing:
  Callback that is called when the text input's submit button is pressed. Invalid if multiline={true} is specified.

setAsyncStorage = () => {
  AsyncStorage.setItem("myKey", this.state.myKey);
}

<TextInput
   style={styles.formInput}
   onChangeText={text => this.saveData(text)}
   onSubmitEditing={this.setAsyncStorage}
/>

<Button
   title="Learn More"
   color="#841584"
   accessibilityLabel="Learn more about this purple button"
   onPress={this.setAsyncStorage}
/>


text:
Q: Similarity between trees according to the number of common subtrees in Prolog I am studying Prolog for an universitary exame using SWI Prolog and I have some problems to understand what my teacher do in this example (it seems to me that is is incomplete) that implement the predicate:
k(T1,T2,N)

that is TRUE if T1 and T2 are trees and if they have if they have exactly N subtrees in common (a subtree is common between two trees T1 and T2 if this subtree exist both in T1 and in T2)
He give me another predicate T(t) where t is a specific tree and T(t) give me all the subtrees of t (if you want to see a graphical interpretation of this thing you can see the slide 18 of this file: http://www.informatica.uniroma2.it/upload/2012/LPDA/08_Lezione_ZNZ.pptx )
So he say that:
k(T1,T2,N)

is TRUE if is TRUE that:
In practice it is TRUE that the trees T1 and T2 have N common subtrees if it is TRUE that the intersection of the subtrees of T1 (give from the T(T1) predicate) and all subtress of T2 (give from the T(T2) predicate) is precisely N in module (ie as a number)
Ok, so go on: he define the trees in the following way:
tree(F, LIST_OF_SUBTREES).

where R is the root of the current tree
So go to implement the predicate k(T1,T2,N) that is TRUE if the trees T1 and T2 have N common subtrees, using the previous property.
This predicate have to use an EXAUSTIVE SEARCH of the subtrees in the trees T1 and T2
Then he implement the k/3 predicate in this way:
k(T1,T2,N) :- t(T1, ST1),
              t(T2, ST2),
              intersect(ST1,ST2,LST),
              lenght(LST,N).

This seems to me pretty clear (correct me if I'm wrong):

*

*t(T1,ST1) put in ST1 the list of all the subtrees contained in T1

*t(T2,ST2) put in ST2 the list of all the subtrees contained in T2

*intersect(ST1,ST2,LST) put in LST the list of the commons subtrees of ST1 and ST2

*lenght(LST,N) put in N the lenght of the commons subtrees of ST1 and ST2

So the predicate k(T1,T2,N) it is true if the calculated value of N unifies with the given N value.
Untill here I think that all is clear...bu now I have some problems to understand how he implement the **t(T,STL) predicate that take a tree T and put in STL the list of all its subtrees.
He give me the following code:
t(T,STL) :- bagof(ST, st(T,ST), STL).

st_r(tree(A,_), tree(A,[]).

st_r(tree(A,R), tree(A,R1) :- st_l(R,R1).

st_l([],[]).
st_l([X|R],[X1|R1]) :- st(X,X1),
                       st_l(R,R1).

st(T,T1) :- st_r(T,T1).

st(tree(A,R),T1) :- member(T,R),
                    st(T,T1).

Regarding the predicate:
t(T,STL) :- bagof(ST, st(T,ST), STL).

I think that simply execute the bagof built in predicate where ST is the subtree object that, if satisfy the goal st(T,ST) is put into the STL list (the list of subtree)
But now I am not understanding how the st/2 predicate (my goal) work !!! Someone can try to explain me the logic of this predicate and of the related st_l/2 and st_r/2 predicates?
And please, I have also some doubts about how to concretely build two trees that I can use to test this program. Can you give me two simple trees to use for the testing?
At last I think that, in this example, missing the intersect/3 predicate
Tnx
Andrea

A: Here the naming it's a bit cryptic, and I'll try to guess it.

*

*st/2 should stand for subtree, its purpose is to enumerate, on backtracking, all subtrees.

*st_r/2 should stand for subtree_root. It separately return the root and the leafs.

*st_l/2 then should stand for subtree_leafs. It makes a list of 'flattened' trees, replacing actual subtrees.

I would disagree that st/2 enumerates only subtrees. Actually, it returns more trees, because of the pruning performed by the first clause st_r. This seems an unusual definition to me - but nevertheless, it's a definition.
The predicate intersect/3 is defined in SWI-prolog library(lists) as intersection/3.
After two typo correction, that code gives to me
?- t(tree(x,[tree(u,[]),tree(v,[tree(p,[]),tree(q,[])])]),L).
L = [tree(x, []), tree(x, [tree(u, []), tree(v, [])]), tree(x, [tree(u, []), tree(v, [tree(p, []), tree(..., ...)])]), tree(x, [tree(u, []), tree(v, [tree(..., ...)|...])]), tree(x, [tree(u, []), tree(v, [...|...])]), tree(x, [tree(u, []), tree(..., ...)]), tree(x, [tree(..., ...)|...]), tree(x, [...|...]), tree(..., ...)|...].


text:
Q: Android 2.1: can't run HelloWorld on the Emulator I'm new in Android. I'm starting with HelloWorld program, but I can't run it on the Emulator. I'm using newest version of Eclipse and Android SDK. I also set up development environment as follows instructions on http://developer.android.com/index.html.
Does anybody have advice for me?

A: OMG!!! My problem is nothing :)) i must wait the emulator in a long time after that my program will be loaded. I watched a tutorial clip on YOUTUBE and i saw the boot screen of the emulator is as like as the emulator in my machine. Thanks all for help!

A: Do you get any errors?
if this is your first app, its probably to do with setup and enviroment. Whats your system spec?

I found running the install process - you have to make sure you follow the installation process in a good sequence. Eclipse, android platform. Java enviroment then ADT plugin.
the AVD Manager updater should have taken a long time to get everything you need when you run it.
If it failed - There is a little check box in the settings of the AVD manager that allows you to force download the HTTP -
But as long as you've got the lot, and your building a 2.1 file.
Also, the first time you run the emulator, it'll sit quiet for a worrying amount of time. Just make tea, watch TV - google kayden kross and it'll be fine.

A: Make sure you create an emulator image (AVD) or you won't be able to run it.

A: also for other newbies , just right click the project and say "debug as -> android" .