text:
Q: restrict addEventDelegate to parent hbox only This is a custom control created for my previous question Custom font for currency signs
I have two span elements coming next to each other. They sit in the FormattedText. The FormattedText itself sits in the HBox.
I want popover fired when user mouses over/out from the hbox. Unfortunately, as I have 2 spans this fires separately when user hovers overs them (thus showing 2 separate popovers, when in fact it should be one). My assumption is that this causes because onmouseover/out is attached to both spans under the hood. Can I restrict these events to hbox only?
sap.ui.define([
  'sap/ui/core/Control',
  'sap/m/FormattedText',
  'sap/m/HBox',
], function (Control, FormattedText, HBox) {

  return Control.extend('drex.control.TherapyCosts', {
    metadata: {
      properties: {
        rank: {
          type: 'int',
          defaultValue: 0
        },
      },
      aggregations: {
        _rankedTherapyCost: {type: 'sap.m.FormattedText', multiple: false, singularName: '_rankedTherapyCost'},
        _popover: {type: 'sap.m.Popover', multiple: false, singularName: '_popover'},
        _hbox: {type: 'sap.m.HBox', multiple: false}
      }
    },

    init: function () {
      Control.prototype.init.apply(this, arguments);
    },

    onBeforeRendering: function () {
      const highlighedCurrency = this.getCurrency().repeat(this.getRank());
      const fadedCurrency = this.getCurrency().repeat(7 - this.getRank());
      const _popover = new sap.m.Popover({
        showHeader: false,
        placement: 'VerticalPreferredBottom',
        content: new sap.m.Text({text: 'test'})
      });
      this.setAggregation('_popover', _popover);
      const _formattedText = new FormattedText({
        htmlText:
          `<span class="currencyHighlighted">${highlighedCurrency}</span>` +
          `<span class="currencyFaded">${fadedCurrency}</span>`
      });
      this.setAggregation('_rankedTherapyCost', _formattedText);
      const _hbox = new HBox(
        { items: [this.getAggregation('_rankedTherapyCost')]})
        .addEventDelegate({
          onmouseover: () => {
            this.getAggregation('_popover').openBy(this);
          },
          onmouseout: () => {
            this.getAggregation('_popover').close()
          }
        });
      this.setAggregation('_hbox', _hbox)
    },

    renderer: function (rm, oControl) {
      const _hbox = oControl.getAggregation('_hbox');
      rm.write('
');
      rm.renderControl(_hbox);
      rm.write('
');
    }
  });
});

Here is the video of the issue
https://streamable.com/fjw408

A: The key here is the mouseout event is triggered when the mouse moves out of any child element of the element that is listening for the event. In this case, for example, moving from the emphasised text to the faded text, you get a mouseout event when moving off the emphasised text, which closes the popup, then a mouseover event on the faded text which opens it again.
Since you opening an already open popup doesn't do anything, you only need add a line on mouseout to inspect the element that you've gone to. If it is not a child of the current element, only then close the popover.
if (!this.getDomRef().contains(e.toElement)) {
  popOver.close()
}

Building on D.Seah's answer, I've added this to the JSBin. I personally don't like using onBeforeRendering and onAfterRendering like this, so I've refactored a little to construct everything on init and simply change the controls on property change. This way, you're doing less on rendering for performance reasons.

sap.ui.define([
  'sap/ui/core/Control',
  'sap/m/FormattedText',
], function (Control, FormattedText) {

  Control.extend('TherapyCosts', {
    metadata: {
      properties: {
        rank: {
          type: 'int',
          defaultValue: 0
        },
        currency: {
          type: "string",
          defaultValue: "$"
        }
      },
      aggregations: {
        _highlighted: {type: 'sap.m.FormattedText', multiple: false},
        _faded: {type: 'sap.m.FormattedText', multiple: false},
        _popover: {type: 'sap.m.Popover', multiple: false, singularName: '_popover'}
      }
    },

    init: function () {
      Control.prototype.init.apply(this, arguments);
      this.addStyleClass('therapy-cost');

      const highlight = new FormattedText();
      highlight.addStyleClass("currency-highlight");
      this.setAggregation('_highlighted', highlight);

      const faded = new FormattedText();
      faded.addStyleClass("currency-faded");
      this.setAggregation('_faded', faded);

      const _popover = new sap.m.Popover({
        showHeader: false,
        placement: 'VerticalPreferredBottom',
        content: new sap.m.Text({text: 'test'})
      });
      this.setAggregation('_popover', _popover);
    },

    _changeAggr: function () {
      const highlighedCurrency = this.getCurrency().repeat(this.getRank());
      const highlight = this.getAggregation("_highlighted");
      highlight.setHtmlText(highlighedCurrency);

      const fadedCurrency = this.getCurrency().repeat(7 - this.getRank());
      const faded = this.getAggregation("_faded");
      faded.setHtmlText(fadedCurrency);
    },

    setRank: function(rank) {
       if (this.getProperty("rank") !== rank) {
         this.setProperty("rank", rank);
         this._changeAggr();
       }
    },

    setCurrency: function(curr) {
       if (this.getProperty("currency") !== curr) {
         this.setProperty("currency", curr);
         this._changeAggr();
       }
    },

    renderer: function (rm, oControl) {
      rm.write('
');
      rm.renderControl(oControl.getAggregation('_highlighted'));
      rm.renderControl(oControl.getAggregation('_faded'));
      rm.write('
');
    },

    onmouseover: function (e) {
      const popOver = this.getAggregation('_popover');
      popOver.openBy(this);
    },

    onmouseout: function (e) {
      if (!this.getDomRef().contains(e.toElement)) {
        const popOver = this.getAggregation('_popover');
        popOver.close();
      }
    }
  });
  (new TherapyCosts({
    rank: 5,
    currency: "£"
  })).placeAt('content')
});
.therapy-cost {
  display: inline-flex;
  flex-direction: row;
}

.therapy-cost .currency-highlighted {
  color: black;
}

.therapy-cost .currency-faded {
  color: lightgrey;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JS Bin</title>

https://jsbin.com/gukedamemu/3/edit?css,js,output

A: i think you can do without the hbox; by just having two formatted text or any sapui5 controls will be ok too.
sap.ui.define([
  'sap/ui/core/Control',
  'sap/m/FormattedText',
], function (Control, FormattedText) {

  Control.extend('TherapyCosts', {
    metadata: {
      properties: {
        rank: {
          type: 'int',
          defaultValue: 0
        },
        currency: {
          type: "string",
          defaultValue: "$"
        }
      },
      aggregations: {
        _highlighted: {type: 'sap.m.FormattedText', multiple: false},
        _faded: {type: 'sap.m.FormattedText', multiple: false},
        _popover: {type: 'sap.m.Popover', multiple: false, singularName: '_popover'}
      }
    },

    init: function () {
      Control.prototype.init.apply(this, arguments);
      this.addStyleClass('therapy-cost')
    },

    onBeforeRendering: function () {
      const highlighedCurrency = this.getCurrency().repeat(this.getRank());
      const highlight = new FormattedText({
        htmlText: highlighedCurrency
      });
      this.setAggregation('_highlighted', highlight);

      const fadedCurrency = this.getCurrency().repeat(7 - this.getRank());
      const faded = new FormattedText({
        htmlText: fadedCurrency
      });
      this.setAggregation('_faded', faded);

      const _popover = new sap.m.Popover({
        showHeader: false,
        placement: 'VerticalPreferredBottom',
        content: new sap.m.Text({text: 'test'})
      });
      this.setAggregation('_popover', _popover);
    },

    renderer: function (rm, oControl) {
      rm.write('
');
      rm.renderControl(oControl.getAggregation('_highlighted'));
      rm.renderControl(oControl.getAggregation('_faded'));
      rm.write('
');
    },
    onAfterRendering: function () {
      const popOver = this.getAggregation('_popover');
      const highlighted = this.getAggregation("_highlighted");
      highlighted.$().addClass("currency-highlighted");
      highlighted.$().hover(function() {
        popOver.openBy(highlighted);
      }, function() {
        popOver.close();
      });
      const faded = this.getAggregation("_faded");
      faded.$().addClass("currency-faded");
    },
  });
  (new TherapyCosts({
    rank: 5
  })).placeAt('content')
});

https://jsbin.com/razebuq/edit?css,js,output


text:
Q: combobox event & clear method    private void ComboBox1_TextChanged(object sender, EventArgs e)
    {
        ComboBox1.Items.Clear();
        XmlNodeList node_lst = doc["paths"].ChildNodes;
        foreach (XmlNode item in node_lst)
        {
            if (item.InnerText.Contains(ComboBox1.Text))
            {
                ComboBox1.Items.Add(item.InnerText);
            }
        }
    }

I am new in this website, i have question in this event when I clear items from combobox, I get these items from an xml file; my problem is when I  enter letters in combobox text, the text is entered in inversed way, I expected that the problem in clear method but i have not idea how to do this.
Thanks.

A: When you delete all items from the ComboBox the cursor will be set to the first position., So after each character that you type the cursor will be shifted to the left and you get the feeling of typing from right to left.
The solution would be to set the SelectionStart after the for-loop by hand to the end of the Text:
comboBox1.SelectionStart = comboBox1.Text.Length;

A: I guess you want something like this:
var nodeList = node_lst.Cast<XmlNode>()
                               .Select(x => library.GetMemberName(int.Parse(x.InnerText)))
                               .ToList();
nodeList.Reverse();

More info on Reverse(): https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sum results of drop down list in Excel I am using drop-down lists for the observation, self-practice, and teaching tabs, and I would like to total the amount of time in column J. Is there a formula that will allow me to do this?

A: The solution is very simple if the cells only contain numbers and no other characters. If this were the case the following formula would go in cell J2 and could be copied drug down automatically updating all the row references for the current row total:
=SUM(G2:I2)
This is the typical way Excel is used, one idea per cell. The labels and units are specified elsewhere, such as column headings.
However, in the stated problem, a formula is needed to isolate the number in the text. To reduce the complexity, we'll assume the number is before any other characters (leading spaces are ok). We will further assume there is at least one space between the number and any following character(s).
This solution allows for empty cells, leading spaces, multiple spaces and a number by itself (or with just spaces before and/or after the number).
=IFERROR( NUMBERVALUE( LEFT( TRIM(F2) & " ", FIND( " ", TRIM(F2) & " " ) - 1)), 0) + IFERROR( NUMBERVALUE( LEFT( TRIM(G2) & " ", FIND( " ", TRIM(G2) & " ") - 1)) ,0) + IFERROR( NUMBERVALUE( LEFT( TRIM(H2) & " ", FIND( " ", TRIM(H2) & " ") -1 )), 0)
Very convoluted, right?!
Here is a slightly more compact version but it is a special formula called an array formula. After pasting it into the cell, perform a special Enter key combination to make it an array formula. Otherwise Excel may say something is wrong with the formula or the results may be incorrect.
=SUM( IFERROR( NUMBERVALUE( LEFT( TRIM(F2:H2) & " ", FIND( " ", TRIM(F2:H2) & " " ) - 1)), 0))
Once the formula is pasted into the cell, make it an array formula by pressing Ctrl-Shift-Enter. This is sometimes referred to by the acronym for this key press combination CSE (Control Shift Enter).
Everytime an array formula is edited, press CSE.


text:
Q: How to set up a DLNA server on Ubuntu 14.04? I've tried a few DLNA servers (including MiniDLNA, uShare, MediaTomb, Rygel), but none of these works as expected. The problem with MiniDLNA is that most of the shared content simply didn't appear on the TVs list or  if they appeared the TV couldn't play them (unsupported or unregistered format). uShare didn't want to work. First i runned it manually using the screen ushare -c /mnt/Films/ --content /mnt/Music/ --content /home/savanweylyn/Képek, and it was working well. After i configured it with sudo dpkg --reconfigure ushare, it suddenly stopped working. The error message on the TV was 'no media detected'. MediaTomb was removed pretty fast, because it was hard to configure and the TV didn't even detect it. And finally: Rygel. I absolutely don't know how to configure it.
So please could you tell me an easy-to-use DLNA server for a GUIless server?

A: The simple way is to use MiniDLNA, because it should be on Ubuntu repositories and it is a simple tool.
You can try all DLNA apps and still your TV is not going to run some file types. You need to check what type of files your capable DLNA TV support.
I recommend you to check the Community Wiki entry on how to configure MiniDLNA or watch an instructional video. Very simple and straight forward.
For MiniDLNA follow these steps:

*

*Install MiniDLNA
sudo apt-get install minidlna

*Edit configuration file
gksu gedit /etc/minidlna.conf

*Add the following text to the file. Replace the folders name by the ones you use. You can just use one type if you want.
inotify=yes
media_dir=P,/home/user/Pictures
media_dir=V,/home/user/Videos
media_dir=A,/home/user/Music
media_dir=/home/user/Videos
friendly_name=UbuntuDLNA

*Then restart the service to apply changes
sudo service minidlna restart

*Make sure the file list is rebuild
sudo service minidlna force-reload

A: Well, how about trying Universal Media Server, a fork of former PMS server, and see how it goes.. comes with a free web interface and a pretty adequate help support as well. Had it in 14.04 64 bit, worked like a charm to like almost 95% of video formats tested to a Panasonic Tv, and 99% to a Samsung.

A: Here's a list of the gotchas that I came across and overcame when working with a couple of DLNA servers and clients. Keeping the below list in mind, I no longer have issues viewing my files.
The following affect media visible to clients:

*

*FILENAME EXTENSIONS:
The DLNA client should indicate which types of
media they support (i.e., read their help menu and/or manual). For
example, one player might understand m4v and mp4 extensions (e.g.,
PlayStation), while another only understands mp4 (Roku), even though
the file is encoded the same for either extension. Thus, you might
have to change the filename (e.g., to mp4 for Roku) or just create a
symbolic-link to the (m4v) file and name the symbolic-link with the
correct extension (mp4).
Another example, this time on the audio side, my Roku will play
lossless "flac" files, but my PS3 won't and requires "wav", instead.

*

*REBOOT SERVER:
I've not needed this for minidlna, but I did have an
ASUS router that had a built-in DLNA server. Restarting the service
was usually enough, but on occasion I even had to reboot the router,
followed by toggle the DLNA service. (This is why I switched to
minidlna.)

*

*REBOOT CLIENTS:
Some DLNA clients (PlayStation 3) may need rebooting
to see the DLNA server and/or changes in media on the
server-side. (Yes, weird, but true.)

*

*PERMISSIONS:
Ensure path and filename on media server are accessible
to server user (e.g., "minidlna"). Just because you enter the path
into /etc/minidlna.conf doesn't make it magically work if user
"minidlna" cannot traverse the path ALL THE WAY to the files'
directory, including ensuring having file-level access.
This means, directories not owned by minidlna but needing to be traversed can be set to NOT allow read/write by others (minidlna) but ALLOW traversing ONLY:
chmod o+x-rw /home/myUserName/

Directories that CAN be browsed by the public (minidlna) are set readable:
chmod o+rx-w /home/myUserName/videos/

And finally, all files/folders are recursively set publically readable inside "videos":
find /home/myUserName/videos/ -type d ! -perm 0775 -exec chmod -v 0775 {} \;
find /home/myUserName/videos/ -type f ! -perm 0444 -exec chmod -v 0444 {} \;

*

*CONVERT MEDIA NOT SUPPORTED:
I had a bunch of AVI files (as well as other formats) that my Roku wouldn't display. With "handbrake" I can pretty much convert my media to MP4 files. I also use command-line tool ffmpeg for either video or audio conversions, although ffmpeg doesn't always convert my AVI-to-MP4 files successfully.

*

*RESTART SERVICE AND REBUILD DATABASE:
After all is said and done:
sudo service minidlna restart
sudo service minidlna force-reload

NOTE: It also helps to have "inotify=yes" in /etc/minidlna.conf to ensure "Automatic discovery of new files in the media_dir directory."

A: You have to understand what the different media apps do.
MiniDLNA only serves up teh files, no conversion, so the file types and formats must meat the playing devices requirements. Not all MP3's for instance are the same, some many encoding schemes, bit rates and types. So all files should be the same type, format etc to meet all players requirements.
You can use one of the media server apps that has conversion so no matter the audio format will convert to the players format. However this takes a good bit of processing so best to have a good speedy computer.

A: The functionality is built-in to Ubuntu since 19.10. Just go to Settings → Sharing and enable Media sharing.
Ref: https://www.omgubuntu.co.uk/2019/10/ubuntu-dlna-media-sharing-server


text:
Q: How to get UTC time based on a DateTime and a TimeZone Offset? I have a datetime object, and I know the UTC offset (double).  How can I get UTC time from these two pieces of information?
All of the examples I've seen require a timezone.  Well, I don't know what timezone is, and it shouldn't really matter.  If i have an offset of -7, it could either be PDT, or it could be MST - it's really irrelevant as either would produce the same UTC.  It seems really stupid that I have to convert the offset that I have to a timezone just so the "ToUniversalTime" can pull the offset back out.
Honestly, I'm about to resort to just using something like this:
DateTime dateTime = new DateTime(2014, 8, 6, 12, 0, 0);
Double timeZone = -7.0;
string utc = String.Format("{0}-{1}-{2}T{3}:{4}:{5}{6}:{7}", startDate.Year, startDate.Month, startDate.Day, startDate.Hour, startDate.Minute, startDate.Second, (int) Math.Floor(timeZone), (timeZone % 1) * 60);

can someone please tell me why this is a bad idea?
(someone will probably close this as a duplicate, but I looked at a dozen other questions and none of them were quite the same - they all used the TimeZoneInfo object).

A: Just use DateTimeOffset:
TimeSpan utcOffset = TimeSpan.FromHours(timeZone);
DateTimeOffset result = new DateTimeOffset(dateTime, utcOffset);
DateTime utc = result.UtcDateTime;

or
string utc = result.ToString("yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);

It's not clear why you want it as a string in the end though...
(You might also want to consider using my Noda Time project, particularly as you're likely to see time zone IDs which are TZDB time zones...)


text:
Q: Windows 10-kernel security check error when i unplug usb or plug in an usb I recently updated to windows 10 and I've been getting these crashes alot when i plug in or unplug an usb or sometimes even randomly just crashes and gives me the kernel security check error message.
https://onedrive.live.com/?id=root&cid=23CDE74496897CDE
Here is the dump file


text:
Q: How to append or prepend an element to a tuple in Scala I have a tuple and want to add an element without loosing type safety. This is what I want to achieve:
val tuple = ("", 1, 1f) // (String, Int, Float)

val newTuple:(String, Int, Float, Double) = tuple :+ 1d

A: I found a solution with the help of the awesome Shapeless library and it's HList
/*
  Define an implicit class to add the methods
  It accepts any tuple as we have typed it as Product
*/
implicit class TupleOps[A <: Product](t: A) {

  /*
    Declare the method to append

    B - The type of element we want to append
    L - The HList representing the tuple A
    P - The HList after appending B
    R - The final result
  */
  def :+[B, L <: HList, P <: HList, R <: Product](b: B)(
    /*
      We need some tools to help with the conversion

      hlister - Converts a tuple into an HList
      prepend - Can prepend one HList before another
      tupler  - Can convert an HList into a tuple
    */
    implicit hlister: HListerAux[A, L], prepend: PrependAux[L, B :: HNil, P], tupler: TuplerAux[P, R]):R =
      // Let the helpers do their job
      tupler(prepend(hlister(t), b :: HNil))

  /*
    The prepend method is similar to the append method but does not require
    the extra effort to append
  */
  def +:[B, L <: HList, R <: Product](b: B)(
    // Here we use the :: type of shapeless
    implicit hlister: HListerAux[A, L], tupler: TuplerAux[B :: L, R]):R =
      tupler(b :: hlister(t))
}

// usage is like this
("", 1, 1f) :+ 1d  //> res0: (String, Int, Float, Double) = ("",1,1.0,1.0)
1d +: ("", 1, 1f)  //> res1: (Double, String, Int, Float) = (1.0,"",1,1.0)

Edit
In some cases, where you need to deal with implicit conversions this solution will not work in combination with case classes. I now reverted to the following implementation (based on the code of Rex Kerr)
def char(n: Int) = ('A' + n).toChar
def prop(n: Int) = "t._" + (n + 1)

val result =
  for (n <- 1 to 21) yield {

    val range = (0 until n)
    val tupleTypeParams = range map char mkString ", "
    val tupleProperties = range map prop mkString ", "

    val elementType = char(n)
    val elementProperty = prop(n)

    val first = n == 1
    val tupleType = if (first) s"Tuple1[$tupleTypeParams]" else s"($tupleTypeParams)"
    val tupleInstance = if (first) s"Tuple1($tupleProperties)" else s"($tupleProperties)"

    val resultType = s"($tupleTypeParams, $elementType)"

    s"""|implicit def tupleOps$n[$tupleTypeParams, $elementType] =
        |  new TupleAppendOps[$tupleType, $elementType, $resultType] {
        |    def append(t: $tupleType, e: $elementType) = ($tupleProperties, e)
        |    def init(t: $resultType) = $tupleInstance
        |    def last(t: $resultType) = $elementProperty
        |  }""".stripMargin
  }

println(result mkString "\n")

A: You can try my experimental macros library based on macro paradise scala branch at https://github.com/leonardschneider/macrogen which does exactly your example.
Right now I still have some bugs though, where I can not chain the calls.

A: Shapeless now does it. Adding
import shapeless.syntax.std.tuple._

before your code just compiles.

A: It's worth noting that you can also write a code generator for this in a few lines:
val tupadd = for (n <- 2 to 20) yield {
  val t = (0 until n).map(i => ('A'+i).toChar).mkString(", ")
  val u = ('A'+n).toChar
  val i = (0 until n).map(i => "x._"+(i+1)).mkString(", ")
  List(
    s"implicit class TupOps$n[$t](val x: ($t)) extends AnyVal {",
    s"  def :+[$u](y: $u) = ($i, y)",
    s"  def +:[$u](y: $u) = (y, $i)",
    "}"
  ).mkString("\n")
}

Print these out, stick 'em in a file, and you're good to go:
scala> implicit class TupOps2[A, B](val x: (A, B)) extends AnyVal {
     |   def :+[C](y: C) = (x._1, x._2, y)
     |   def +:[C](y: C) = (y, x._1, x._2)
     | }
defined class TupOps2

scala> (1,"salmon") :+ true
res15: (Int, String, Boolean) = (1,salmon,true)


text:
Q: Flaks REST api starting with Gunicorn giving inconsistent number instance Below is command to start Flask Api using gunicorn
gunicorn -w 2 --bind ip:port dashboardApi:app  > logs/ui-backend-$logdate.log

But when starting this only one master and 2 workers should be running, instead its running 1 master , 2 worker and addition workers work work istelf
 gunicorn(29066)─┬─gunicorn(184076)─┬─{gunicorn}(184159)
            │                  ├─{gunicorn}(184160)
            │                  ├─{gunicorn}(184161)
            │                  ├─{gunicorn}(184162)
            │                  ├─{gunicorn}(184163)
            │                  ├─{gunicorn}(184164)
            │                  ├─{gunicorn}(184165)
            │                  ├─{gunicorn}(184166)
            │                  ├─{gunicorn}(184167)
            │                  ├─{gunicorn}(184168)
            │                  ├─{gunicorn}(184169)
            │                  ├─{gunicorn}(184170)
            │                  ├─{gunicorn}(184171)
            │                  ├─{gunicorn}(184172)
            │                  ├─{gunicorn}(184173)
            │                  ├─{gunicorn}(184174)
            │                  ├─{gunicorn}(184175)
            │                  ├─{gunicorn}(184176)
            │                  ├─{gunicorn}(184177)
            │                  ├─{gunicorn}(184178)
            │                  ├─{gunicorn}(184179)
            │                  ├─{gunicorn}(184180)
            │                  ├─{gunicorn}(184181)
            │                  ├─{gunicorn}(184182)
            │                  ├─{gunicorn}(184183)
            │                  ├─{gunicorn}(184184)
            │                  ├─{gunicorn}(184185)
            │                  ├─{gunicorn}(184186)
            │                  ├─{gunicorn}(184187)
            │                  ├─{gunicorn}(184188)
            │                  ├─{gunicorn}(184189)
            │                  ├─{gunicorn}(184190)
            │                  ├─{gunicorn}(184191)
            │                  ├─{gunicorn}(184192)
            │                  ├─{gunicorn}(184193)
            │                  ├─{gunicorn}(184194)
            │                  ├─{gunicorn}(184195)
            │                  ├─{gunicorn}(184196)
            │                  ├─{gunicorn}(184197)
            │                  ├─{gunicorn}(184198)
            │                  ├─{gunicorn}(184199)
            │                  ├─{gunicorn}(184200)
            │                  ├─{gunicorn}(184201)
            │                  ├─{gunicorn}(184202)
            │                  ├─{gunicorn}(184203)
            │                  ├─{gunicorn}(184204)
            │                  └─{gunicorn}(184205)
            └─gunicorn(199762)─┬─{gunicorn}(199764)
                               ├─{gunicorn}(199765)
                               ├─{gunicorn}(199766)
                               ├─{gunicorn}(199767)
                               ├─{gunicorn}(199768)
                               ├─{gunicorn}(199769)
                               ├─{gunicorn}(199770)
                               ├─{gunicorn}(199771)
                               ├─{gunicorn}(199772)
                               ├─{gunicorn}(199773)
                               ├─{gunicorn}(199774)
                               ├─{gunicorn}(199775)
                               ├─{gunicorn}(199776)
                               ├─{gunicorn}(199777)
                               ├─{gunicorn}(199778)
                               ├─{gunicorn}(199779)
                               ├─{gunicorn}(199780)
                               ├─{gunicorn}(199781)
                               ├─{gunicorn}(199782)
                               ├─{gunicorn}(199783)
                               ├─{gunicorn}(199784)
                               ├─{gunicorn}(199785)
                               ├─{gunicorn}(199786)
                               ├─{gunicorn}(199787)
                               ├─{gunicorn}(199788)
                               ├─{gunicorn}(199789)
                               ├─{gunicorn}(199790)
                               ├─{gunicorn}(199791)
                               ├─{gunicorn}(199792)
                               ├─{gunicorn}(199793)
                               ├─{gunicorn}(199794)
                               ├─{gunicorn}(199795)
                               ├─{gunicorn}(199796)
                               ├─{gunicorn}(199797)
                               ├─{gunicorn}(199798)
                               ├─{gunicorn}(199799)
                               ├─{gunicorn}(199800)
                               ├─{gunicorn}(199801)
                               ├─{gunicorn}(199802)
                               ├─{gunicorn}(199803)
                               ├─{gunicorn}(199804)
                               ├─{gunicorn}(199805)
                               ├─{gunicorn}(199806)
                               ├─{gunicorn}(199807)
                               ├─{gunicorn}(199808)
                               ├─{gunicorn}(199809)
                               └─{gunicorn}(199810)

This is what iam getting from pstree -p of master pid
Is this normal, and why ..?
gunicorn(191765)─┬─gunicorn(191770)
             ├─gunicorn(191771)
             ├─gunicorn(298499)
             └─gunicorn(304711)

Above is the pstree -p output of, another falsk api which is running with only 4 worker, which is looking fine.


text:
Q: High Firebase Downloads I have a React Native app that has 2k users. All user data is stored in Firebase in the following format:

So each user has a list of Fasts, where they generally create one fast per day. A very small amount of data. This is what my Database Usage graph looks like:

Some observations:

*

*On the 27th, 134MB was downloaded. The total database size is .5MB. 134MB/.5MB = 268 times that the entire database was downloaded. This means each user would have downloaded their data 268 times, which is highly unlikely. My Firebase rules:

So it's not possible users are downloading other users' data.
I ran Firebase Profiler for ~11 mins:

I'm stumped. Finally, here's my one file that does almost every Firebase operation besides logging in/out:
import * as firebase from 'firebase';
import moment from 'moment'
import {
  currentFastChanged,
  setGraphData,
  setAllData,
  targetFastChanged,
  setLastFastEnd,
usernameChanged,} from '../actions/actions'
// Initialize Firebase
var firebaseConfig = {
};
export const firebaseApp = firebase.initializeApp(firebaseConfig);

function syncFirebase(store) {

  firebaseApp.auth().onAuthStateChanged(function(user) {
    if (user)
    {
      getUserRef().child('TargetFast').on('value', (snap) => {
        store.dispatch(targetFastChanged(snap.val() ? snap.val() : 15));
      });

      getUserRef().child('Fasts').on('value', (snap) => {
        var items = [];
        snap.forEach((child) => {
          items.push({
            start: child.val().Start,
            end: child.val().End,
            _key: child.key
          });
        });

        items.sort(function(a, b) {
           return parseInt(b.start) - parseInt(a.start);
       });
       store.dispatch(setGraphData(createGraphData(items, store.getState().myReducer.targetFast)));
       store.dispatch(setLastFastEnd(getLastFastEnd(items)));
       store.dispatch(setAllData(items));
     });

     getUserRef().child('CurrentFast').on('value', (snapshot) => {
       store.dispatch(currentFastChanged(snapshot.val()));
     });

   });

    }
  })

}

function getUserRef()
{
  return firebaseApp.database().ref('Users/' + firebaseApp.auth().currentUser.uid);
}

function createGraphData(items, targetFast) {

 var graphItems = [];
 var idx = 0;
 for(idx = 0; idx < 7 && idx < items.length; idx++)
 {
   var item = items[idx];
   graphItems.push({
     duration : moment.duration(item.end - item.start).asHours(),
     label : moment(item.start).format('ddd'),
     item : item
   });
 }

 while(graphItems.length < 7)
 {
   var add = targetFast * .2 * (Math.random() - .5);
   var randomVal = targetFast + add
   graphItems.push({duration : randomVal, label : "na", color : 'lightgrey', });
 }
  return graphItems.reverse();
}

function getLastFastEnd(items) {
  return items.length && items[0].end;
}

export function setCurrentFastRef(val)
{
  getUserRef().child('CurrentFast').set(val);
  //firebaseApp.database().ref('Users/' + firebaseApp.auth().currentUser.uid + '/CurrentFast').set(val);
}

export function pushNewFast(start, end)
{
  getUserRef().child('Fasts').push({'Start': start, 'End': end, 'Publish' : true})
}

export function editFastRef(key, start, end)
{
  getUserRef().child('Fasts').child(key).set({'Start' : start, 'End' : end});
}

export function deleteFastRef(key)
{
  getUserRef().child('Fasts').child(key).remove();
}

export function setTargetFastRef(val)
{
  getUserRef().child('TargetFast').set(val);
}

module.exports = firebaseApp;
module.exports.sync = syncFirebase;
module.exports.serverTimestamp = firebase.database.ServerValue.TIMESTAMP

My bill is already at $1 for about 15 days for what seems like a trivial amount of data. My current suspicions are:

*

*Listeners are just stacking up and downloading data many times. The listeners aren't being deleted

*Overhead that's not my fault (SSL?)

*??? Any ideas?


text:
Q: What does Interpretation by Vikram Seth mean? In the poetry collection All You Who Sleep Tonight by Vikram Seth, is this four-line poem entitled Interpretation:

Somewhere within your loving look I sense,
Without the least intention to deceive,
Without suspicion, without evidence,
Somewhere within your heart the heart to leave.

What is the meaning of this poem?

A: English has a number of tropes to convey the emotion of love by bodily description.  One of these is to place the seat of emotion in the heart.  You "give your heart" to a lover, and the one you love "breaks your heart" by spurning you.  Other descriptions use the senses, e.g., "the look of love."  For instance, consider the lyrics to the song of the same name:

The look of love is in your eyes
  The look, your smile can't disguise
  The look of love, it's saying so much more
  Than just words could ever say
  And what my heart has heard, well it
  takes my breath away

Here the beloved conveys the emotion of her love by seeing him in a certain way, a way that he, in turn, can see for himself.  (Notice that the heart is here too, a heart that can hear.)
Let's examine just the first and last lines of the poem:

Somewhere within your loving look I sense,
  ...
  Somewhere within your heart the heart to leave.

The insecure lover sees that look of love, but he detects somehow that she might leave him anyway.  Heart not only metaphorically conveys the feeling of love, but also strength and courage.  In other words, the wherewithal to leave him.
Now, the second line:

Without the least intention to deceive,

The insecure lover isn't making an accusation of deceit; he doesn't think his beloved is concealing her desire to leave.
And the third line:

Without suspicion, without evidence,

The insecure lover isn't made suspicious by any actual evidence he can cite, but in spite of that he knows somehow that his beloved is capable of throwing him over.
(The gender of my pronouns is heterosexist for convenience.  Feel free to transpose them to any other relationships.)

A: He is able to perceive her latent desire to leave after all, despite absence of such physical manifestations.


text:
Q: How do I add a WebView2 control to a CDialog resource in a MFC project? I have been able to download and build the sample projects from Microsoft. I can run the Win32 project and it displays a WebView2 object in the View and appears functional.
For my situation I want to use a CDialog as the parent for the WebView2 control and I can't work out how to do this. When I follow the instructions here it is based on a View style object. In the instructions it says:

Step 3 - Create a single WebView within the parent window
Add a WebView to the main window.

I get lost here and don't knwo how to add the control to my basic CDialog project.
Thank you for your direction on how to deal with this.

A: This alternative tutorial helped me. I downloaded the sample project, compiled it and it worked. Again, it was based on a application derived from a CView. However, I have managed to work out the principles required.
No doubt more will be involved as I continue to tweak the test application I am making.

*

*Create a dialog based application using boiler place code.

*Set the C++ Language Standard to ISO C++ 17.

*Install two NuGet packages:

*

*Microsoft.Web.WebView2 NuGet package

*Microsoft.Windows.ImplementationLibrary NuGet package

*Change InitInstance to use CoInitialize.

*Add the ExitInstance handler and call UnCoinitialize.

For testing purposes I simply used the dimensions of my dialog. Begin by adding a variable to your dialog class:
std::unique_ptr<CWebBrowser> m_pWebBrowser;

Then, in OnInitDialog you can do something like this:
m_pWebBrowser = std::make_unique<CWebBrowser>();

if (m_pWebBrowser != nullptr)
{
    CRect rectClient;
    GetClientRect(rectClient);

    m_pWebBrowser->CreateAsync(
        WS_VISIBLE | WS_CHILD,
        rectClient,
        this,
        1,
        [this]() {
            m_pWebBrowser->SetParent(this);
            m_pWebBrowser->DisablePopups();
            m_pWebBrowser->Navigate(L"https://jw.org", nullptr);

            m_pWebBrowser->RegisterCallback(CWebBrowser::CallbackType::TitleChanged, [this]() {
                CString title = m_pWebBrowser->GetTitle();

                AfxGetMainWnd()->SetWindowText(title);
                });
        });
}

For the test, I also added the OnSize handler:
void CMFCTestWebView2Dlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);

    CRect rectClient;

    if (m_pWebBrowser != nullptr)
    {
        m_staticBrowser.GetClientRect(rectClient);
        m_staticBrowser.ClientToScreen(rectClient);
        ScreenToClient(rectClient);

        m_pWebBrowser->Resize(rectClient.Width(), rectClient.Height());
    }

}

The heart of this is the CWebBrowser class. This is available in the linked tutorial and all I did was adjust the SetParentView method so that it accepted a CWnd pointer instead.
Oh, and you add DestroyWindow to the dialog class:
BOOL CMFCTestWebView2Dlg::DestroyWindow()
{
    m_pWebBrowser.reset();

    return CDialogEx::DestroyWindow();
}

CWebBrowser Header
#pragma once

#include <EventToken.h>
#include <functional>
#include <map>

struct ICoreWebView2Environment;
struct ICoreWebView2Controller;

struct CWebBrowserImpl;
class CView;

class CWebBrowser : public CWnd
{
public:
   enum class CallbackType
   {
      CreationCompleted,
      NavigationCompleted,
      TitleChanged,
   };

   using CallbackFunc = std::function<void()>;

public:
   CWebBrowser();
   virtual ~CWebBrowser();

   virtual BOOL Create(
      LPCTSTR lpszClassName,
      LPCTSTR lpszWindowName,
      DWORD dwStyle,
      const RECT& rect,
      CWnd* pParentWnd,
      UINT nID,
      CCreateContext* = NULL) override;

   BOOL CreateAsync(
      DWORD dwStyle,
      const RECT& rect,
      CWnd* pParentWnd,
      UINT nID,
      CallbackFunc onCreated);

   void RegisterCallback(CallbackType const type, CallbackFunc callback);

   RECT GetBounds();
   void SetBounds(LONG const width, LONG const height) { Resize(width, height); }
   void Resize(LONG const width, LONG const height);

   CString GetLocationURL();

   void Navigate(CString const & url, CallbackFunc onComplete);
   void NavigatePost(CString const& url, CString const& content, CString const& headers, CallbackFunc onComplete = nullptr);
   void GoBack();
   void GoForward();
   void Reload();
   void Stop();
   bool IsNavigating() const { return m_isNavigating; }
   void DisablePopups();

   void PrintDocument();
   CString GetTitle() const { return m_strTitle; }

   void SetParent(CWnd* pParent) { m_pParent = pParent; }
   bool IsWebViewCreated() const;

protected:
   DECLARE_DYNCREATE(CWebBrowser)
   DECLARE_MESSAGE_MAP()

private:
   CWebBrowserImpl* m_pImpl;
   std::map<CallbackType, CallbackFunc> m_callbacks;

   EventRegistrationToken m_navigationCompletedToken = {};
   EventRegistrationToken m_navigationStartingToken = {};
   EventRegistrationToken m_documentTitleChangedToken = {};

   bool m_isNavigating = false;
   CWnd* m_pParent = nullptr;
   CString m_strTitle;

private:
   void RunAsync(CallbackFunc callback);

   void CloseWebView();
   void RegisterEventHandlers();
   void ResizeToClientArea();
   void NavigateTo(CString url);
   CString NormalizeUrl(CString url);

   static CString GetInstallPath();
   static CString GetInstallPathFromRegistry(bool const searchWebView = true);
   static CString GetInstallPathFromDisk(bool const searchWebView = true);
   static CString GetUserDataFolder();

   void InitializeWebView();
   HRESULT OnCreateEnvironmentCompleted(HRESULT result, ICoreWebView2Environment* environment);
   HRESULT OnCreateWebViewControllerCompleted(HRESULT result, ICoreWebView2Controller* controller);

   static PCTSTR GetWindowClass();
   static LRESULT CALLBACK WndProcStatic(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
   bool HandleWindowMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, LRESULT* result);

   BOOL CreateHostWindow(
      LPCTSTR lpszClassName,
      LPCTSTR lpszWindowName,
      DWORD dwStyle,
      const RECT& rect,
      CWnd* pParentWnd,
      UINT nID);
};

CWebBrowser Source
#include "pch.h"
#include <wrl.h>
#include "wil/com.h"

using namespace Microsoft::WRL;

#include "EdgeWebBrowser.h"
#include "Messages.h"

#include "WebView2.h"

#include <sstream>
#include <iomanip>

#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
#include "shlobj.h"

#pragma comment(lib,"Version.lib")

#include <string>

#define CHECK_FAILURE_STRINGIFY(arg)         #arg
#define CHECK_FAILURE_FILE_LINE(file, line)  ([](HRESULT hr){ CheckFailure(hr, L"Failure at " CHECK_FAILURE_STRINGIFY(file) L"(" CHECK_FAILURE_STRINGIFY(line) L")"); })
#define CHECK_FAILURE                        CHECK_FAILURE_FILE_LINE(__FILE__, __LINE__)
#define CHECK_FAILURE_BOOL(value)            CHECK_FAILURE((value) ? S_OK : E_UNEXPECTED)

struct CWebBrowserImpl
{
   wil::com_ptr<ICoreWebView2Environment>    m_webViewEnvironment;
   wil::com_ptr<ICoreWebView2Environment2>   m_webViewEnvironment2;
   wil::com_ptr<ICoreWebView2>               m_webView;
   wil::com_ptr<ICoreWebView2_2>             m_webView2;
   wil::com_ptr<ICoreWebView2Controller>     m_webController;
   wil::com_ptr<ICoreWebView2Settings>       m_webSettings;
};

void ShowFailure(HRESULT hr, CString const & message)
{
   CString text;
   text.Format(L"%s (0x%08X)", (LPCTSTR)message, hr);

   ::MessageBox(nullptr, static_cast<LPCTSTR>(text), L"Failure", MB_OK);
}

void CheckFailure(HRESULT hr, CString const & message)
{
   if (FAILED(hr))
   {
      CString text;
      text.Format(L"%s : 0x%08X", (LPCTSTR)message, hr);

      // TODO: log text

      std::exit(hr);
   }
}

/////////////////////////////////////////////////////////////////////////////
// CWebBrowser

IMPLEMENT_DYNCREATE(CWebBrowser, CWnd)

/////////////////////////////////////////////////////////////////////////////
// CWebBrowser properties
BEGIN_MESSAGE_MAP(CWebBrowser, CWnd)
END_MESSAGE_MAP()

CWebBrowser::CWebBrowser():m_pImpl(new CWebBrowserImpl())
{
   m_callbacks[CallbackType::CreationCompleted] = nullptr;
   m_callbacks[CallbackType::NavigationCompleted] = nullptr;
}

CWebBrowser::~CWebBrowser()
{
   SetWindowLongPtr(m_hWnd, GWLP_USERDATA, 0);
   CloseWebView();
   delete m_pImpl;
}

BOOL CWebBrowser::CreateHostWindow(
   LPCTSTR lpszClassName,
   LPCTSTR lpszWindowName,
   DWORD dwStyle,
   const RECT& rect,
   CWnd* pParentWnd,
   UINT nID)
{
   if (lpszClassName == nullptr)
      lpszClassName = GetWindowClass();

   if (!CWnd::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID))
      return FALSE;

   ::SetWindowLongPtr(m_hWnd, GWLP_USERDATA, (LONG_PTR)this);

   return TRUE;
}

BOOL CWebBrowser::Create(
   LPCTSTR lpszClassName,
   LPCTSTR lpszWindowName,
   DWORD dwStyle,
   const RECT& rect,
   CWnd* pParentWnd,
   UINT nID,
   CCreateContext*)
{
   if (!CreateHostWindow(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID))
      return FALSE;

   InitializeWebView();

   return TRUE;
}

BOOL CWebBrowser::CreateAsync(
   DWORD dwStyle,
   const RECT& rect,
   CWnd* pParentWnd,
   UINT nID,
   CallbackFunc onCreated)
{
   if (!CreateHostWindow(nullptr, nullptr, dwStyle, rect, pParentWnd, nID))
      return FALSE;

   m_callbacks[CallbackType::CreationCompleted] = onCreated;

   InitializeWebView();

   return TRUE;
}

void CWebBrowser::RegisterCallback(CallbackType const type, CallbackFunc callback)
{
   m_callbacks[type] = callback;
}

void CWebBrowser::CloseWebView()
{
   if (m_pImpl->m_webView)
   {
      m_pImpl->m_webView->remove_NavigationCompleted(m_navigationCompletedToken);
      m_pImpl->m_webView->remove_NavigationStarting(m_navigationStartingToken);
      m_pImpl->m_webView->remove_DocumentTitleChanged(m_documentTitleChangedToken);

      m_pImpl->m_webController->Close();

      m_pImpl->m_webController = nullptr;
      m_pImpl->m_webView = nullptr;
      m_pImpl->m_webView2 = nullptr;
      m_pImpl->m_webSettings = nullptr;
   }

   m_pImpl->m_webViewEnvironment2 = nullptr;
   m_pImpl->m_webViewEnvironment = nullptr;
}

void CWebBrowser::InitializeWebView()
{
   CloseWebView();

   CString subFolder = GetInstallPath();
   CString appData = GetUserDataFolder();
   ICoreWebView2EnvironmentOptions* options = nullptr;

   HRESULT hr = CreateCoreWebView2EnvironmentWithOptions(
      subFolder,
      appData,
      options,
      Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
         this,
         &CWebBrowser::OnCreateEnvironmentCompleted).Get());

   if (!SUCCEEDED(hr))
   {
      CString text;
      if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
      {
         text = L"Cannot found the WebView2 component.";
      }
      else
      {
         text = L"Cannot create the webview environment.";
      }

      ShowFailure(hr, text);
   }
}

HRESULT CWebBrowser::OnCreateEnvironmentCompleted(
   HRESULT result,
   ICoreWebView2Environment* environment)
{
   CHECK_FAILURE(result);

   if (!environment)
      return E_FAIL;

   CHECK_FAILURE(environment->QueryInterface(IID_PPV_ARGS(&m_pImpl->m_webViewEnvironment)));
   CHECK_FAILURE(environment->QueryInterface(IID_PPV_ARGS(&m_pImpl->m_webViewEnvironment2)));

   CHECK_FAILURE(m_pImpl->m_webViewEnvironment->CreateCoreWebView2Controller(
      m_hWnd,
      Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
         this,
         &CWebBrowser::OnCreateWebViewControllerCompleted).Get()));

   return S_OK;
}

HRESULT CWebBrowser::OnCreateWebViewControllerCompleted(
   HRESULT result,
   ICoreWebView2Controller* controller)
{
   if (result == S_OK)
   {
      if (controller != nullptr)
      {
         m_pImpl->m_webController = controller;
         CHECK_FAILURE(controller->get_CoreWebView2(&m_pImpl->m_webView));

         if (!m_pImpl->m_webView)
            return E_FAIL;

         CHECK_FAILURE(m_pImpl->m_webView->QueryInterface(IID_PPV_ARGS(&m_pImpl->m_webView2)));

         CHECK_FAILURE(m_pImpl->m_webView->get_Settings(&m_pImpl->m_webSettings));

         RegisterEventHandlers();

         ResizeToClientArea();
      }

      auto callback = m_callbacks[CallbackType::CreationCompleted];
      if (callback != nullptr)
         RunAsync(callback);
   }
   else
   {
      ShowFailure(result, L"Cannot create webview environment.");
   }

   return S_OK;
}

void CWebBrowser::RegisterEventHandlers()
{
   // NavigationCompleted handler
   CHECK_FAILURE(m_pImpl->m_webView->add_NavigationCompleted(
      Callback<ICoreWebView2NavigationCompletedEventHandler>(
         [this](
            ICoreWebView2*,
            ICoreWebView2NavigationCompletedEventArgs* args) -> HRESULT
         {
            m_isNavigating = false;

            BOOL success;
            CHECK_FAILURE(args->get_IsSuccess(&success));

            if (!success)
            {
               COREWEBVIEW2_WEB_ERROR_STATUS webErrorStatus{};
               CHECK_FAILURE(args->get_WebErrorStatus(&webErrorStatus));
               if (webErrorStatus == COREWEBVIEW2_WEB_ERROR_STATUS_DISCONNECTED)
               {
                  // Do something here if you want to handle a specific error case.
                  // In most cases this isn't necessary, because the WebView will
                  // display its own error page automatically.
               }
            }

            wil::unique_cotaskmem_string uri;
            m_pImpl->m_webView->get_Source(&uri);

            if (wcscmp(uri.get(), L"about:blank") == 0)
            {
               uri = wil::make_cotaskmem_string(L"");
            }

            auto callback = m_callbacks[CallbackType::NavigationCompleted];
            if (callback != nullptr)
               RunAsync(callback);

            return S_OK;
         })
      .Get(),
            &m_navigationCompletedToken));

   // NavigationStarting handler
   CHECK_FAILURE(m_pImpl->m_webView->add_NavigationStarting(
      Callback<ICoreWebView2NavigationStartingEventHandler>(
         [this](
            ICoreWebView2*,
            ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT
         {
            wil::unique_cotaskmem_string uri;
            CHECK_FAILURE(args->get_Uri(&uri));

            m_isNavigating = true;

            return S_OK;
         }).Get(), &m_navigationStartingToken));

   // DocumentTitleChanged handler
   CHECK_FAILURE(m_pImpl->m_webView->add_DocumentTitleChanged(
      Callback<ICoreWebView2DocumentTitleChangedEventHandler>(
         [this](ICoreWebView2* sender, IUnknown* args) -> HRESULT {
            wil::unique_cotaskmem_string title;
            CHECK_FAILURE(sender->get_DocumentTitle(&title));

            m_strTitle = title.get();

            auto callback = m_callbacks[CallbackType::TitleChanged];
            if (callback != nullptr)
               RunAsync(callback);

            return S_OK;
         })
      .Get(), &m_documentTitleChangedToken));
}

void CWebBrowser::ResizeToClientArea()
{
   if (m_pImpl->m_webController)
   {
      RECT bounds;
      GetClientRect(&bounds);
      m_pImpl->m_webController->put_Bounds(bounds);
   }
}

RECT CWebBrowser::GetBounds()
{
   RECT rc{0,0,0,0};
   if (m_pImpl->m_webController)
   {
      m_pImpl->m_webController->get_Bounds(&rc);
   }

   return rc;
}

void CWebBrowser::Resize(LONG const width, LONG const height)
{
   SetWindowPos(nullptr, 0, 0, width, height, SWP_NOMOVE| SWP_NOREPOSITION);
}

CString CWebBrowser::GetLocationURL()
{
   CString url;
   if (m_pImpl->m_webView)
   {
      wil::unique_cotaskmem_string uri;
      m_pImpl->m_webView->get_Source(&uri);

      if (wcscmp(uri.get(), L"about:blank") == 0)
      {
         uri = wil::make_cotaskmem_string(L"");
      }

      url = uri.get();
   }

   return url;
}

CString CWebBrowser::NormalizeUrl(CString url)
{
   if (url.Find(_T("://")) < 0)
   {
      if (url.GetLength() > 1 && url[1] == ':')
         url = _T("file://") + url;
      else
         url = _T("http://") + url;
   }

   return url;
}

void CWebBrowser::NavigateTo(CString url)
{
   m_pImpl->m_webView->Navigate(NormalizeUrl(url));
}

void CWebBrowser::Navigate(CString const & url, CallbackFunc onComplete)
{
   if (m_pImpl->m_webView)
   {
      m_callbacks[CallbackType::NavigationCompleted] = onComplete;
      NavigateTo(url);
   }
}

// The raw request header string delimited by CRLF(optional in last header).
void CWebBrowser::NavigatePost(CString const& url, CString const& content, CString const& headers, std::function<void()> onComplete)
{
   if (!m_pImpl->m_webView) return;

   CString normalizedUrl{ NormalizeUrl(url) };

   m_callbacks[CallbackType::NavigationCompleted] = onComplete;

   wil::com_ptr<ICoreWebView2WebResourceRequest> webResourceRequest;
   wil::com_ptr<IStream> postDataStream = SHCreateMemStream(
      reinterpret_cast<const BYTE*>(static_cast<LPCTSTR>(content)),
      content.GetLength() + 1);

   CHECK_FAILURE(m_pImpl->m_webViewEnvironment2->CreateWebResourceRequest(
      CT2W(normalizedUrl),
      L"POST",
      postDataStream.get(),
      CT2W(headers),
      &webResourceRequest));

   CHECK_FAILURE(m_pImpl->m_webView2->NavigateWithWebResourceRequest(webResourceRequest.get()));
}
void CWebBrowser::PrintDocument()
{
   if (m_pImpl->m_webView)
   {
      m_pImpl->m_webView->ExecuteScript(L"window.print();", nullptr);
   }
}

void CWebBrowser::Stop()
{
   if (m_pImpl->m_webView)
   {
      m_pImpl->m_webView->Stop();
   }
}

void CWebBrowser::Reload()
{
   if (m_pImpl->m_webView)
   {
      m_pImpl->m_webView->Reload();
   }
}

void CWebBrowser::GoBack()
{
   if (m_pImpl->m_webView)
   {
      BOOL possible = FALSE;
      m_pImpl->m_webView->get_CanGoBack(&possible);
      if(possible)
         m_pImpl->m_webView->GoBack();
   }
}

void CWebBrowser::GoForward()
{
   if (m_pImpl->m_webView)
   {
      BOOL possible = FALSE;
      m_pImpl->m_webView->get_CanGoForward(&possible);
      if (possible)
         m_pImpl->m_webView->GoForward();
   }
}

void CWebBrowser::DisablePopups()
{
   if (m_pImpl->m_webSettings)
   {
      m_pImpl->m_webSettings->put_AreDefaultScriptDialogsEnabled(FALSE);
   }
}

PCTSTR CWebBrowser::GetWindowClass()
{
   static PCTSTR windowClass = []
   {
      static TCHAR const * className = L"EdgeBrowserHost";

      WNDCLASSEX wcex;
      wcex.cbSize = sizeof(WNDCLASSEX);

      wcex.style = CS_HREDRAW | CS_VREDRAW;
      wcex.lpfnWndProc = WndProcStatic;
      wcex.cbClsExtra = 0;
      wcex.cbWndExtra = 0;
      wcex.hInstance = AfxGetInstanceHandle();
      wcex.hIcon = nullptr;
      wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
      wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
      wcex.lpszMenuName = nullptr;
      wcex.lpszClassName = className;
      wcex.hIconSm = nullptr;

      ATOM result = RegisterClassEx(&wcex);
      if (result == 0)
      {
         [[maybe_unused]] DWORD lastError = ::GetLastError();
      }

      return className;
   }();

   return windowClass;
}

LRESULT CALLBACK CWebBrowser::WndProcStatic(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   if (auto app = (CWebBrowser*)::GetWindowLongPtr(hWnd, GWLP_USERDATA))
   {
      LRESULT result = 0;
      if (app->HandleWindowMessage(hWnd, message, wParam, lParam, &result))
      {
         return result;
      }
   }

   return ::DefWindowProc(hWnd, message, wParam, lParam);
}

bool CWebBrowser::HandleWindowMessage(
   HWND, UINT message, WPARAM wParam, LPARAM lParam, LRESULT* result)
{
   *result = 0;

   switch (message)
   {
   case WM_SIZE:
   {
      if (lParam != 0)
      {
         ResizeToClientArea();
         return true;
      }
   }
   break;
   case MSG_RUN_ASYNC_CALLBACK:
   {
      auto* task = reinterpret_cast<CallbackFunc*>(wParam);
      (*task)();
      delete task;
      return true;
   }
   break;
   }

   return false;
}

void CWebBrowser::RunAsync(CallbackFunc callback)
{
   auto* task = new CallbackFunc(callback);
   PostMessage(MSG_RUN_ASYNC_CALLBACK, reinterpret_cast<WPARAM>(task), 0);
}

bool CWebBrowser::IsWebViewCreated() const
{
   return m_pImpl->m_webView != nullptr;
}

CString CWebBrowser::GetInstallPath()
{
   static CString path = []
   {
      auto installPath = GetInstallPathFromRegistry();   // check registry for WebView2
      if (installPath.IsEmpty())
         installPath = GetInstallPathFromDisk();         // check disk for WebView2
      if (installPath.IsEmpty())
         installPath = GetInstallPathFromRegistry(false);// check registry for Edge
      if (installPath.IsEmpty())
         installPath = GetInstallPathFromDisk(false);    // check disk for Edge

      return installPath;
   }();

   return path;
}

CString CWebBrowser::GetInstallPathFromRegistry(bool const searchWebView)
{
   CString path;

   HKEY handle = nullptr;

   LSTATUS result = ERROR_FILE_NOT_FOUND;

   if (searchWebView)
   {
      result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
         LR"(SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView)",
         0,
         KEY_READ,
         &handle);

      if (result != ERROR_SUCCESS)
         result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
            LR"(SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView)",
            0,
            KEY_READ,
            &handle);
   }
   else
   {
      result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
         LR"(SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Edge)",
         0,
         KEY_READ,
         &handle);

      if (result != ERROR_SUCCESS)
         result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
            LR"(SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft Edge)",
            0,
            KEY_READ,
            &handle);
   }

   if (result == ERROR_SUCCESS)
   {
      TCHAR buffer[MAX_PATH + 1]{ 0 };
      DWORD type = REG_SZ;
      DWORD size = MAX_PATH;
      result = RegQueryValueEx(handle, L"InstallLocation", 0, &type, reinterpret_cast<LPBYTE>(buffer), &size);
      if (result == ERROR_SUCCESS)
         path += CString{ buffer };

      TCHAR version[100]{ 0 };
      size = 100;
      result = RegQueryValueEx(handle, L"Version", 0, &type, reinterpret_cast<LPBYTE>(version), &size);
      if (result == ERROR_SUCCESS)
      {
         if (path.GetAt(path.GetLength() - 1) != L'\\')
            path += L"\\";
         path += CString{ version };
      }
      else
         path.Empty();

      RegCloseKey(handle);
   }

   return path;
}

CString CWebBrowser::GetInstallPathFromDisk(bool const searchWebView)
{
   CString path =
      searchWebView ?
      LR"(c:\Program Files (x86)\Microsoft\EdgeWebView\Application\)" :
      LR"(c:\Program Files (x86)\Microsoft\Edge\Application\)";
   CString pattern = path + L"*";

   WIN32_FIND_DATA ffd{ 0 };
   HANDLE hFind = FindFirstFile(pattern, &ffd);
   if (hFind == INVALID_HANDLE_VALUE)
   {
      [[maybe_unused]] DWORD error = ::GetLastError();
      return {};
   }

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         CString name{ ffd.cFileName };
         int a, b, c, d;
         if (4 == swscanf_s(ffd.cFileName, L"%d.%d.%d.%d", &a, &b, &c, &d))
         {
            FindClose(hFind);
            return path + name;
         }
      }
   } while (FindNextFile(hFind, &ffd) != 0);

   FindClose(hFind);

   return {};
}

CString CWebBrowser::GetUserDataFolder()
{
   TCHAR szPath[MAX_PATH]{ 0 };
   ::SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, szPath);
   ::PathAppend(szPath, LR"(\Demos\)");
   ::PathAppend(szPath, L"MfcEdgeDemo");
   return CString{ szPath };
}

It works. One final comment, atleast for current ooperating systems... Make sure you have installed the WebView2 Runtime.


text:
Q: Using diagonalisation of a symmetric on quadratic form Let $f (x, y) = 7x_2 + 4y_2 + 4xy$. Use the diagonalisation of a symmetric matrix to write this quadratic form in the form $λ_1u_2^2 +λ_2v_2^2$, with u and v linear combinations of x and y.
Here's what I have tried:
step 1. get the symmetric matrix
$$f (x, y) = 7x_2 + 4y_2 + 4xy=\left(\begin{matrix}7&2\\2&4\\\end{matrix}\right)$$
step 2. find the eigenvalues
$$det(A-\lambda I) \\
\left(\begin{matrix}7-\lambda&2\\2&4-\lambda\\\end{matrix}\right)=(7-\lambda)(4-\lambda)-4=(\lambda-3)(\lambda-8)$$
step 3. find the eigenvectors
case for $\lambda =3$
$$\left(\begin{matrix}7-3&2\\2&4-3\\\end{matrix}\right)=\left(\begin{matrix}4&2\\2&1\\\end{matrix}\right)
$$
Row reduced
$$\left(\begin{matrix}4&2\\2&1\\\end{matrix}\right)=\left(\begin{matrix}1&\frac{1}{2}\\0&0\\\end{matrix}\right) \implies \left(\begin{matrix}x\\y\\\end{matrix}\right)=y_1\left(\begin{matrix}-\frac{1}{2}\\1\\\end{matrix}\right)$$
Doing the same for $\lambda =8$ (i'll skip the calculation), I get $\left(\begin{matrix}x\\y\\\end{matrix}\right)=y_2\left(\begin{matrix}2\\1\\\end{matrix}\right)$
Finding the orthogonal eigenvectors
$$u_1 = \frac{y_1}{||y_1||} = \frac{2}{\sqrt{5}}\left(\begin{matrix}-\frac{1}{2}\\1\\\end{matrix}\right) \\
u_2 = \frac{y_1}{||y_1||} = \frac{1}{\sqrt{5}}\left(\begin{matrix}2\\1\\\end{matrix}\right) \\
P=(u_1,u_2)=\left(\begin{matrix}-\frac{1}{\sqrt{5}}&\frac{2}{\sqrt{5}}\\\frac{2}{\sqrt{5}}&\frac{1}{\sqrt{5}}\\\end{matrix}\right) \\
D = P^TAP = \left(\begin{matrix}-\frac{1}{\sqrt{5}}&\frac{2}{\sqrt{5}}\\\frac{2}{\sqrt{5}}&\frac{1}{\sqrt{5}}\\\end{matrix}\right)\left(\begin{matrix}7&2\\2&4\\\end{matrix}\right)\left(\begin{matrix}-\frac{1}{\sqrt{5}}&\frac{2}{\sqrt{5}}\\\frac{2}{\sqrt{5}}&\frac{1}{\sqrt{5}}\\\end{matrix}\right) = \left(\begin{matrix}3&0\\0&8\\\end{matrix}\right) \\
x^TAx = \lambda^TD\lambda =  \left(\begin{matrix}\lambda_1&\lambda_2\\\end{matrix}\right)\left(\begin{matrix}3&0\\0&8\\\end{matrix}\right)\left(\begin{matrix}\lambda_1\\\lambda_2\\\end{matrix}\right) = 3\lambda_1^2+8\lambda_2^2$$
However, my result does not look like it's in the same form as the question:
$λ_1u_2^2 +λ_2v_2^2 \ne  3\lambda_1^2+8\lambda_2^2$, how do I proceed from here?

A: You start with the quadratic form
$$
 7x^2 + 4y^2 + 4xy=
\left(\begin{matrix}x&y\end{matrix}\right)A
\left(\begin{matrix}x\\y\\\end{matrix}\right)=
\left(\begin{matrix}x&y\end{matrix}\right)
\left(\begin{matrix}7&2\\2&4\\\end{matrix}\right)
\left(\begin{matrix}x\\y\\\end{matrix}\right)
$$
Write the eigenvalues decomposition of $A$ as
$$
A=PDP^T=\left[\frac{1}{\sqrt{5}}\left(\begin{matrix}-1&2\\2&1\end{matrix}\right)\right]
\left(\begin{matrix}3&0\\0&8\\\end{matrix}\right)
\left[\frac{1}{\sqrt{5}}\left(\begin{matrix}-1&2\\2&1\end{matrix}\right)\right]
$$
the quadratic form becomes
$$
\left[\left(\begin{matrix}x&y\end{matrix}\right)
\frac{1}{\sqrt{5}}\left(\begin{matrix}-1&2\\2&1\end{matrix}\right)\right]
\left(\begin{matrix}3&0\\0&8\\\end{matrix}\right)
\left[\frac{1}{\sqrt{5}}\left(\begin{matrix}-1&2\\2&1\end{matrix}\right)
\left(\begin{matrix}x\\y\\\end{matrix}\right)\right]$$
can you see what the two new variables $u,v$ are?
Note that your notation is a bit inaccurate and confusing.

A: This is a longer comment rather than an full answer:
If you want to "diagonalize" a quadratic form, completing the square is simpler than your approach via the eigendecomposition. Note that
$$ f (x, y) = 7x^2 + 4y^2 + 4xy = 6 x^2 + (2 y +x)^2 = 6 u^2 + v^2$$
with
$$u = x, \qquad v = 2 y +x$$
is a diagonalization in terms of a linear combination of $x$ and $y$.


text:
Q: VB.NET ListView/ListBox Checked item in WPF How do I simply add a checked (or unchecked) item in a listview (or a listbox) ?
I've searched for a long time but I always find topics on Windows Forms about CheckedListBox objects and ListView.Checked properties that don't seem to exist in WPF.
I succeeded in populating the list with some groups from an active directory, but I don't know how to show them with a simple check (or hide them).
Do I need to import some references?
I'm working with VB.NET with Visual Studio Express 2012.

A: You need to define an ItemTemplate for the ListBox:
         <ListBox ItemsSource="{Binding}" SelectionMode="Extended">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBoxItem}}"
                              Content="{Binding}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>


text:
Q: Understanding Valgrind's output I'm writing a project for university. It's all done, passes all the tests, runs fine, but Valgrind tells me this:
==8059== Invalid read of size 8
==8059==    at 0x406E4E: RegPoly::getCurrentCoefficient() const (RegPoly.cpp:59)
==8059==    by 0x403368: MyPoly::operator+(MyPoly const&) const (MyPoly.cpp:281)
==8059==    by 0x403A6D: MyPoly::operator+=(MyPoly const&) (MyPoly.cpp:354)
==8059==    by 0x401E20: main (DemoPoly.cpp:50)
==8059==  Address 0x5953f50 is 0 bytes after a block of size 16 alloc'd
==8059==    at 0x4C27297: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8059==    by 0x4060CD: __gnu_cxx::new_allocator<double>::allocate(unsigned long, void const*) (new_allocator.h:92)
==8059==    by 0x405934: std::_Vector_base<double, std::allocator<double> >::_M_allocate(unsigned long) (in /a/fr-05/vol/home/stud/lablabla/CppLab/Ex3/DemoPoly)
==8059==    by 0x407355: double* std::vector<double, std::allocator<double> >::_M_allocate_and_copy<__gnu_cxx::__normal_iterator<double const*, std::vector<double, std::allocator<double> > > >(unsigned long, __gnu_cxx::__normal_iterator<double const*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double const*, std::vector<double, std::allocator<double> > >) (stl_vector.h:1052)
==8059==    by 0x40700E: std::vector<double, std::allocator<double> >::operator=(std::vector<double, std::allocator<double> > const&) (vector.tcc:167)
==8059==    by 0x406C5D: RegPoly::RegPoly(RegPoly const&) (RegPoly.cpp:19)
==8059==    by 0x4031DB: MyPoly::operator=(MyPoly const&) (MyPoly.cpp:249)
==8059==    by 0x403B58: MyPoly::operator*=(MyPoly const&) (MyPoly.cpp:364)
==8059==    by 0x401DB6: main (DemoPoly.cpp:44)

The lines:
44 - p3 *= p2; // both are MyPoly objects
50 - p3 += p1;
I kind of understand that it means that I'm trying to read from a memory that has been changed (?), but I couldn't understand why.
I could post the relevant code, only, I'm not sure which part, as it would make the question messy. I can paste relevant parts, just tell me what you need.
Here's the code:
MyPoly& MyPoly::operator *=(const MyPoly& rhs)
{
    *this = *this * rhs; // 364
    return *this;
}

// ===================

case PolyInterface::REG:
{
    RegPoly *tempReg = dynamic_cast<RegPoly*>(rhs.p_PolyBody); // rhs is an interface, hence the dynamic cast
    if (tempReg != NULL)
    {
        p_PolyBody = new RegPoly(*tempReg);  // 249. p_PolyBody is a pointer stored in MyPoly. points to RegPoly object
    }
    break;
}

// ===================

RegPoly::RegPoly(RegPoly const& other)
{
    gCurrentRank = 0;
    gData = other.gData; // 19. gData is a vector<double>
    _isZeroPoly = other._isZeroPoly;
}

// ===================

double RegPoly::getCurrentCoefficient() const
{
    return *gDataIterator; // 59. vector<double>::const_iterator
}

// ===================

newPolyValues.push_back(
                p_PolyBody->getCurrentCoefficient() + rhs.p_PolyBody->getCurrentCoefficient());
// 281.

I'm also getting this when getCurrentCoefficient() returns gData[gCurrentRank], meaning that it's something with the location of gData itself, right?
RegPoly:
std::vector<double> gData;
std::vector<double>::iterator gDataIterator;
int gCurrentRank;
bool _isZeroPoly; // Inherited from the interface

A: Trust Valgrind. It almost always shows existing problems.
Here is how you read the message:
RegPoly::getCurrentCoefficient() const (RegPoly.cpp:59) tried to read from a memory location it shouldn't have read, because it doesn't belong to your app (wasn't allocated, non-stack, etc...).
This invalid address was just beyond the space that was allocated with the new operator, used in your RegPoly copy constructor (and you can see the whole backtrace that created that call).
I don't see that your copy constructor copies gDataIterator.

A: The problem is on RegPoly.cpp:59, not in DemoPoly.cpp:50.
It is stated that you had allocated 16 bytes, but it is trying to read 8 bytes beyond your allocation.
See this: 4.2. Explanation of error messages from Memcheck
Probably you are trying to access an invalid iterator. A const iterator just means that you are not able use this iterator to modify a value inside a container.
A brief explanation related to invalid iterators.


text:
Q: How to set the first selector value to 1 in Cake PHP Form->select I am a new user to Cake PHP and I am going through the cake book of Cake PHP. When I am using the $this-Form->select('field', $array); the first value is always set to 0. I want this that the first selector has a value of 0.
$this->Form->select(
    'field',
    [1, 2, 3, 4, 5]
);
Output:

<select name="field">
    <option value="0">1</option>
    <option value="1">2</option>
    <option value="2">3</option>
    <option value="3">4</option>
    <option value="4">5</option>
</select>

Can anyone help me with this query?

A: That's how arrays are created by default, if you don't supply keys. To use the same values for keys and values, try this:
$values = [1, 2, 3, 4, 5];
$this->Form->select(
    'field',
    array_combine($values, $values)
);


text:
Q: Why is the AJAX call coming back with a status code 0 I'm exploring AJAX form submission and I've run into a problem where my AJAX call is returning an error with little to no information as to why.
My SubmitForm method is as follows:
function SubmitForm(FormId,Container)
{
    var FormElement = document.getElementById(FormId);
    var TargetUrl = document.URL + "resource/form/" + FormId + ".php";
    var SubmitUrl = TargetUrl + "?action=submit";
    var SuccessUrl = TargetUrl + "?action=success";
    var ErrorUrl = TargetUrl + "?action=failure";
    var DataString = "";

    for( var i = 0; i < FormElement.length; i++ )
    {
        if( i > 0 )
            DataString += "&"

        DataString += FormElement.elements[i].name + "=" + FormElement[i].value;
    }

    $.ajax({
      type: "POST",
      url: SubmitUrl,
      data: DataString,
      success: function() {
        RequestAjax(Container,SuccessUrl);
      },
      error: function(object, textStatus, errorThrown){
      console.log(textStatus + "|" + errorThrown + "|" + object.status + "|" + object.responseText);
          RequestAjax(Container,ErrorUrl);
      }
    });
    return false;
}

Being submit from:
<input name="submit" type="submit" id="submit" class="submit" value="Login" onClick="javascript: SubmitForm('loginForm','userData');" />

And I am getting output something like this;
error||0|

I know that the URL that I'm trying to hit exists, and have used basically identical code in another instance to submit a form, but am encountering the truly indescript problem that you see above.
Any advice would be much appreciated.

A: Status of zero comes from when the page is running off the file protocol or the page is refreshed when the Ajax call is made. Without seeing how your method is being called, I am assuming you are doing it like
<form onsubmit="SubmitForm();" />

You are missing the return
<form onsubmit="return SubmitForm();" />
                ^^^^^^

or with the input's click
<input type="submit" onclick="SubmitForm();" />

which should be
<input type="submit" onclick="return SubmitForm();" />
                              ^^^^^^

A: First thing I'd try would be to UrlEncode your values:
var DataString = "";

for( var i = 0; i < FormElement.length; i++ )
{
    if( i > 0 )
        DataString += "&"

    DataString += FormElement.elements[i].name + "=" + encodeURI(FormElement[i].value);
}

A: I find this happens when an Ajax process is aborted. This can happen if the page is unloaded, or if the server connection is reset for some reason.
btw: if you're using jQuery you're better off building your postdata string with $(FormElement).serialize()


text:
Q: Llamada de métodos en python Tengo dos scripts en Python pero ahora quiero hacer uno solo, terminando de llamar un método luego quiero llamar el otro pero me dice

name 'readImage' is not defined

Asi es como estoy llamando los métodos:
def decoder(image):
    #code

def main():
    #code
    decoder(frame)

if __name__ == '__main__':
    main()#se ejecuta correctamente
    readImage(frame)#esta me da el error anterior

def readImage(img):
    #code

El último método readImage() es de otro script y lo quiero unificar con lo que ya esta ahí en el primer script.
Aclarando es la primera vez que estoy usando Python, quizás sea algo sencillo para alguien con algo de experiencia en este lenguaje, igual sigo buscando información en San Google :)

A: Modifica el orden de tus funciones:
def decoder(image):
    #code

def main():
    #code
    decoder(frame)

def readImage(img):
    #code

if __name__ == '__main__':
    main() #se ejecuta correctamente
    readImage(frame)

A: La definición de una función debe estar por encima de su llamada. Debes modificar el orden del código y eso solucionará el problema.


text:
Q: Laravel Validator facade fails with file input I have a modal form that submits a file to the controller. I validate using the Validate facade. EVerytime i upload file it says no file(My validation fail response). This code was working perfectly i can't figure out what causes this issue
<form enctype ="multipart/form-data" action = "/profile_image" method = "POST">
<label>Your Profile Image</label>
<input type = "file" name = "avatar">
{{ csrf_field() }}
<input type = "submit" class= "pull-right btn btn-sm btn-primary">Upload image</input>
</form>

Here is my controller
public function userImage(Request $request){

    $post = $request->all();
    $val = \Validator::make($request->all(),
        ['avatar' => 'required']);

    if ($val->fails()) {
        echo "no file";
    } else{
        if($request->hasFile('avatar')) {
            $avatar = $request->file('avatar');
            $filename = time().'.'.$avatar->getClientOriginalExtension();
            Image::make($avatar)->save('resources/assets/avatars',$filename);
            $user=\Auth::user();
            $user->avatar=$filename;
            $user->save();
        } else {
            echo "No file found";
        }
    }
}

I get this response
if ($val->fails()) {
  echo "no file";
}

I dont understand what makes validator to fail


text:
Q: How to Make an Array for Annotations Not all my annotations will show up in my map because I can't make var annotation = MKPoinatAnnotation the same MKPointAnnotation in fetching the CKrecords(annotation), and in getting directions for an annotation. I'm confused on how to make an array for annotations so I can be able to load all my annotations from the CloudKit database and be able to get directions when the annotation is selected.
let annotation = MKPointAnnotation()
let database = CKContainer.default().publicCloudDatabase
var truck: [CKRecord] = []

func fetch() {

let truePredicate = NSPredicate(value: true)
let eventQuery = CKQuery(recordType: "User", predicate: truePredicate)
let queryOperation = CKQueryOperation(query: eventQuery)

queryOperation.recordFetchedBlock = { (record : CKRecord!) in

    self.truck.append(record)

    self.annotation.title = record["username"] as? String
    self.annotation.subtitle = record["hours"] as? String
    if let location = record["location"] as? CLLocation {
        self.annotation.coordinate = location.coordinate
    }

    print("recordFetchedBlock: \(record)")

    self.mapView.addAnnotation(self.annotation)

}

self.database.add(queryOperation)

}

How I get directions -
@IBAction func getDirections(_ sender: Any) {
let view = annotation.coordinate

print("Annotation: \(String(describing: view ))")

let currentLocMapItem = MKMapItem.forCurrentLocation()

let selectedPlacemark = MKPlacemark(coordinate: view, addressDictionary: nil)
let selectedMapItem = MKMapItem(placemark: selectedPlacemark)

let mapItems = [selectedMapItem, currentLocMapItem]

let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]

MKMapItem.openMaps(with: mapItems, launchOptions:launchOptions)
}

A: I'm assuming the contents of the array change depending on the search query. If that is the case, make an array of type MKPointAnnotation:
var points: [MKPointAnnotation] = []

Then fill the array however you fill it and run it through a loop whereby each iteration adds a point to the map:
for point in points {
    mapView.addAnnotation(point)
}

If you have a problem with varying types of annotations, make the array of type CLLocationCoordinate2D and then you can fill the array by accessing MKPointAnnotation.coordinate, for example.
Does this help?


text:
Q: How do I add a drop down menu icon? I have a question about adding some type of icon or indicator to the buttons that have drop down menus in my navigation. The menu looks good in all browsers with minor exceptions. The menu itself is built in an Ektron CMS. I have 7 buttons in my navigation, 5 of which have drop down menus. As you can see on my site I have a little right-arrow indicating which ones have drop downs. The arrow is a unicode character that luckily worked when adding it in the menu control in the CMS. I'm fairly happy with the results but I'm not sure if that was the best way to create the icon.
Is there a better, or more efficient way of creating this type of indicator? Is there a way in JavaScript to assign a symbol or icon only if there is a sub menu present?
Although my solution works, there is one issue that I'm having trouble solving. In IE7+, Chrome and Safari all of the buttons were perfectly aligned. In FireFox, the 2 buttons without drop down menus were 4px higher than the ones with drop downs. This occurred as soon as I added the unicode arrow character. I added a little CSS hack that corrects the issue in FF but now I have an issue in Chrome where the last two buttons are 4px lower than the rest. I'm not sure how to correct this problem efficiently.
Here is a link to my site. I appreciate any help you can provide.
http://www.clinicaltrialsummit.com/

A: Try to remove this style:
#nav li a:last-child[href="http://www.healthtech.com/press.aspx"] {
    padding: 16px 0.4em 0
}

You have 14px default padding top, but the rule above sets padding of 16px for the last child with a specific href.
In your jsfiddle example there isn't this css rule.
You can use css arrows instead of UTF-8 symbol or use an icon, but I think that it's OK to use UTF-8 symbol like you do.

A: Thanks for responding but I should have mentioned that the style you reference above is my css hack. I'll try to explain my reason behind using it.
I needed a way of singling out my last navigation button without being able to apply a class directly to the li. Since the menu itself is created using a control in my CMS the HTML markup is generated dynamically. I didn't want to use the :last-child pseudo class but I also needed a way of adding the extra px of padding only to FF. I knew that IE would ignore the :last-child. However, that's where I failed because it also added it in Chrome and I believe Safari. I can take the entire style out and that might help you see my problem better. You would see that the vertical alignment is correct in every browser except FF.
The entire alignment was perfect until I added in my UTF-8 character. That's when it became misaligned but only in FF.
How would I add a CSS arrow?


text:
Q: need iframe code for facebook like button I am trying to create a like button for my weebly website.  Weebly advises to use the IFRAME code but when I select this option with the facebook web developer, no code appears.  What's going on?

A: <iframe src="//www.facebook.com/plugins/like.php?href=PUT_URL_HERE&width&layout=standard&action=like&show_faces=true&share=true&height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:80px;" allowTransparency="true"></iframe>

And replace the PUT_URL_HERE with the url of the page you'd like to have your users like.


text:
Q: An element adding unwanted margin space above the footer automatically Something is adding unwanted margin-top space to footer. I want to remove this but could not figure it out where it is coming from. Please see image below.
Thank you for your answer in advance.

element.style {
    margin-top: 581px;
    display: block;
}
footer#main-footer {
    background: #F60;
    padding: 60px 0 30px;
    color: #fff;
    font-size: 13px;
    line-height: 1em;
}
article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary {
    display: block;
}
HTML

<footer id="main-footer">

A: obviously some javascript (probably from a framework or template) is adding that element.style dynamically (i.e. a script is executed). You have to to deactivate at least that part of your (framework) script.
Since you give no more information and code, that's all that can be said to help you.
ADDITION: Note what is written at the bottom right of your image: that's where this stuff comes from...
ADDITION 2: You can try to add #main-footer { margin-top: 0 !important;}, but that's not really a good solution...

A: With limited details in the question and no way to reproduce the issue I can suggest 2 things:

*

*As a WORKAROUND you can use footer#main-footer { margin-top: 0px !important }. Though this is not recommended. https://css-tricks.com/when-using-important-is-the-right-choice/

*Alternatively if you wish to debug the issue, start removing JS references from your HTML one by one. There will be some JS code that is causing this. When you remove reference to that code your footer will be fine (without using the workaround mentioned above). Once you have identified the JS file you can debug that code to check why its adding margin-top.

A: bootstrap mt20 solved the problem: <footer id="main-footer" class="mt20" style="margin-top: 581px; display: block;">


text:
Q: Use SUM With Update & CTE I am attempting to Use the SUM() function with an update query and I am getting an error of

Msg 130, Level 15, State 1, Procedure PYES, Line 144
  Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

I am not sure how to re-write this in order to achieve my desired result.  Can someone please provide assistance?
;WITH CTE As
(Select pkID,serviceman, jv
 FROM OPENQUERY(XXX.XX.XXX.XXX,
                'Select
                    jb.pkID As pkID
                    ,cm.cn As serviceman
                    ,jb.jv As jv
                    FROM arica jb
                    INNER JOIN serviceman cm
                    ON jb.spID = cm.spID
                    INNER JOIN salesperson sp
                    ON jb.uqID = sp.uqID
                    INNER JOIN jointca js
                    ON jb.css = js.sid
                    INNER JOIN jart jp
                    ON jp.pkID = jb.pkID
                    WHERE jb.css IN (''R'',''H'',''p'',''S'',''O'',''N'')
                    GROUP BY jb.pkID, jb.jv,cm.cn') v
WHERE jv > 0)
UPDATE t
SET INP = SUM(ISNULL(INP,0)+ISNULL(SUM(jv),0))
FROM tertiarydata t
INNER JOIN CTE cte
ON t.pkID = cte.pkID;

EDIT
Thanks to the dupe by @SP_BlitsErik - I modified my code to the below - but that returns multiple entries for the field serviceman I want to only return 1 row for each serviceman listed
;WITH CTE As
(Select pkID,serviceman, jv
 FROM OPENQUERY(XXX.XX.XXX.XXX,
                'Select
                    jb.pkID As pkID
                    ,cm.cn As serviceman
                    ,jb.jv As jv
                    FROM arica jb
                    INNER JOIN serviceman cm
                    ON jb.spID = cm.spID
                    INNER JOIN salesperson sp
                    ON jb.uqID = sp.uqID
                    INNER JOIN jointca js
                    ON jb.css = js.sid
                    INNER JOIN jart jp
                    ON jp.pkID = jb.pkID
                    WHERE jb.css IN (''R'',''H'',''p'',''S'',''O'',''N'')
                    GROUP BY jb.pkID, jb.jv,cm.cn') v
WHERE jv > 0)
, uCTE as (
  select pkID,serviceman, sumJV=sum(jv)
    from cte
    group by serviceman,pkID
)
Select * from uCTE


text:
Q: Difference between int and unsigned int in C I know that the range of unsigned int is 0<= I <= 2^32-1
However, when I type like this in C(visual 2015)
void main(){
   unsigned int k = -10;
   printf("%d",k);
}

then why computer print -10 on screen?? I think there should be error.

A: int stores signed numbers by default, which means they can go from -2,147,483,648 to 2,147,483,647 in range.  An unsigned int means you won't be using negative numbers, so the range is much larger because you have freed up the left most bit in your number which is normally used to indicate that it is signed (negative) or not.  So an unsigned int can go from 0 to 4,294,967,295.  This applies to types like char as well, they normally go from -128 to 127, when unsigned, a char holds one byte exactly, or 0 to 255.
Visual Studio (and most compilers) should give you a warning for trying to store a signed value into an unsigned type.
When you used printf("%d",k) The %d is telling printf() to print out a signed int.  So that is what it did.  If you want printf() to print out an unsigned int than you needed to use printf("%u").

A: in hexadecimal form, -10 is 0xFFFFFFF6
unsigned int k = -10; means
unsigned int k = 0xFFFFFFF6;
and when printing this value if you say
printf("%d",k); the compiler will evaluate the value (0xFFFFFFF6) as integer because of the %d specifier. (check http://www.cplusplus.com/reference/cstdio/printf/ about the issue)
if you say printf("%u",k); the compiler will evaluate the value (0xFFFFFFF6) as unsigned integer and will print a value between 0-2^32-1


text:
Q: is this valid C plus valid ebpf, means can I safe the address of any object in long type which is 8 byte size this is my code
#include <stdio.h>
#include <string.h>
#include <stdint.h>
struct mystruct{
int i;
int j;
long k;
long l;
char str[11];

};
int main()
{

    struct mystruct obj;
    obj.i=5;obj.j=55;obj.k=6;obj.k=1000001;obj.l=2000007;memcpy(obj.str,"hello",sizeof("hello"));
    long addr=(long)((uint8_t *)&obj);
    struct mystruct *myobj=(struct mystruct *)(addr);
    printf("%d %d %zu %zu %s\n",myobj->i,myobj->j,myobj->k,myobj->l,myobj->str);
    printf("%zu=%zu\n",sizeof(long),sizeof(myobj));
    return 0;
}

So I like to know can I safe the address of any object (struct,union, etc.) or any type variable (int,long,char) into long variable. I showed the the code sizeof struct address or pointer is same as long. Is my above code is OK.
Also does ebpf varifier  allows this?
Also if I have map with value of type long
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __type(key, __u32);
    __type(value, long);
    __uint(max_entries, 2);
} hash_map1 SEC(".maps");

can I do extract my struct object like following from long type for map value
struct hash_elem {
    int cnt;
    struct bpf_spin_lock lock;
};

from long type. is this possible in ebpf/xdp?

A: long addr=(long)((uint8_t *)&obj);
struct mystruct *myobj=(struct mystruct *)(addr);

I don't see a reason why the BPF verifier should reject this; you are just casting into and from long.
This will be compiled into a 64-bit BPF register anyway and type information will be lost (unless using BTF). The verifier will then infer a type for its own purpose and will correctly recognize this as a pointer to the stack (PTR_TO_STACK).

can I do extract my struct object like following from long type for map value

No, that wouldn't make sense. If you store in the map a pointer to the stack, then when your program exists, the pointer may be pointing to invalid memory.

A: Why not simple:
    uintptr_t addr=(uintptr_t)&obj;
    struct mystruct *myobj=(struct mystruct *)(addr);

uintptr_t type is guaranteed to keep any pointer converted to an integer and it is widely used in the BPF code.


text:
Q: Ternary to return undefined? I want to include a property on an object only in the event that a variable is defined. I don't want the property at all otherwise. I don't even want it to equal a blank string. I'm thinking something like this:
someFunc({
    bing: "bing",
    bang: (myVar) ? myVar : undefined,
    boom: "boom"
    }, "yay");

In the event that myVar is undefined, I want this to result in the same thing as the below:
someFunc({
    bing: "bing",
    boom: "boom"
    }, "yay");

Am I doing it right?

A: There is a difference between this:
var ex1 = {foo: undefined};

and this:
var ex2 = {};

Therefore, here's how I would do it:
var args = {
    bing: 'bing',
    boom: 'boom'
};

if (typeof myVar !== 'undefined') {
    args.bang = myVar;
}

someFunc(args, 'yay');

A: i would do something like
var config = {
    bing: "bing",
    boom: "boom"
};

if (typeof myVar !== 'undefined') config.bang = myVar;

someFunc(config, 'yay');

you have to be careful of javascript truthiness and falsiness.  The if statement in my example only puts bang on config if myVar is defined, but it works if myVar is defined as false.

A: Use rest operator.
var obj = {
    bing: "bing",
    ...(myVar ? { bang: myVar } : {}),
    boom: "boom"
}

A: The best way to do this would be
var args = {
    bing: "bing",
    bang: myVar,
    boom: "boom"
}

if (myVar === undefined) {
    delete args.myVar;
}

someFunc(args, "yay");

Clearly adding it when it exists is better then then deleting it when it doesn't exist.
The point is to treat something like it really isn't there it is safest to use the native delete to remove a property from an object.
You can hack it using setTimeout and callbacks. I recommend againts this
var args = {
    bing: 4,
    bang: (myVar === undefined) ? (function() {
        setTimeout(function() {
            delete args.bang;
        }, 0);
    })() : myVar
}, "yay");

A: var obj = {
    bing: "bing",
    boom: "boom"
}

myVar != null && obj.bang = myVar;

someFunc(obj, "yay");

The above code gets the job done. I don't think that you can do it directly inside the function call.


text:
Q: ILMerge, Unresolved assembly reference not allowed: System.Runtime I'm getting this exception during merging my project's executable file with the SQLite-net.dll file.
Screenshot
Does anyone have a solution?
EDIT: I added a config file containing this:
<configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <requiredRuntime safemode="true" imageVersion="v4.0.30319" version="v4.0.30319"/>
    </startup>
</configuration>

to the ILMerge folder and a new exception occured
Unresolved assembly reference not allowed: SQLitePCLRaw.core
Screenshot


text:
Q: Nested xpath: How do I use the result of an XPath expression as value? I am having the following XML structure:
  <xml>
      <value>b</value>
      <objects>
        <object>
            <value>a</value>
        </object>
        <object>
            <value>b</value>
        </object>
      </objects>
  </xml>

What I want is to select the second object, based on the value in the xml.
This XPath works:
//xml/objects/object[value = 'b']

This XPath does not return results:
//xml/objects/object[value = //xml/value/text()]

Are nested XPath expressions not supported?

A: They are, but the search within a predicate is always relative to the context you currently in.
Currently you start looking for an <xml/> element which is a child of <object/> and as there is none it will yield an empty result set.
Using ../ or parent::* you can go an axis step up to the parent and can select the required value:
//xml/objects/object[value = ../../value]


text:
Q: Replace numbers in data frame column in R?
Possible Duplicate:
Replace contents of factor column in R dataframe

I have the data.frame
df1<-data.frame("Sp1"=1:6,"Sp2"=7:12,"Sp3"=13:18)
rownames(df1)=c("A","B","C","D","E","F")

df1
  Sp1 Sp2 Sp3
A   1   7  13
B   2   8  14
C   3   9  15
D   4  10  16
E   5  11  17
F   6  12  18

I want to replace every entry of the number 8 in the column df1$Sp2 with the number 800. I have tried:
test<-replace(df1$Sp2,df1[800,"Sp2"],5)

A: e.g.:
df1$Sp2[df1$Sp2 == 8] <- 800


text:
Q: Trying to create function to count number of checked cells and call it from another function So I created a function:
-(void)checkCount:(UITableView *)tableView isIndexPathChecked:(NSIndexPath *)indexPath{
NSString *name = [[NSString alloc] init];
UITableViewCell *investigatedCell = [tableView cellForRowAtIndexPath:indexPath];
if(investigatedCell.accessoryType ==UITableViewCellAccessoryCheckmark)
    name = investigatedCell.textLabel.text;
[checkedRows addObject: name];
}

I'm getting errors every time I try to call this method from within another method.  What would be the proper syntax for this?  Thank you.

A: I believe the error you are seeing is because the method call is not present in your public header file.  Try adding
-(void)checkCount:(UITableView *)tableView isIndexPathChecked:(NSIndexPath *)indexPath;

to your .h file.
You might also want to double-check your spelling and be absolutely sure you're sending the method call to the correct object.  I'm guessing self.
UITableView *myTable = pointer_to_tableView_instance;
NSIndexPath *indexPath = pointer_to_indexPath_to_check;
[self checkCount:myTable isIndexPathChecked:indexPath];
NSLog(@"%i",checkedRows.count);


text:
Q: Interpretation of PCA I am wondering if there is a practical interpretation of a principal component analysis: Consider you have a data matrix $X\in\mathbb{R}^{N\times p}$ and you perform a principal component analysis where you typically receive certain directions $v_1,...,v_q$, $q<p$, in $\mathbb{R}^N$ that explain the most of the variance in the data. Is there an interpretation of these principal components in terms of the original components, i.e. the variables $x_1,...,x_p$ that constitute the model. Think e.g. of $x_i$ being certain "variables" of a human body such as weight, blood pressure etc. that should be used to predict expected life time. If one now performs a PCA as described a above, one recognizes that certain linear combinations of the columns of $X$ explain most of the variance. If one wants to reduce the model (i.e. reduce the $p$), which variables do you exclude given the information of the PCA?

A: I assume that by "reducing the model," you mean to omit those measurements from the predictive model entirely (such that, for instance, you wouldn't even need to collect information about those variables in the future).
For this kind of goal, ordinary PCA is inappropriate, because each new variable is, as you said, a linear combination of the old variables.
If you want to stay within the realm of principal components analysis, then you should look at Sparse PCA.  Sparse PCA essentially finds an approximation to the true PCA under the constraint that the principal components must be sparse.
However, there are two disadvantages here:

*

*PCA and variants are solutions in the realm of unsupervised learning.  When these methods perform dimensionality reduction, they consider covariance structure, but they completely disregard the utility of the predictor variables for predicting response variable (here, expected life time).

*Moreover, sparsity of the principal components doesn't necessarily map that well to variable reduction.  Even if one of the original variables is dropped from many or almost all of the linear combinations constituting the new variables, you would still have it "in the model" so long as it obtained a non-zero value in a single new predictor variable. (More precisely, if you set up your data matrix such that the rows are samples and the columns are predictors, and you find the SVD of your data matrix as $X=U\Sigma V^T$, then you would need to retain the $i$th  variable in your model so long as the $i$th row of V attained a non-zero value in a single column).

Thus, it sounds like what you really want is the lasso.  In the realm of predictive modeling, the lasso would find a subset of predictor variables that are useful for predicting the response variable.


text:
Q: Terminology: Subsets that are contained in a compact subset I am looking at a subsets of a particular topological space $\mathbf{X}$, and I care about subsets $A$ of $\mathbf{X}$ which are a subset of a compact subset $B$ of $\mathbf{X}$. Since I am not restricting myself to Hausdorff $\mathbf{X}$ here, this notion is not the same as being relatively compact.
My question is whether the notion I am looking at has a name or some "further reading" attached to it.


text:
Q: Spark - SparkSession access issue I have a problem similar to one in
Spark java.lang.NullPointerException Error when filter spark data frame on inside foreach iterator
    String_Lines.foreachRDD{line ->
            line.foreach{x ->
                // JSON to DF Example
                val sparkConfig = SparkConf().setAppName("JavaKinesisWordCountASL").setMaster("local[*]").
                                  set("spark.sql.warehouse.dir", "file:///C:/tmp")
                val spark = SparkSession.builder().config(sparkConfig).orCreate

                val outer_jsonData = Arrays.asList(x)
                val outer_anotherPeopleDataset = spark.createDataset(outer_jsonData, Encoders.STRING())
                spark.read().json(outer_anotherPeopleDataset).createOrReplaceTempView("jsonInnerView")
                spark.sql("select name, address.city, address.state from jsonInnerView").show(false)
                println("Current String #"+ x)
        }
    }

@thebluephantom did explain it to the point. I have my code in foreachRDD now, but still it doesn't work. This is Kotlin and I am running it in my local laptop with IntelliJ. Somehow it's not picking sparksession as I understand after reading all blogs. If I delete "spark.read and spark.sql", everything else works OK. What should I do to fix this?

A:
If I delete "spark.read and spark.sql", everything else works OK

If you delete those, you're not actually making Spark do anything, only defining what Spark actions should happen (Spark actions are lazy)

Somehow it's not picking sparksession as I understand

It's "picking it up" just fine. The error is happening because it's picking up a brand new SparkSession. You should already have defined one of these outside of the forEachRDD method, but if you try to reuse it, you might run into different issues

Assuming String_Lines is already a Dataframe. There's no point in looping over all of its RDD data and trying to create brand new SparkSession. Or if it's a DStream, convert it to Streaming Dataframe instead...
That being said, you should be able to immediately select data from it
// unclear what the schema of this is
val selected = String_Lines.selectExpr("name", "address.city", "address.state")
selected.show(false)

You may need to add a get_json_object function in there if you're trying to parse strings to JSON

A: I am able to solve it finally.
I modified code like this.... Its clean and working.
This is String_Lines data type
val String_Lines: JavaDStream<String>
        String_Lines.foreachRDD { x ->
            val df = spark.read().json(x)
            df.printSchema()
            df.show(2,false)
        }

Thanks,
Chandra