Compound Permissions on windows 2012R2 using Kerberos Armoring

Question: I am trying to setup NTFS Compound Permissions to limit access from certian devices using Kerberos Armoring. As far as I can tell it should be very easy you just set 2 GPO settings. One for the server and then one for the client. Once that is turned on it should then be possible to set a permission on a NTFS file share to set a device permission to only allow access from certain machines. You still have touse group permissions but you can now lock it down to only allow access from certain machines as well.
I have tried setting the 2 GPO settings both for the client and server but on trying to map a network share it always fails with permission denied.
Has any one had any luck with Kerberos Armoring ?
I have tried the following guide Config compound NTFS permissions
But each time I try and connect to the share I get accessed denied.
Comment: Have you looked at the Effective Permissions for the user in question?
Comment: Yes I have checked that and confirmed that it works both with out the advance rule enabled and then enabled and made sure to select the security group the machine was and it shows that it has the correct permission.
Answer: I am late to help you, but the answer is:
Computer Configuration > Policies >
Administrative Templates > System > Kerberos > Support compound authentication


Primefaces menubar vertical separator

Question: I am using PrimeFaces 3.5. There is a vertical seperator in p:toolbar (https://www.primefaces.org/showcase/ui/panel/toolbar.xhtml).
I want to use vertical seperator in p:menubar. When I use the
 tag in p:menubar, it makes a horizontal seperator.
How can i use vertical seperator in p:menubar?
Thanks.
Comment: what is this code? where is output?
Comment: you mean the code in the link?
Answer: I did it with next css:
.ui-menu .ui-separator {
   background: #A8A8A8;
   border: none;
   width: 1px;
   clear: none;
   height: 22px;
   margin: 4px 6px 0;
   box-shadow: none;
}

The key things are width and clear. Height, background color and margin you can adjust for your preferences.
Answer: Try this:

Comment: This is a working solution, but I would remove the `height="22"` and add `style="height: 100% !important;"`
Comment: It is an option. But I chose to leave fixed, due to the adjustment `bottom: -5px`. That is, depending on the value of the `height`, you must change the value of the `bottom` to center.
Answer: Try this:

Comment: that creates a horizontal seperator, not vertical
Comment: Sorry!... what if you try setting style="width:1px; height:100%;"
Comment: i tried it but it doesnt work neither. it creates a 1px horizontal seperator, and rest of the menu elements goes under that seperator
Comment: Try this: style="width:1px; height:100%; float:left;"
Comment: Is your site online so that I can see the problem? Hard to help out like this.
Comment: @tylerdurden use style="width:10px; height:100%; clear: none;"
Answer: It's too late to answer, but hope it helps someone.
With latest versions of primefaces (v10 current) .. For primefaces menubar vertical seperator, you can use

For those who are using lower versions & couldn't find anything ..
Use the trick - Show right border of submenu, it will work like vertical seperator.
Something LIKE

NOTE - I'm using
 for Horizontal seperation of menuitem.

Primefaces menubar vertical separator


I don't know how to represent the curves in the graph below.

Question:
So I am making an Arcade game and I am trying to make the difficulty curve smooth (now the values are hard coded), but I don't know how f(x) or f(g(x)) should look like in order to achieve this.
I found this resource Transforming Game Difficulty Curves usingFunction Composition , but I find it hard to understand as a whole.
I have basic knowledge about functions and calculus but I haven't used them in a while.
Any advice or resource that I can research is well received.
I would love it if any potential solution to my problem comes with some explanation. I want to understand what I am doing 100% .
Thank you for your time and atentintion.
Comment: Sorry, what exactly do you need? I'm not sure what you mean by $\frac{f(x)}{f(g(x))},$ I don't see any other reference to an $f$ or $g.$ If you just want the equation for the baseline curve then that's in the article, about halfway down
Comment: @StephenDonovan Thank you for your response. I meant to write f(x) or f(g(x)). I've seen the equation in the article and the composing operations required to alter the difficulty curve in the desired way. I tried to reproduce them and didn't get the same result. My question's sole purpose was to get a little bit more clarity or a "simpler/more general explanation". I'm sure my rusty math knowledge is one of the reasons why I didn't understand the explanation in the article in the first place .
Answer: A typical function that models this sort of behavior is a logistic function:
$$
f(x) = \frac{1}{1 + e^{-(x - a)/d}}
$$
where $a$ is the "center" of the function (such that $f(a) = \frac12$), and $d$ is a parameter that controls the "steepness" of the transition from small values of $f$ to large values of $f$ (smaller $d$ means a "steeper" transition.)
Here's a Desmos calculator that allows you to play around with the parameters and see what works best for your application.


How can I display an image on top of a generated heatmap?

Question: I am trying to use heatmap.js to create a heatmap, following the instructions from this post: How to render heatmap.js on an image?
All of my code is identical to the one at that example. Just a simple generated heatmap with a background image added in CSS. Please see this screenshot from that post :

But I want to display an image on top of the heatmap, so a foreground image instead of a background image.
I have tried using plotly, but unfortunately this is intended to run on an ESP-32, with SPIFFS, so I am extremely limited to space and processing power. Even after I used the partial bundle to get the file size down small enough, the web page just simply wouldn't load. I'd really prefer to use heatmap.js if possible anyways, since it has a much smaller footprint.
To further explain what I'm trying to do, I want to put this half-transparent image on top of the generated heatmap:

So the final desired result would look like this, displaying only the heatmap inside the transparent part of the foreground image:

All the code I am using is identical to the previously mentioned post, just a simple generated heatmap with a background image added in CSS. I also used this documentation here to build an example heatmap, https://www.patrick-wied.at/static/heatmapjs/docs.html
Is there any easy way to do this using HTML/CSS/JavaScript?
Answer: I don't know heatmap so cannot test this, but from the info given in the question if the placing of a background image works as shown then the placing of a foreground image should be possible.
What we do is style an after pseudo element on #heatmap, give it the correct dimensions, put it above the heatmap element using z-index and give it the required image as its background. The image should then appear to be sitting above the heatmap element - I assume obscuring part of it.
You need to make sure that the heatmap element is positioned so its after pseudo element knows where to position itself in relation.
<code>#heatmap {
  width: as you want
  height: as you want
  background-image: if you still want it to have one
  any other styling you want heatmap to have

  position: relative;
}

#heatmap::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1; /* make sure this is big enough - higher than the heatmap's z-index */
  background-image: url(the image you want to be in the foreground);
  background-size: cover; /* or contain depending on what you want */
  background-repeat: no-repeat;
  background-position: center center; /*or wherever you want it */
}
</code>
}
Comment: Thanks for the suggestion! I'll give it a try and post back here with the results!


For each delegated item in FolderListModel do

Question: I have a QML app that I currently lists files in a directory. I now want to add a way to run a function for each delegates item eg. for each file in the set dir.
Or really each file through a function (adding them to a local db)
How do I do that using QML?
Answer: You can use the Component.onCompleted
However this may be called multiple times, so i wouldn't recommend you update databases using this.
(I hope you have a plugin to update the DB.)
import QtQuick 1.0
import Qt.labs.folderlistmodel 1.0

ListView {
    width: 200; height: 400

    FolderListModel {
        id: folderModel
        nameFilters: ["*.qml"]
    }

    Component {
        id: fileDelegate
        Text {
            text: fileName
            Component.onCompleted: {
                //DO WHATEVER YOU WANT HERE
                console.log("process the file"+fileName);
            }
        }
    }

    model: folderModel
    delegate: fileDelegate
}

Original code taken from http://doc.qt.digia.com/4.7/src-imports-folderlistmodel.html and modified to suit the answer
Comment: @DanielHolm : ListView has dynamic loading. If you want to manage loading yourself, use Repeater instead.
Comment: Thank you, that did indeed help. The thing is, though, that it doesn't load all of the items at once, When I'm scrolling trough the list, more items gets loaded progressively, and scrolling up again prints out items that's already been handled. Just like you mention. But I Want all the items to be run trough a function once.

How?


canvas is stretching when changing device type in dev tool

Question: I have next canvas with some content:

class ExpectedLifespanRound {
    constructor() {
      // max lifespan that is possible
      this.lifespanMax = 125

      // expected lifespan block
      this.expLsBlock = document.getElementById("expected-lifespan-block")

      // set style for the block
      this.style = this.expLsBlock.style
      this.style.padding = "20px"
      this.style.display = "flex"
      this.style.width  = "320px"
      this.style.height = "406px"
      this.style.borderRadius = "20px"
      this.style.backgroundColor = "white"

      // set canvas style
      this.can = this.initCanvas("expected-lifespan-block")
      this.can.style.backgroundColor = "white";
      // - 40 is padding
      this.can.style.width = this.expLsBlock.outerWidth - 40 + "px"
      this.can.style.height =this.expLsBlock.outerHeight - 40 + "px"
      this.can.style.marginLeft = "8px"
      this.expLsBlock.appendChild(this.can);
      this.ctx = this.can.getContext("2d")
      // set gradient for arc
      this.gradient = this.ctx.createLinearGradient(320, 0, 0, 406);
      this.gradient.addColorStop("0.3", "#ABB8FF")
      this.gradient.addColorStop("0.7" ,"#ABF0FF")
    }
    clearCanvas() {
      // clear canvas
      this.ctx.clearRect(0, 0, 320, 406)
      this.ctx.beginPath();
      this.ctx.globalCompositeOperation = "source-over";
      this.ctx.globalAlpha = 1;
      this.ctx.closePath();
    }
    create(years) {
      // title
      this.ctx.save()
      this.clearCanvas()
      this.ctx.fillStyle = "black"
      this.ctx.font = "bolder 18px Arial";
      this.ctx.fillText("Ожидаемая", 100, 30)
      this.ctx.fillText("продолжительность жизни", 32, 56)
      this.ctx.restore()
      // arc
      this.ctx.save()
      this.ctx.fillStyle = this.gradient
      this.ctx.strokeStyle = this.gradient
      this.ctx.lineWidth = 35
      this.ctx.arc(150, 250, 125, Math.PI - (1.5 * Math.PI/this.lifespanMax)*years, 1.5 * Math.PI)
      this.ctx.font = "bold 55px Arial"
      var x = 120
      if (years >= 100) {x = 105}
      this.ctx.fillText(years, x, 245)
      this.ctx.font = "bold 36px Arial"
      this.ctx.fillText("лет", 120, 285)
      this.ctx.stroke()
      this.ctx.restore()
    }
    refresh(years) {
      this.create(years)
    }
    initCanvas(blockForCanvas) {
        // create high dpi canvas and put it in the block

        // return pixel ratio
        var getRatio = function () {
          var ctx = document.createElement("canvas").getContext("2d");
          var dpr = window.devicePixelRatio || 1;
          var bsr =
            ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio ||
            1;

          return dpr / bsr;
        };
        // return high dots per inch canvas
        var createHiDPICanvas = function (w, h) {
          var ratio = getRatio();
          var chart_container = document.getElementById(blockForCanvas);
          var can = document.createElement("canvas");
          can.style.backgroundColor = "white";
          can.width = 320 * ratio;
          can.height = 406 * ratio;
          can.style.width = w + "px";
          can.style.height = h + "px";
          can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
          chart_container.appendChild(can);
          return can;
        }
        var canvas = createHiDPICanvas(this.scaleWidth, this.scaleHeight)
        return canvas
     }
  }

  var expLsRound = new ExpectedLifespanRound()
  expLsRound.create(95)
body {
    background-color:grey;
}

It is ok on my 1920x1080 screen, but when I switch type to mobile (line iphone 6, ipad or any other) - it is strating to stretch in not appropriate way. You can test it in chrome dev tools, or take a look on the pictures I tave taken:
normal:

stretched after switching to another device using dev tools:

How to avoid such a stretching and let this canvas be the same size no depending what device screen user has?
Answer: Just needed to replace 2 functions out if innerCanvas function and it does not stretch anymore


GAE Go 1.11 instance startup issues when migrating from flex to standard

Question: I am in the process of migrating a simple app using the Go 1.11 runtime from the AppEngine flex environment to the standard environment because flex got shockingly expensive for my low-traffic site (and standard wasn't available for this runtime until recently). Every time GAE hits the /_ah/start endpoint for my app it logs a 301 and the following error: Process terminated because it failed to respond to the start request with an HTTP status code of 200-299 or 404.
My server does have a handler for /_ah/start that simply writes a 200 and works fine locally. I also tried adding a handler for all routes in app.yaml just to make sure requests to the AppEngine load balancer are actually being routed to my server, but it still isn't working. I know from the service logs that my server is starting and listening on the correct port but it gets restarted over and over and can't actually handle any requests because of this issue with the GAE start request.
Here's my app.yaml:
runtime: go111
instance_class: B1
basic_scaling:
  max_instances: 1
handlers:
- url: /.*
  script: auto

Edit: Here's a screenshot of the logs
Comment: Show messages logged for the application and the code that runs the net/http server.
Comment: Edited my original post to include a screenshot of the logs!
Comment: The application responds to /_ah/start with a redirect (status 301).  How did you determine that the application responds with a 200 running locally? Does the application redirect any requests?
Comment: When I run my server locally I am able to hit `/_ah/start` and it returns a 200. I am not sure how to mimic the setup of the actual AppEngine environment locally so that basically just validates that my server works as expected in a more general sense, not that it works in the context of AppEngine. I have no idea where the redirect is coming from when I deploy to GAE, but it's interesting that that first error log happens before my server logs anything, meaning it's trying to hit that endpoint before running main.go.
Comment: My server only redirects http traffic to https, which I added when I was using the flex environment. I wonder if that's the culprit? I'll try removing that middleware and see what happens.
Comment: The application must serve traffic over http when running in the standard environment.  Remove the redirect.  If that does not work, the update the question with the code that runs the http/server (as requested earlier) and anything else that might be relevant.
Comment: Removing the https redirect did the trick! Thanks for pointing me in the right direction. I didn't think that could be the issue because the logs seemed to indicate that it was making that request and being redirected before even starting my server. Also my bad re: the code - I misread your comment as just asking for the _logs_ from both places, hence that screenshot.
Answer: The application redirects http to https per discussion in the comments.
An application running in the standard environment must serve http.  The App Engine infrastructure handles https.
Fix by removing the redirect from http to https.


Does the series of octaves (1, 2, 4, 8) have a name?

Question: We call any series of frequencies which are multiples of 1,2,3,4,5... etc a harmonic series, and they define the notes (for example) C0-C1-G1-C2-E2-G2-Bb2-...
Is there a name for the series of frequencies 1,2,4,8,16... multiples of which would define the octaves C0-C1-C2-C3-C4-C5...?
Answer: Not sure I'm interpreting your question correctly, but you seem to be asking about about the mathematical relationship between the frequency (Hz) of a pitch and the sequences of pitches that we organize into scales and octaves.
So at the risk of being too pedantic, we map frequencies to pitches using a logarithmic scale (in base 2).
Because our ears don't perceive pitch distance linearly with frequency, as the wikipedia article for "12-tone equal temperament" says:

the ratios of the frequencies of any adjacent pair of notes is the same, and, as pitch is perceived roughly as the logarithm of frequency, equal perceived "distance" from every note to its nearest neighbor.

So to answer your question, an octave is a unit of frequency used with logarithm base-2. (A semitone is one twelfth of an octave. A cent is one hundredth of a semitone.) The "series" of octaves itself would just be referred to as a base-2 logarithmic scale.
Answer: If I understand your question right these are the names of the different octavas:
C0 - B0: sub-contra octave (A0 is the lowest pitch on a full piano)
C1 - B1: contra octave
C2 - B2: great octave
C3 - B3: small octave
C4 - B4: one-line octave, or 2nd small octave (contains both middle C and A440)
C5 - B5: two-line octave, or 3rd small octave
C6 - B6: three-line octave, or 4th small octave
C7 - B7: four-line octave, or 5th small octave
C8 - B8: five-line octave, or 6th small octave (C8 is the highest pitch on a full piano)
source:
https://www.liveabout.com/pitch-notation-and-octave-naming-2701389
As the following table shows there are different pitch names used in different countries (languages) and the naming in midi is a special kind of numbering 1-128
Comment: Sorry, no this is not what I meant. I now suspect the answer is "geometric series" though not sure whether music theory uses this term?
Comment: Well, I think this might fit! ;
https://www.youtube.com/watch?v=2TCDiK7GpNM


Number of Unique Values Using CrossFilter

Question: CrossFilter/JS newbie here.
This question pretty much describes exactly what I'm trying to do but there doesn't seem to be a solution using CrossFilter:
How to return the number of unique values by category using crossfilter?
I have data with
var va = [{
date: "2014-10-01",
id: "1"},
{
date: "2014-10-02",
id: "1"},
{
date: "2014-10-03",
id: "1"},
{
date: "2014-10-04",
id: "1"},
{
date: "2014-10-05",
id: "1"},
{
date: "2014-10-01",
id: "2"},
{
date: "2014-10-02",
id: "2"},
{
date: "2014-10-03",
id: "2"},
{
date: "2014-10-04",
id: "1"},
{
date: "2014-10-01",
id: "3"},
{
date: "2014-10-02",
id: "3"},
{
date: "2014-10-03",
id: "1"},
{
date: "2014-10-01",
id: "4"},
{
date: "2014-10-02",
id: "1"},
{
date: "2014-10-01",
id: "5"}
}

I am trying to get the number of unique id's per date from this. I would like to group by date and basically have a count of unique id's for that particular date:
"2014-10-01" - 5
"2014-10-02" - 3
"2014-10-03" - 2
"2014-10-04" - 1
"2014-10-05" - 1

Currently, I'm trying to follow the answer given in this question
Crossfilter reduce :: find number of uniques
to do the following:
//Create a Crossfilter instance
var ndx = crossfilter(va);

//Define dimensions
var date_dim = ndx.dimension(function(d) {
    return d["date"]; });

//total number of ids per date
var num_ids_by_date = date_dim.group();

//unique number of ids per date
var num_uniq_ids_by_date = date_dim
    .group()
    .reduce(
        function (p, d) {
            if(d.id in p.ids){
            }
            else{
                p.ids[d.id] = 1;
            }
            return p;
        },

        function (p, d) {
            p.ids[d.id]--;
            if(p.ids[d.id] === 0){
                delete p.ids[d.id];
            }
            return p;
        },

        function () {
            return {ids: {}};
        })

When I look in the num_uniq_ids_by_date object and call num_uniq_ids_by_date.reduceCount().top(1), it seems to be the same output as num_ids_by_date.top(1).
So, I still don't seem to be getting what I'm looking for and have been stumped for a while.
Any suggestions? Thanks in advance!
Comment: Seems like you aren't incrementing the counter on add, which will cause you problems. If you put together a working example, it will be easier to diagnose the issue. You could also use a library like Reductio, which supports this: https://github.com/esjewett/reductio#aggregations-standard-aggregations-exception-aggregation (plugging my own library, sorry)
Comment: Thanks for the response Ethan. The reason I don't increment the counter on add is because I don't entirely care about the amount of each particular id, I just would like the number of unique ids. Also, thanks for the library suggestion, I'll definitely check it out. If possible, I would like to keep it to just the CrossFilter library for now while I'm still learning :)
Comment: If you don't increment on add, but you decrement on remove (which you're doing), you're going to get into an inconsistent state pretty fast. I didn't see your actual question though. Calling `num_uniq_ids_by_date.reduceCount()` wipes out all your custom group reducers. Just call `num_uniq_ids_by_date.top(1)`.
Comment: Oops, that was a mistake on my part - thanks for pointing it out. Thanks for the suggestions! I was actually able to get it. I'll be sure to add my answer.
Answer: Okay I was able to get it.
What I ended up doing is the following:
//Create a Crossfilter instance
var ndx = crossfilter(va);

//Define dimensions
var date_dim = ndx.dimension(function(d) {
    return d["date"]; });

var num_unique_ids_by_date = date_dim
    .group()
    .reduce(
        function (p, d) {
            if(d.id in p.ids){
                p.ids[d.id] += 1
            }
            else{
                p.ids[d.id] = 1;
                p.id_count++;
            }
            return p;
        },

        function (p, d) {
            p.ids[d.id]--;
            if(p.ids[d.id] === 0){
                delete p.ids[d.id];
                p.id_count--;
            }
            return p;
        },

        function () {
                return {ids: {},
                id_count: 0};
            });

This gives me a total number of unique id's as well as the total numer of occurences of each id.
Then when I want to display this in my bar graph using dc.js, I go ahead and use the following code.
var minDate = date_dim.bottom(1)[0]["date"];
var maxDate = date_dim.top(1)[0]["date"];

var timeChart = dc.barChart("#time-chart");

timeChart
    .width(1500)
    .height(400)
    .margins({top: 10, right: 50, bottom: 30, left: 50})
    .dimension(date_dim)
    .group(num_unique_ids_by_date)
    .valueAccessor(function (d) {
        return d.value.id_count;
    })
    .transitionDuration(500)
    .x(d3.time.scale().domain([minDate, maxDate]))
    .elasticY(true)
    .elasticX(true)
    .xAxisLabel("Year")
    .yAxis();

dc.renderAll();


Find $f(n)$ where $f(2n)= 2f(n)+ 1$

Question: A function $f:\mathbb{N}\to\mathbb{N}$ satisfies the following for all $n$ natural.
$f(1)= 1$
$f(f(n))= n$
$f(2n)= 2f(n)+ 1$
Find $f(n)$
I'm really stuck, new to functions
All I've gotten is :
$f(2(f(f(n)))= 2(f(f(f(n)))+ f(1),$
which isn't very helpful..
Comment: Can you find the values of $f(2),f(3),f(4),f(5)$?
Comment: It may be helpful to think of $n$ written in binary and consider the action of $f$ on the bits. (separate the first bit from the rest)
Answer: You know that $f\left(1\right)=1$. Then
$$
f\left(2\right)=2f\left(1\right)+1=3
$$
$$
f\left(4\right)=2f\left(2\right)+1=7
$$
$$
f\left(8\right)=2f\left(4\right)+1=15
$$
You can then show that
$$
f\left(2^n\right)=2^{n+1}-1
$$
Then what about odd numbers ?
$$
f\left(3\right)=f\left(f\left(2\right)\right)=2
$$
Then $$f\left(6\right)=2f\left(3\right)+1=5$$
$$
f\left(5\right)=f\left(f\left(6\right)\right)=6
$$
I let you continue to find a pattern, knowing how to compute $f\left(n\right)$ for all $n$.
Answer: Assume* $f$ is uniquely defined and consider the function $g : \mathbb{N} \to \mathbb{N}$ defined by $$g(1) = 1 \\ g(2n) = 2g(n)+1 \\ n\geq 1 \implies g(2n+1) = 2g(n)$$
then it's not hard to see that $g$ satisfies $g(g(n)) = n$ so that $f=g$.
The reason this characterization is nicer is that it can be described simply in terms of the binary expansion of $n$.  That is, to find $g(n)$, write $n$ in binary and flip every bit other than the leading bit.  That is, we keep the most significant $1$, and every less significant bit is flipped, $1$ becomes $0$ and $0$ becomes $1$.
This may be written succinctly as $$f(n) = g(n) = 3\cdot 2^{\lfloor\log_2 n\rfloor}- n - 1$$

*To show $f$ is uniquely determined, it's convenient to define $N(n) = \lfloor\log_2n\rfloor$ and then induct on $N(n)$ to show $f(n)$ is uniquely determined and $N(f(n))=N(n)$.
The base case of $N(n)=0 \iff n=1$ is immediate from $f(1)=1$.
For the inductive step, first assume $n>1$ is even, so that $n=2m$ where $N(m) = N(n)-1$. Then $f(n) = 2f(m)+1$ is uniquely determined and $$N(f(n)) = N(f(2m)) = N(2f(m)+1) = 1+N(f(m)) = 1+N(m) = N(n).$$  Here, we also note that $f(n)$ is odd, where $f(f(n)) = n$ and $N(f(f(n))) = N(n) = N(f(n))$.
This effectively finishes the inductive step, because $N^{-1}[N(n)] = \{k \in \mathbb{N} : N(k) = N(n)\}$ has an equal number of odd numbers and even numbers.  Since $f$ is injective and the above argument can show $k\in N^{-1}[N(n)]$ is even implies $f(k) \in N^{-1}[N(n)]$ is odd, it follows that every odd number in $N^{-1}[N(n)]$ is the image of an even number in $N^{-1}[N(n)]$.
Answer: WLOG Let $f(m)=g(m)+b$
$$1=f(2n)-2f(n)=g(2n)+b-2(g(n)+b)=g(2n)-2g(n)-b$$
Let $b=-1$  to find $$g(2n)=2g(n)$$
$1=f(1)=g(1)+(-1)\implies g(1)=2$
$$g(2^r)=2g(2^{r-1})=\cdots=2^rg(1)=2^r(2)$$

Find $f(n)$ where $f(2n)= 2f(n)+ 1$


Vertical text in IE7, IE8, IE9, and IE10 with CSS only

Question: Does anyone know how to successfully implement vertical text in IE7, IE8, IE9, and IE10 with CSS only?  (by vertical text, I'm referring to text being rotated counterclockwise 90 degrees)
This is what I have implemented today, which I think should be correct:
.counterclockwise-text {

/* Chrome/Safari */
-webkit-transform: rotate(-90deg);
-webkit-transform-origin: 50% 50%;

/* Firefox */
-moz-transform: rotate(-90deg);
-moz-transform-origin: 50% 50%;

/* IE9 */
-ms-transform: rotate(-90deg);
-ms-transform-origin: 50% 50%;

/* This should work for IE10 and other modern browsers that do not need vendor prefixes */
transform: rotate(-90deg);
transform-origin: 50% 50%;

/* IE8 or less - using the "\9" CSS hack so that other browsers will ignore these lines */
zoom: 1\9;
writing-mode: tb-rl\9;
filter: flipv fliph;

}

However, IE10 is not ignoring the "\9" CSS hack -- it will pick up those values and rotate the text another 90 degrees.  A useful solution would be a way to do vertical text in IE8 and below that will not be picked up by IE10.  I really want to avoid having an IE8-only stylesheet, or having a media query to detect IE10.  I'm just looking for a way to modify the CSS above to have vertical text in all browsers.  Thank you!
EDIT:
For what it is worth, I also tried the code below that uses a filter to rotate the text.  This may work for most cases, but in my instance a lot of the text is cut off by the restricted (non-rotated?) constrains of the wrapping element.
.counterclockwise-text {

/* Chrome/Safari */
-webkit-transform: rotate(-90deg);
-webkit-transform-origin: 50% 50%;

/* Firefox */
-moz-transform: rotate(-90deg);
-moz-transform-origin: 50% 50%;

/* IE9 */
-ms-transform: rotate(-90deg);
-ms-transform-origin: 50% 50%;

/* IE10 and other modern browsers that do not need vendor prefixes */
transform: rotate(-90deg);
transform-origin: 50% 50%;

/* IE8 */
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

/* IE7 or less */
*zoom: 1;
*writing-mode: tb-rl;
*filter: flipv fliph;

}

I still have not found a way to do this with pure CSS where IE10 and IE8 are happy.
Answer: Here is pure CSS ( + 1 extra div for every text ) solution
Works for all IE versions IE7-10
/**
 * Works everywere ( IE7+, FF, Chrome, Safari, Opera )
 */
.rotated-text {
    display: inline-block;
    overflow: hidden;
    width: 1.5em;
}
.rotated-text__inner {
    display: inline-block;
    white-space: nowrap;
    /* this is for shity "non IE" browsers
       that doesn't support writing-mode */
    -webkit-transform: translate(1.1em,0) rotate(90deg);
       -moz-transform: translate(1.1em,0) rotate(90deg);
         -o-transform: translate(1.1em,0) rotate(90deg);
            transform: translate(1.1em,0) rotate(90deg);
    -webkit-transform-origin: 0 0;
       -moz-transform-origin: 0 0;
         -o-transform-origin: 0 0;
            transform-origin: 0 0;
   /* IE9+ */
   -ms-transform: none;
   -ms-transform-origin: none;
   /* IE8+ */
   -ms-writing-mode: tb-rl;
   /* IE7 and below */
   *writing-mode: tb-rl;
}
.rotated-text__inner:before {
    content: "";
    float: left;
    margin-top: 100%;
}

/* mininless css that used just for this demo */
.container {
  float: left;
}

HTML example
<!DOCTYPE html>

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

Easy

Normal

Hard

source: https://gist.github.com/obenjiro/7406727
Comment: Works well.  I tested from IE5, IE7-IE11.
Answer: You should use conditionnal comment for older IEs .
That what they are meant for and it will do no hurts nor hack (ing head) s :)
Comment: I understand that conditional comments may be a better solution overall, but I asked for a solution using pure CSS.
Answer: Having the same problem, but with additional bad readability of the rotated text, I would advice not to use the:
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
for IE9 or IE 8.
That's, what worked for me:
p.css-vertical-text {
    color:#333;
    border:0px solid red;
    writing-mode:tb-rl;
    -webkit-transform:rotate(90deg);
    -moz-transform:rotate(90deg);
    -o-transform: rotate(90deg);
    white-space:nowrap;
    display:block;
    bottom:0;
    width:20px;
    height:20px;
    font-family: 'Trebuchet MS', Helvetica, sans-serif;
    font-size:24px;
    font-weight:normal;
    text-shadow: 0px 0px 1px #333;
}

from http://scottgale.com/css-vertical-text/2010/03/01/


Distribution function or density in Mixed Distribution EM

Question: In this calculation
https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm#E_step
a probability, $P(Z_i = j|X_i=x_i;\theta^{(t)})$ is evaluated using bayes theorem, and then each of the probabilites is written as densities (as opposed to the integrals of densities, which probabilites are).
I should clarify. We have
$$P(Z_i = j|X_i=x_i;\theta^{(t)}) = \frac{P(X_i=x_i|Z_i = 1,\theta^{(t)})P(Z_i = 1)}{P(X_i|\theta^{(t)})} = \frac{f(x_i,\mu_j,\Sigma_j) \tau_j}{f(x_i,\mu_1,\Sigma_1) \tau_1 + f(x_i,\mu_2,\Sigma_2) \tau_2} $$
which implies that $$P(X_i=x_i|Z_i = 1,\theta^{(t)}) = f(x_i,\mu_j,\Sigma_j)$$
I feel like it should rather be $$P(X_i=x_i|Z_i = 1,\theta^{(t)}) = \int_{-\infty}^{x_i} f(s,\mu_j,\Sigma_j)ds$$
So why is the probability equal to the density, and not the integral of the density?
Answer:
Since the OP is refering to
  the full E-formula from Wikipedia, here is the E-step described in
  Wikipedia for a mixture of two Gaussian distributions (with a typo on the side):
\begin{align}Q(\theta|\theta^{(t)}) &=
 \operatorname{E}_{\mathbf{Z}|\mathbf{X},\mathbf{\theta}^{(t)}} [\log
  L(\theta;\mathbf{x},\mathbf{Z}) ] \\ &=
  \operatorname{E}_{\mathbf{Z}|\mathbf{X},\mathbf{\theta}^{(t)}} [\log
  \prod_{i=1}^{n}L(\theta;\mathbf{x}_i,\mathbf{z}_i) ] \\ &=
  \operatorname{E}_{\mathbf{Z}|\mathbf{X},\mathbf{\theta}^{(t)}}
  [\sum_{i=1}^n \log L(\theta;\mathbf{x}_i,\mathbf{z}_i) ] \\ &=
  \sum_{i=1}^n\operatorname{E}_{\mathbf{Z}|\mathbf{X};\mathbf{\theta}^{(t)}} [\log L(\theta;\mathbf{x}_i,\mathbf{z}_i) ] \\ &= \sum_{i=1}^n
  \sum_{j=1}^2 \overbrace{P(Z_i =j | X_i = \mathbf{x}_i; \theta^{(t)}) \log
  \underbrace{L(\theta_j;\mathbf{x}_i,\mathbf{z}_i)}_{\text{should be}\\ L(\theta;\mathbf{x}_i,j)}}^\text{see below for discussion of the typo there} \\ &= \sum_{i=1}^n \sum_{j=1}^2
  T_{j,i}^{(t)} \big[ \log \tau_j  -\tfrac{1}{2} \log |\Sigma_j|
  -\tfrac{1}{2}(\mathbf{x}_i-\boldsymbol{\mu}_j)^\top\Sigma_j^{-1} (\mathbf{x}_i-\boldsymbol{\mu}_j) -\tfrac{d}{2} \log(2\pi) \big]
  \end{align}

The conditional probabilities $\mathbb{P}(Z_i=j|X_i,\theta^{(t)})$ appear in the E-step of the EM algorithm because the E-step purpose is to produce the expectation of the complete(d) log-likelihood $\log\,L(\theta;x,z)$ conditionally on the observables $(x_1,\ldots,x_n)$. Hence
\begin{align*}
\overbrace{\mathbb{E}_{Z|X=x,\theta^{(t)}}}^{\text{i.e., expectation}\\\text{conditional on}\\X=x\ \text{and for the}\\\text{value $\theta^{(t)}$ of $\theta^{(t)}$}}\Big[\log\,\overbrace{L(\theta;x,Z)}^{\text{joint density of}\\ \text{sample of }(X_i,Z_i)}\Big]
&= \mathbb{E}_{Z|X=x,\theta^{(t)}}\overbrace{\left[\log\,\prod_{i=1}^n L(\theta;x_i,Z_i)\right]}^{\text{independence of the pairs}\\(X_i,Z_i)\ \text{for}\ i=1,\ldots,n}\\
&= \sum_{i=1}^n \mathbb{E}_{Z|X=x,\theta^{(t)}}\left[\log\, L(\theta;x_i,Z_i)\right]\\
&= \sum_{i=1}^n \mathbb{E}_{Z_i|X_i=x_i,\theta^{(t)}}\left[\log\, L(\theta;x_i,Z_i)\right]\\
&= \sum_{i=1}^n \underbrace{\sum_{j=1}^k \mathbb{P}(Z_i=j|X_i=x_i,\theta^{(t)})\log\, L(\theta;x_i,j)}_{\text{definition of conditional expectation}}
\end{align*}
Note that there is a typo in the line before last in the Wikipedia derivation of $Q(\theta|\theta^{(t)})$, which should be
$$\sum_{i=1}^n \sum_{j=1}^2 \mathbb{P}(Z_i=j|X_i=x_i,\theta^{(t)})\log\, \overbrace{L(\theta;x_i,j)}^{\text{since $Z_i=j$}\\\text{and $\theta$ remains}\\\text{a free variable}}$$rather than$$\sum_{i=1}^n \sum_{j=1}^2 \mathbb{P}(Z_i=j|X_i=x_i,\theta^{(t)})\log\, L(\theta_j;x_i,z_i)$$
Or, with the original notations there,
$$\sum_{i=1}^n \sum_{j=1}^2 P(Z_i =j | X_i = \mathbf{x}_i; \theta^{(t)}) \log L(\theta;\mathbf{x}_i,j) \\
$$rather than
$$\sum_{i=1}^n \sum_{j=1}^2 P(Z_i =j | X_i = \mathbf{x}_i; \theta^{(t)}) \log L(\theta_j;\mathbf{x}_i,\mathbf{z}_i) \\
$$
As for the question about using the density and not the cdf in the likelihood, this is a generic one. The likelihood of the pairs $(X_i,Z_i)$ is the product of the densities, by definition of the likelihood function. The notation $$P(X_i=x_i|Z_i = 1,\theta^{(t)})$$ is incorrect when $X_i$ is a continuous random variable, but is not to be confused with $$P(X_i\le x_i|Z_i = 1,\theta^{(t)})$$
Comment: Apologies for being unclear, I have edited the original question to be more precise.
Comment: Becuse it did not adress my question! You misunderstood what I asked for, and answered the second part of the calculation, not the first part which I asked about. The question was about why is a probabilty equal to a density, not about why they appear in the formula. But your second part now adresses my question, thank you!


learning_curve() with holdout set

Question: Is there any way to plot the learning curves of training and validation data, when validation data does already exist as a holdout set?
sklearn learning_curve() does not offer such a paramater, as far as I can tell.
Answer: You can set the parameter cv as a PredefinedSplit (or just a length-1 iterator of train/test indices).  See the description of cv in the documentation.

learning_curve() with holdout set


What is the boundary at infinity in the hyperboloid model of the hyperbolic plane?

Question: The boundary of the upper half-plane $\mathbb{H}$ model of the hyperbolic plane is the extended real line $\overline{\mathbb{R}}= \mathbb{R} \cup \{ \infty \}$.
What is the boundary of the hyperboloid model of the hyperbolic plane? Is it the positive light cone $L^+$?
Comment: It is the light cone's directions, not the cone, i.e. $\mathbb{P}L^+=L^+/\mathbb{R}^+\cong S^{n-1}$.
Comment: @user10354138 That's a good answer, so it might as well be an answer, not a comment.
Answer: The boundary is not the light cone $L_+$ itself, but the set of directions of the light cone, or equivalently the projectivization $L_+ / \mathbb R_+ \cong S^{n-1}$.


GWT javascript does not catch exception

Question: When converting an Applet with the GWT framework I stumbled over this piece of code, where the author finds out the length of the array imageNames in a loop until an out-of-bounds exception occurs. It worked in the Applet, but not in GWT! After GWT compile the browser loops and does not show a reaction. Replacing Exception by JavaScriptException does not help.
    boolean error=false;
    int n_img = -1;
    String tmp;
    String[] imageNames;
    ...
    while (!error) {
        try {
            tmp = imageNames[(++n_img)];
        } catch (Exception e) {
            error = true;
        }
    }

Do you have any idea, how to catch the out-of-bounds-exception in GWT?
Comment: Well, that's the strangest loop I ever saw! This code can easily replaces with "for each". No need to handle exception! Or fori and using imageNames.lenght. And if you are not sure if imageNames is null, check it before.
Answer: This is one of the "shortcomings" of GWT - in the name of performance, extra emulation is not added to solve what should be an entirely avoidable bug. This is one of the most overt examples though.
First, recall that JS, for better or worse, is totally okay with you assigning values to indexes in Arrays that it may not have room for - you can use this to make a sparse array by skipping far past the end of the array, you can even assign to negative indexes.
On top of that Array feature, the Java array is implemented, and rather than read the expression array[n] and rewrite it to check n against the length before assigning (requiring two more checks for each read or write), it leaves it as-is.
And, since typically array operations like this are in a loop (such as in your code), this change would make every step through the loop faster, since it is trivial to do the bounds check as part of the loop condition.
And, typically Java users aren't writing array code on a regular basis, but leaning on ArrayList or the like - which does do these checks (though they can be disabled or reduced to improve runtime performance).
One more reason this isn't so bad: Sometimes you'd like to write in Java, and expect (not unreasonably) that you are actually acting on JS output. This allows for tricks like this:
array[array.length] = item;

to grow the array with each item. Obviously will fail in a JVM, but this is natural code to write in JS.
Finally, unless I'm very much mistaken, that isn't even a very optimized way to write that loop, even if throwing and catching that exception is cheaper than just doing a < check each step of the loop - we're still checking if !error is true each step! Instead, just make the loop run forever, and actually exit it, instead of requiring an additional boolean to track what the exception already tracks for you:
// just like the code in the question, do not do this,
// this is just an example of how to get "too clever"
try {
  while (true) {
    tmp = imageNames[(++n_img)];
  }
catch (Exception ignore) {
  // do nothing, something "exceptional" but totally expected has occurred
}

Answer: So, thank you for the comment and the explaining answer. It will help me in further development. I now changed the faulty loop this way
   while (!error) {
        try {
            tmp = this.imageNames[(++n_img)];
            error=(n_img==imageNames.length); // correct severe bug
        } catch (Exception e) {

            error = true;
        }
    }

GWT javascript does not catch exception


one enter keypress runs JavaScript keypress event handler code twice

Question: Why does one enter keypress run through this code twice?
I've tried keypress, keydown and also event.preventdefault() to no avail.
$(document).keydown(function (e) {
    if (e.which == 13) {
       alert("0")
        var focado = document.getElementById(document.activeElement.id), fim = focado.id.substring(1),
            inicio = focado.id.substring(0, 1),
            fimseg = fim,
            anterior = inicio + (fim - 1),

        alert("1")

        alert("focado " + focado.id + " fim " + fim + " inicio " + inicio + " fimseg " + fimseg + " anterior " + anterior);
    }
});

Only after giving these 3 messages twice would it continue to the remaining code (not shown).
UPDATE:
This is the full program:
$(document).keydown(function (e) {
    if (e.which == 13) {

        var focado = document.getElementById(document.activeElement.id), fim = focado.id.substring(1),
            inicio = focado.id.substring(0, 1),
            fimseg = fim,
            anterior = inicio + (fim - 1),
            seguinte = focado;

        switch (fim) {
            case "1":
                fimseg = "2"
                break;
            case "2":
                fimseg = "3"
                break;
            case "3":
                fimseg = "4"
                break;
            case "4":
                fimseg = "5"
                break;
        }
      seguinte = inicio + (fimseg);

        if (seguinte == "p5") {
            seguinte = "a1";
        }

        alert("focado " + focado.id + " fim " + fim + " inicio " + inicio + " fimseg " + fimseg + " anterior " + anterior + " seguinte " + seguinte);

        if (focado.value.length == 0) {//enter no vazio

           alert("aqui")
            if (fim != 1) {//se não é p1 nem a1
                alert("1")
                if (document.getElementById(anterior).value.length == 0) {//se anterior vazio
                    alert("2")
                    document.getElementById(anterior).focus()
                } else {//se anterior não vazio
                    alert("3")
                    if (seguinte == "a5") {//se é a4
                        alert("4")
                        document.getElementById("btnSubmit").click();
                    } else {//se nºao é a4
                        alert("5")
                        document.getElementById(seguinte).focus()
                    }
                }

            } else {//é p1 ou a1

                document.getElementById(focado.id).focus()  //foca no próprio

            }
        } else {
                            if (focado.value.length < 7 || (isNaN(focado.value))) {

                document.getElementById(focado.id).innerHtml = "";
                if (anterior.value.length == 0) {

                    document.getElementById(anterior).focus()
                } else {

                    document.getElementById(focado.id).focus()
                }
            } else {

                if (fim != 1) { //não é p1 nem a1

                    if (document.getElementById(anterior).value.length ==0) {

                        document.getElementById(anterior).focus()
                    } else {

                        if (seguinte == "a5") {

                            document.getElementById("btnSubmit").click();
                        } else {

                            document.getElementById(seguinte).focus()

                        }
                    }
                } else {

                    document.getElementById(seguinte).focus()

                }
            }
        }
    } //não é enter
}); //fim função

When it gets to
if (focado.value.length == 0)

it goes back to the first variable declaration.  This is a problem because that way the variables fimseg and seguinte begin that cycle with the wrong values.
Comment: Does this behaviour persist you replace `alert()` by `console.log()`?
Comment: Your example code has a syntax error. Please provide the full code so anyone could reproduce your actual error.
Comment: it doesnt trigger more than once. see here: http://jsfiddle.net/swm53ran/425/. but you're missing semicolons everywhere (also fixed in the demo)
Comment: i've added an update with the full code.  missing semicolons on the trimmed code.
@Halcyon : alerts are just my debug helper
Comment: that switch block is just because i couldn't do this:
 seguinte = inicio + (fim +1);
           with sum instead of concatenate (fim +1)
I've tried seguinte = inicio + (parse(fim) +1); and seguinte = inicio + (parseInt(fim) +1); but they throwed errors
if I can make this sum work I can avoid the switch block and the function will probably work.
Comment: I managed to do it with parsefloat() but the error continues.

when it evaluates    if (focado.value.length == 0)
begins again saying the focus is in the next input field.
Answer: You seem to have a syntax error. Even when I include the }); that was not properly code-wrapped in your question, I still get this error in my Firebug console:
SyntaxError: missing ;
before statement alert("1") <----

Try creating a sample at http://jsfiddle.net/. Then we can help you more.
EDIT:
OK, I looked at your jsfiddle. Based on your comment, I think the main problems are:

It sounds like this is meant to be some sort of client-side validation script. But you don't explain exactly what it is supposed to do if the input is valid, or invalid. I'm going to assume that you want a popup message either way. I think it makes more sense to separate the "jump to the next empty box" behavior from the "validate and submit the values" behavior. So I did that in two separate handlers.
If you focus on the button (e.g. by tabbing to it, or pressing it down but moving the mouse away before releasing the mouse button) and then press Enter, you will get an error because the ID of the button does not match the expected pattern of the ID's you've set for the text boxes. So I changed the button to act the same as an Enter keypress on the first (top-left text box.) And I called event.stopPropagation() to prevent it from bubbling up to the document Enter handler.
I updated the Enter handler to only work on the textboxes, because you would get an error if you focus on just the document body or the button and then press Enter.

Here is the updated, working code: https://jsfiddle.net/op96m1Ln/2/. I use parseInt to capture the current box and some simple logic to jump to the next box in order. I also use regular expressions to validate the input.
Comment: tried to create a sample on jsfiddle but it does nothing...

https://jsfiddle.net/mehrlicht/bro0nwmo/
Comment: that switch block is just because i couldn't do this:
 seguinte = inicio + (fim +1);
           with sum instead of concatenate (fim +1)
I've tried seguinte = inicio + (parse(fim) +1); and seguinte = inicio + (parseInt(fim) +1); but they throwed errors
if I can make this sum work I can avoid the switch block and the function will probably work.
Comment: @mehrlicht Check out this fiddle that indubitablee created based on your original sample: http://jsfiddle.net/swm53ran/425. It works fine once you add the semi-colons. As for your new code, what is it supposed to be doing? The code is totally different from before. What do you expect to happen? Note that you have to press Ctrl+Enter to run the fiddle, then click in the bottom-right Result window to use it.
Comment: I managed to do it with parsefloat() but the error continues.

when it evaluates    if (focado.value.length == 0)
begins again saying the focus is in the next input field.
Comment: @mehrlicht Again: Exactly what do you expect to happen? Describe in words what you want the code to do. (These words may take many minutes to write, even over an hour, for a proper explanation. That's OK! The requirements are more important than the code!) Then describe what happens instead. (And remember to include *how* you get the bad behavior -- are you still pressing Enter? Which control has focus when you press Enter?) We need more details to help you. We can't debug a shell of a program without knowing exactly what it's supposed to do.
Comment: the aim is to click the submit button and send the textbox values.
before that it navigates between the textboxes.
First the boxes on the left and then the ones on the right.
Must be 7 or 8 digits on the left and 7 on the right.
At least one box on each column must be filled.
if enter is pressed on an empty box it jumps to the next field (according to the rules above)
Comment: i'm pressing the enter on the first textbox on the left. it runs correctly until the evaluation
 if (focado.value.length == 0)
but than returns to the variables declaration saying it catched the keypress on the second box on the left
Comment: I was mistaken.
It goes correctly to the last else. focus on the second box on the left.
and then catches a new enter keypress
Comment: ok.
On jfiddle your code didn't work as I wanted. Enter on an empty p2, p3 or p4, should jump to a1 and not the next one. for example.
Also, the validation shouls be done on the input box keypress (primary aim is to be used with barcodes) and this is a very mechanical task so it should be corrected right there and not after 8 codes.

What I did:
I took your advice (and despite pressing enter outside the boxes not giving me errors) and changed $(document).keydown to $("input[type=text]").keydown

And this is way it workd. no repeating cycle!

Thanks for putting me in the right track ;-)
Comment: @mehrlicht You're welcome. Please upvote and/or mark accepted the answer if it helped. Or create your own answer with the full solution. You may also want to consider editing your question as the original problem you described is no longer relevant.


How does the increase in overall number of events affect the peak (events/time)?

Question: I have a (simple?) question that I hope someone will find interesting enough to help me out with.
A web site has a given number of subscribers who generate a certain amount of traffic on the web server. Hits (web requests) are distributed throughout the day and result in a peak load of x hits/second.
Question: should the number of users increase (let's say double) and follow the same usage pattern, how would the peak load (hits/second) be affected?
I strongly doubt that the answer is 2x hits/second and realise that more information might be needed, to start from the actual distribution of the hits and the average total hits per day.
Anyone intrigued and kind enough to lend a hand?
Thanks,
Paolo
Comment: That's not what 'distribution-theory' means! Easy mistake to make, I know, but do read the category descriptions when tagging.
Comment: You'd need to define the peak load. If you model the hits as instantaneous events, there's no such thing as an instantaneous peak load. Either you need to look at the number of hits in a certain time interval, or the requests need to take a finite time to be served -- the result would be the same.
Comment: @joriki - Peak Load = number of instantaneous events that occur within a second.
Answer: It does indeed depend on the distribution and number of hits.
For example, suppose everyone always logged on at the same moment. Then the peak doubles.
Now suppose that the distribution is completely random throughout the day, and that you go from 1 user to 2 users. The chance that they log on at the same time is 1/86400. Therefore the peak will almost certainly stay at 1.
Basically, if the distribution is 'filled out' by the current usage, it will go up by 2, if it's sparse, it will stay the same. In between, it will vary, but on average increase by a factor between 1 and 2.
Comment: Thanks. Indeed my question is how to practically calculate that factor (well, its pdf).


Verifying the method when $x^2+y^2=1$.

Question: Before I show my method, I'll post an example question. (Also, this one is the start of my wonder.)

$x^2+y^2=1, z^2+w^2=1$. Then, find the minimum and maximum of $xw+yz$.

Of course, It can be easily solved with the Brahmagupta-Fibonacci Inequality, but I'll try to use my strategy.
\begin{align}
& \alpha=\arcsin(x), \beta=\arcsin(z). \\
& \therefore \arccos(y)=\alpha, \arccos(w)=\beta. \\ & xw+yz=\sin\alpha\cos\beta+\cos\alpha\sin\beta=\sin(\alpha+\beta). \\
& \therefore \min(xw+yz)=-1, \max(xw+yz)=1.
\end{align}
Like this, I found that if the variables satisfy $x^2+y^2=1$, we can use it as a trigonometric function. (Maybe a lot of people know about this.)
But, my question is:

Is this method always valid when the variables $x, y$ satisfies $x^2+y^2=1$, and the question is asking about the minimum, maximum, or the range of quadratic polynomials?

If not, please let me know the counterexample of this.
Comment: Your question is rather vague. What does it mean to say that *the question is all about quadratic polynomials*? Can you formulate a logically precise version of your question?
Comment: If $x^2+y^2=1$, there exists $a$ such that $x=\cos a,y=\sin a$. This is true even if we allow $x,y,a\in\mathbb C$.
Comment: Further, if $x,y$ satisfy some quadratic equation that does not define a parabola, then there either exist constants $a,b,c,d,\theta$ such that $x=a\cos\theta+b,y=c\sin\theta+d$, or the same but with hyperbolic functions. Finding these constants is nontrivial, but they will exist.
Comment: Umm... just for the one who has downvoted this post, please tell me why you downvoted this post so that I can edit this post.
Answer: Use Cauchy–Schwarz inequality:
$\vert \langle (x,y),(w,z)\rangle\vert \leq \Vert (x,y)\Vert \cdot \Vert (w,z)\Vert$. Equivalently,
$$ \vert xw+yz\vert \leq \sqrt{x^2+y^2}\cdot \sqrt{w^2+z^2} =1$$
Comment: Yes, this is also a nice solution, but this was just an example to show my method. In fact, this has a lot of solutions. For example, $(x^2+y^2)(z^2+w^2)=(xw+yz)^2+(xz-yw)^2$, so $(xw+yz)^2$ has a maximum of $1$, when $xz=yw$.

Verifying the method when $x^2+y^2=1$.


Deque data structure: Applications

Question: When we can insert and delete from both ends, why is it called a deque? Also, what are the applications of a deque?
I'm a student studying data structures for the first time. Thanks!
Answer: It's also known as the double-ended queue.  It's called this because it provides a generalized queue which we can modify from both the head or the tail.  Hence, double-ended.
When should we use one?
Whenever we want fast access to inserts and deletes at both the beginning and the end.  Scheduling and modeling real life queues are common examples.
Answer: One application I could think of is maintaining a Playlist of songs.

Next song is played from the front of the queue(i.e. playlist).
You can add a song to the queue (append) or the "play next" option adds the song to the front of the queue (appendleft)

For real-world application read this answer

Deque data structure: Applications


Buscando dados a partir de uma ID na DB

Question: Dei uma pesquisada aqui e no google para ver se resolveria meu problema sem ter que fazer uma pergunta, mas não consegui encontrar nenhuma solução.
O que estou tentando fazer é criar um "relacionados" mas sem que exibe o mesmo post ou vídeo no caso. No caso estou usando o seguinte código:
<?php
    if(!@mysql_connect("localhost","root",""))
    {
        die('oops connection problem ! --> '.mysql_error());
    }
    if(!mysql_select_db("player"))
    {
        die('oops database selection problem ! --> '.mysql_error());
    }
    $query = @mysql_query("SELECT * FROM videopv2 WHERE `videopv2`.`tipo_relacao`= '$tipode' ORDER BY id DESC");
    while ($relacionados = @mysql_fetch_object($query)):
        ?>
    <article class="video-preview <?php echo $relacionados->categoria_video; ?>" data-viewkey="6b684234a3" itemscope="itemscope" itemtype="http://schema.org/ImageObject">
        <a title="<?php echo $relacionados->titulo_video; ?>" itemprop="url" target="_blank" href="/AP/embed/<?php echo $relacionados->id; ?>">
            <img class="media-preview-thumbnail js-resrc js-resrc-lazy" alt="<?php echo $relacionados->titulo_video ?>" itemprop="thumbnailUrl" src="/AP/assets/embed/imgs/<?php echo $relacionados->imagem_video; ?>" data-src="/AP/assets/embed/imgs/<?php echo $relacionados->imagem_video; ?>" />

<?php echo $relacionados->titulo_video; ?>

<?php endwhile; ?>

Comment: Não ficou claro pra mim a descrição do problema.Importante resaltar que as funções mysql_* estão obsoletas.
Comment: Utilize Pdo ao invés de mysql_*.
Sobre a query, você poderia armazenar o id da postagem exibida em um variável e fazer algo tipo "select * table where idPostagem != idPostagemAberta"
Comment: @MarcosXavier, por exemplo, estou acessando uma postagem, e no rodapé tem uma parte onde exibi as postagens relacionadas. Nesse campo, eu queria saber como que faço para buscar sem que apareça a mesma postagem(que está aberta na página). Em questão do mysql_* qual é o método que está sendo utilizado agora?, estou aprendendo php com algumas video aulas antigas.
Answer: Para teu código funcionar vamos fazer algumas alterações. Mas primeiro vamos a teoria.
Você está utilizando a forma procedural do mysqli_query e está pulando algumas etapas. Caso queira saber mais, existe a forma orientado a objetos do mysqli::query. Abordei as diferenças de como utilizá-los aqui.
Criei um arquivo de conexão ao banco separado. Assim centraliza a conexão ao banco em apenas um lugar do seu projeto e evita retrabalhos.
include "conexao.php";

Como você não postou nada de como está sendo feito a conexão, vou colocar como é feito na forma procedural: (Não que o seu esteja errado)
// Conecta ao banco de dados
mysql_connect('127.0.0.1', 'usuario', 'senha');
mysql_select_db('banco');

Dica: após conectar o banco verifique se não houve erros:
/* valida conexão ao banco */
if (mysqli_connect_errno()) {
    printf("Falha na conexão ao banco: %s\n", mysqli_connect_error());
    exit();
}

Para realizar uma consulta com base em uma query você pode fazer assim:
// Monta e executa uma consulta SQL
$sql = "SELECT *` FROM `usuarios`";
$query = mysql_query($sql);

Para percorrer a consulta você pode fazer usando um laço de repetição, exatamente como está fazendo:
// Para cada resultado encontrado...
while ($usuario = mysql_fetch_assoc($query)) {
  // Exibe um link com a notícia
  echo $usuario['nome'] . ' - ' . $usuario['email'];
} // fim while

Repare que no array $usuario['nome'] é aspas simples (''), ao invés de crases (``).
E uma dica para exibir o total de linhas vindas na consulta
// Total de notícias
echo 'Total de notícias: ' . mysql_num_rows($query);

Qualquer dúvida basta comentar.

Buscando dados a partir de uma ID na DB


Returning an object which has keys as the values of passed array

Question: I would like my function to return an object which has the key of the passed in array parameter's values.
If user passes the array ["i","love","potato"], then I want the return type to be inferred as { i: string; love: string; potato: string }. How can I achieve this?
Here is my attempt:
public async getParameters(keys: readonly string[]): Promise<{ [K in typeof keys]: string }> {...}

Answer: I am making a few assumptions here, looking at the code, it looks like you are writing a function in TS where you want to map over the types of an array and then produce a new object with the keys based on the values in the array.
Your method wont work, here is the correct way of going about it:
public async getParameters<T extends string[]>(keys: readonly [...T]): Promise<{ [K in T[number]]: string }> {
    const result: any = {};
    for (const key of keys) {
        result[key] = "";
    }
    return result;
}

const obj = await getParameters(["i", "love", "potato"]);

Answer: Like this
type ToObject<T extends readonly string[]> = {[key in T[number]]: string}

declare function toObject(keys: readonly string[]): ToObject<typeof keys>


Change Number of Values in CCK Filefield/Upload

Question: Using hook_form_alter(), how would I change the default of 1-10 then Unlimited, to 1-24 then Unlimited?  CCK Only gives 1-10 as options before going to Unlimited and I need to have 1-24.  I know this is possible using hook_form_alter() but I do not know the syntax of how to write that.
Any help is greatly appreciated!
Answer: <code>/**
 * Implementation of hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_field_edit_form') {
    $form['field']['multiple']['#options'] = array(1 => t('Unlimited'), 0 => 1) + drupal_map_assoc(range(2, 24));
  }
}
</code>


Why is there no divsion by degrees if freedom in sample correlation?

Question: Why is there no divsion by degrees of freedom in sample correlation? The same seems to hold for the coefficent of the depandt variable using linear regression.
To me it look like some kind of sample variance and sample covariance but not divided by $\frac{1}{n-1}$
Any ideas?
Answer: If by "$\textit{no divsion by degrees of freedom in sample correlation}$" you mean that there is no $\frac{1}{n-1}$in the expression:
corr$(x, y)$ = $\frac{\displaystyle \sum_{n=1}^n(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\displaystyle \sum_{n=1}^n(x_i - \bar{x})^2 \displaystyle \sum_{n=1}^n(y_i - \bar{y})^2}}$
Simply consider the case where you actually add it:
corr$(x, y)$ = $\frac{\displaystyle \sum_{n=1}^n\frac{(x_i - \bar{x})(y_i - \bar{y})}{n-1}}{\sqrt{\displaystyle \sum_{n=1}^n \frac{(x_i - \bar{x})^2}{n-1} \displaystyle \sum_{n=1}^n \frac{(y_i - \bar{y})^2}{n-1}}}$
Then:
corr$(x, y)$ = $\frac{\displaystyle \frac{1}{n-1}\sum_{n=1}^n(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\displaystyle \left(\frac{1}{n-1}\right)^2\sum_{n=1}^n (x_i - \bar{x})^2 \displaystyle \sum_{n=1}^n (y_i - \bar{y})^2}}$
Consequently:
corr$(x, y)$ = $\frac{\displaystyle \frac{1}{n-1}\sum_{n=1}^n(x_i - \bar{x})(y_i - \bar{y})}{\displaystyle \frac{1}{n-1}\sqrt{\sum_{n=1}^n (x_i - \bar{x})^2 \displaystyle \sum_{n=1}^n (y_i - \bar{y})^2}}$
Which is equal to the original expression as $\frac{1}{n-1}$ in the numerator and denominator cancels out.
In case you are wondering why no degrees of freedom correction is made in some expressions you might have found on the internet or textbooks, it is probably because those examples are part of Large Sample Theory. As the number of observations goes to infinity, biased estimators are not that important provided that these estimators are consistent.
Just consider this:
$\lim_{n \to \infty} \frac{1}{n} = \lim_{n \to \infty} \frac{1}{n-1}$.
Note that some assumptions like random sampling or covariance stationarity might be needed.


Two different applications (Heroku and EC2) on the one domain name

Question: Is it possible to point my Heroku application to https://myawesomeapp.com and my EC2 wordpress server pointing to http://myawesomeapp.com ?
Answer: Though it is possible but its not good practice to point two app to same domain name. Some user will get ur heroku app and some users will get Wordpress sitedepends upon the DNS resolution from the network.
Answer: It's entirely possible, yes - I wouldnt say it's bad practise, or that users will get different things depending on DNS either.
IIS will certainly let you run different websites on different ports - so simply run one on HTTP, and the other on HTTPS.
I don't know what web server you're using though.
Comment: We can't edit the Heroku web server and the EC2 server would be running apache


Why do we care about the noise in the target variables when building machine learning models?

Question: When building linear regression problem, we assume that we have a noise or erros in the target variables that we measured. I have two questions about that

If I want to build a machine learning model. I think that we mustn't care about the errors in the data. Because simply, it is not my problem. This is the problem of customers/researchers who are measuring the data. I mean their job to decrease the noise using Digital Signals Processing or any other tools. From my point of view, we have a lot of problems in this field and we do not need more. Secondly, we don't separate this field from other fields. Thirdly, I think by modeling the noise in the target variables, we are just telling people that ML field is a tool to solve problems from A to Z regardless of where the data came from. Of course, there is a reason to build that noise, but I can't find it.
Can you give me a practical example where we should model the noise, otherwise our machine learning system will fail?

I found that the origin of this is based on Errors-in-variables models. However, I want to understand the reason from machine learning prospective.
Comment: The terms "error" and "noise" might have misled you. These are genuine properties of the data that are inherent in the data generating process. Measurement error can come on top, but that is less frequently an issue.
Comment: +1. And the whole point of ML/Stats is to find relevant information through random data. So of course we care about this randomness. Errors in the data is different, but if your algorithms are going to be applied to real data it may be wise to ensure that it won't "break down" whenever it encounters an error.
Comment: Very  unclear question
Answer:
I think that we mustn't care about the errors in the data. Because simply, it is not my problem.

What if the data was collected with a bias? For example, say you want to learn people's voting habits. You send out a survey and get thousands of responses back, so you think its a representative sample. However, it turns out that only people with incomes greater than $100K responded. But you don't know that. That will surely impact your analysis. But no one actually made a mistake, per se, did they? Are you suggesting that you shouldn't care about this?

This is the problem of customers/researchers who are measuring the data. I mean their job to decrease the noise using Digital Signals Processing or any other tools.

Who are you in this situation? A customer may not have to care, but a researcher or practitioner certainly should.

Secondly, we don't separate this field from other fields.

I'm not sure what you're trying to say here. Can you elaborate what "this field" and "other fields" mean and why they aren't separate?

Thirdly, I think by modeling the noise in the target variables, we are just telling people that ML field is a tool to solve problems from A to Z regardless of where the data came from. Of course, there is a reason to build that noise, but I can't find it.

If you're suggesting that ML requires domain knowledge of the data generating process, then I definitely agree. Modeling the noise in the target variable does not preclude this from being true. Why would it?

Can you give me a practical example where we should model the noise, otherwise our machine learning system will fail?

What does it mean for our machine learning system to "fail"? Fail at minimizing some objective function? Imagine we build a model that minimizes CV error, so by many measures it's "successful". Then the data changes over time in ways that our model failed to account for because it wasn't robust enough (due to data error/bias or because we didn't model the noise accurately). Now, on new data, it will fail. Perhaps we can retrain it to the new data, but that's just one approach to dealing with poor modeling choices. How often will you need to retrain? Will it even "work" anymore on new data if that new data contradicts your modeling assumptions?
In short, one cannot overestimate the importance of modeling error. One could argue that the field of Statistics is based on this premise.
Comment: For the third question: Let us say that I am dealing with EEG data (biomedical signals) then this data is very noisy and what we are doing usually is using Digital Signals Processing to increase the signal to noise ratio. So, what I think is that, modeling the noise and dealing with it is the job of DSP people not machine learning people. Anyway, I understand that the noise refers to the uncertainty results from that we can't "survey" all the cases/data and has nothing to do with "real noise" of the signals/data. I am a DSP engineer and that what confused me.
Comment: I see. What you're referring to is a very specific practical example. Not data modeling in general, but more the data processing pipeline. In that case, I'd agree that there are certain situations in which you may need to trust that the data is collected accurately by your colleagues. Of course, that doesn't mean you shouldn't perform some data integrity checks yourself.


Functional analysis problems

Question:
Problem: Let $\psi_1,\psi_2,\psi_3,...$ be non $-$ negative continuous functions on $[0,1]$ such that:$$\lim_{n\rightarrow \infty} \int_0^1x^k \psi_n(x)dx$$ exists for every $k=0,1,2,...$.Prove that $$\lim_{n\rightarrow \infty} \int_0^1 f(x) \psi_n(x)dx$$ exists for every for every continuous function $f$ on $[0,1].$

Studying some functional analysis problems, and the problems in my problem sheet my professor gave us seem alittle too hard. This is actually one of our assignment problems, I really would appreciate some hints at least. Can anyone help me with this problem? Our professor gave us a hint and he said use Stone-Weierstrass theorem, then construct some sequence and show that it is Cauchy. Still have no clue...
Answer: First note that $\lim \int_0^{1} \psi_n(t)\, dt$ exists so $C\equiv \sup_n \int_0^{1} \psi_n(t)\, dt <\infty$. Let $f$ be a continuous function and let us show that $\{\int f\psi_n\}$ is Cauchy. Let $\epsilon>0$ and choose a polynomial $p$ such that $|f(x)-p(x)|<\epsilon$ for all $x$. Then $$|\int f \psi_n -\int f\psi_m| \leq |\int p \psi_n -\int p\psi_m| +|\int f \psi_n -\int p\psi_n| +|\int f \psi_m -\int p\psi_m|$$ The second term is bounded by $\epsilon C$ and the last term is also bounded by the same number. The first term tends to $0$ as $n,m \to \infty$. Can you complete the proof now?
Comment: $\int f \psi_n -\int f \psi_m =(\int f\psi_n -\int p \psi_n) +(\int p \psi_n-\int p \psi_m)-(\int f \psi_m-\int p \psi_m)$
Comment: Is it then: $$||f-p||_{\infty}\int_0^1 \psi_n+\frac{\epsilon}{3}+||f-p||_{\infty}\int_0^1 \psi_m \le \frac{\epsilon}{3M}M+\frac{\epsilon}{3}+ \frac{\epsilon}{3M}M=\epsilon$$ Also shouldnt the first integral of the RHS in your answer be:$$\bigg|\int_0^1 f\psi_n-\int_0^1p\psi_n\bigg|$$
Comment: I think the RHS is correct.
Comment: Why is it:$$∣∫_0^1p\psi_n−∫_0^1p\psi_m\bigg|$$
In one of the terms on the RHS of your answer? I do not get this part sorry. I get everything else but this part of the inequality.
Comment: Thank you for this, it was very helpful !

Functional analysis problems


Period of two equal functions

Question: I'm dealing with a problem here.
We know that two functions are the same if they have the same domain and codomain.
Let's say we have given the functions $f$ ang $g$ where $f\left(\frac{3x-8}{4}\right) = g(x)$ .
The tasks says: If function f has the period 9, find the period of g.
The solution in my book says that the period of g is 12.
But what I don't understand is how can two equal functions have different periods(9 and 12)?!
Can anyone help me ?
Thank you!
Comment: The functions aren't equal. They take on all the same values, but for different inputs. like sinx, cosx, and sin(2x)
Answer: $f$ and $g$ are certainly not "equal functions". In fact, $g=f\circ \ell$, where $\ell$ is the linear function (with whatever domain and range) with rule $\ell(x) = (3x-8)/4 = \frac34x - 2$.
Suppose the period of $g$ is $p$. Then
$$g(x) = g(x+p)$$
$$f(\tfrac34x - 2) = f(\tfrac34(x+p) - 2)$$
$$f(\underbrace{\tfrac34x - 2}) = f(\underbrace{\tfrac34x - 2} + \tfrac34p)$$
If this is to be true for all $x$, then $\frac34p$ must be a period of $f$. The minimal such value then is that for which
$$\tfrac34p = 9$$
$$p = \tfrac43(9) = \boxed{12}$$
as desired.

Period of two equal functions


Custom block not showing

Question: I created a custom block module (nothing fancy, just an A-Z list and a taxonomy list for navigation), this worked fine in D8 & D9, now since upgrading to D10 it only shows when logged out, when logged in, it still writes a debug message to the Apache errorlog from the build() function, so I know the code is being called and I can dump the content to the log, I just get no display of the output. I have a few paths including . Log out and the block is displayed again.
All the answers I can find are for the block not displaying and requiring a login, this works fine until I login.
I'm outputting to the "hero" region and the region is displaying OK, just without my block content.
Any suggestions on what to look for?
Comment: Yes, all good, but surely if it was incompatible, it would fail regardless of logon?
Comment: Could be caching with your theme.  Try with one of the unmodified core themes and see if you can reproduce the issue.
Comment: Does the block have caching metadata? It's not absolutely required: I'm just asking. Perhaps you should show the code.
Comment: main element of build is

`$build = [
            '#theme' => 'hopnavigation_block',
            '#commons' => $commons_menu,
            '#lords' => $lords_menu,
            '#az' => $az,
            '#constituency' => $con_az,
        ];
        return $build;`

`public function getCacheMaxAge(): int
    {
        return 0;
    }`
Comment: Please put code samples in the Question. It's difficult to format code in comments, and the Question should contain everything necessary for a fact-based answer.
Comment: Are there browser console errors?
Answer: Not entirely an answer, but I put the same block into claro theme and all was good, the theme in use was a temporary testing theme so will create new one via starterkit so issue is resolved, even if the actual question was not answered. Testing theme was a clone of Olivero taken from 9.4 using the work at https://github.com/mherchel/olivero-subtheme if that helps others.

Custom block not showing


do While inside a variavel

Question: Estou a criar um sistema de pesquisa por aonde o utilizador ira colocar somente o mês e o ano que pretende pesquisar.
mas não estou a conseguir o código é o seguinte
$output='
Elementos

                        Nº Interno
                        Nome
                        SV

                '.do{.'

                        '.$row_elementos['N Interno'].'
                        '.$row_elementos['Nome'].'
                        '.$total.'

'.
                }while ($row_elementos = mysql_fetch_assoc($elementos)).'

';

Depois é feito o print a base da pesquisa feito em baixo com o seguinte código
<?php print("$output");?>

os erros estão no {do(syntax error, unexpected 'do'(T_DO))} e no {while(syntax error, unexpected '}' }.
Como devo corrigir os erros?
Comment: Feche a string primeiro, depois faça um while normal.
Comment: como assim? o while é só feito naquele local
Comment: Ele quis dizer para fechar a string ali no thead e fazer o do while normal
Comment: mas isto é feito o print após uma pesquisa
Answer: Tente concatenar por partes não misturar tudo num bolo. Exemplo:
$output='
Elementos

                    Nº Interno
                    Nome
                    SV

';
            do{
                $output .= ''.$row_elementos['N Interno'].'
                    '.$row_elementos['Nome'].'
                    '.$total.'	';
            }while ($row_elementos = mysql_fetch_assoc($elementos));
$output .= '

';

Comment: obrigado! 100% funcional
Answer: Primeiro feche a string, não é possível concatenar ela com um laço de repetição. Use um while convecional se usar o do-while no caso da consulta retornar vazia será gerado alguns undefined index porque não existem e porque a verificação é feita apenas no final do laço e não no inicio.
$output='
Elementos

                        Nº Interno
                        Nome
                        SV

';

                while ($row_elementos = mysql_fetch_assoc($elementos)){
                    $output .= '

                        '.$row_elementos['N Interno'].'
                        '.$row_elementos['Nome'].'
                        '.$total.'

';
                }

            $output.= '

';

Comment: fica funcional mas não me apareceu o primeiro elemento
Comment: @AdelinoVasconcelos é para exibir todos o registros. Você use em algum outro lugar `$row_elementos` ou preenche ela manualmente?
Comment: como assim? não percebi

do While inside a variavel


Utilização da função MAX em uma consulta SQL

Question: Estou criando uma consulta onde devo trazer o percentual de ICMS na ultima entrada de um produto. Pensei em fazer da seguinte forma:
SELECT
    IDSUBPRODUTO,
    PERICM,             --% ICMS
    MAX(DTMOVIMENTO)
FROM
    ESTOQUE_ANALITICO EA
GROUP BY
    IDSUBPRODUTO,
    PERICM

Porém como alguns produtos tiveram diferentes valores de ICMS em diferentes entradas, o código acaba me retornado as vezes que o produto entrou com ICMS diferentes como o exemplo abaixo:

Quando na verdade eu gostaria de listar somente essa ultima entrada, do dia 18/06/2022.
Comment: Só pra esclarecer - tu queres um select que retorne sempre o ICMS mais novo (data mais recente na coluna 3) de cada produto (coluna IDSUBPRODUTO)? Se for de um produto só, acho que dá pra ordenar por data e pegar o primeiro da lista (não sei se há uma função TOP no db2, mas tenta aí)...
Comment: precisa fazer uma subquery que te retorne a data para filtra, pq o group by não vai te ajudar uma vez que há diferentes valores em icms. Eu já respondi uma duvida muito parecida aqui, veja se ajuda: https://pt.stackoverflow.com/a/498997/57220
Comment: outro exemplo https://pt.stackoverflow.com/questions/556814/selecionar-%c3%baltimo-registro-da-tabela/556852#556852
Answer: SELECT IDSUBPRODUTO,
       PERICM, --% ICMS
       DTMOVIMENTO
FROM ESTOQUE_ANALITICO EA
/*BUSCA POR SUB SQL A MAIOR DATA POR PRODUTO
  PRECISA DE UM "ALIAS" PARA DIFENCIAR AS INSTANCIAS
  DAS TABELAS */
WHERE DTMOVIMENTO = (SELECT MAX(EA1.DTMOVIMENTO)
                     FROM ESTOQUE_ANALITICO EA1
                     WHERE EA1.IDSUBPRODUTO = EA.IDSUBPRODUTO)


Asp.Net Chat server-side polling

Question: Helo,
I have implemented a chat application using Comet.
the request is "hang" on the server until new messages arive.
It, then, returns to the client with the new messages, and goes to the server again.
My problem is:
In order to check for new messages, I poll the database every 600 ms.
I perform a simple query "select...from messages where messageId > ' + lastMessageId.
In addition, in order to maintain presence, I update the database very (very) often
with each user "LastKeepAliveTime".
The SQL Server transaction log is growing huge, and, at a certain point, my chat application stops working.
The chat users are not registered users, they are just random users who can leave the page at any time.
thanks
Yaron
Answer: Here's how to keep the transaction log from getting out of control: http://support.microsoft.com/kb/873235
Options in that article include:

Doing a shrink.
Changing the log size.
Configuring automatic expansion.
Changing the recovery model.
Backing up the log file regularly.

and more.
As a side note, it may be worthwhile to set up a list of users and their last activity dates that you store as objects in your application state.  It would be quicker to access that way and you could persist the values less frequently.
Answer: Could you use a common cache object for the last keep alive information?  It seems like its a small amount of information and you could avoid a lot of sql updates.
Answer: Switching from full mode transaction log to simple mode should solve your log growth issues.
However, I should also add that it's generally a good idea to avoid polling if you can, since it's not scalable.  You might consider switching to an event-driven model using Service Broker or SqlDependency. There are other approaches to keep-alives, too.

Asp.Net Chat server-side polling


Is excess kurtosis for a mixture of two normal distributions with the same means and different variances always positive?

Question: For a mixture of two normal distributions with the same mean the excess kurtosis is stated to be
$$3 \frac{(p_1 \sigma_1^4 + p_2 \sigma_2^4)}{(p_1\sigma_1^2 + p_2\sigma_2^2)^2} -3$$
I believe that this should always be positive when the sigmas are always > 0 and the p's are from (0,1). This website implies that the demonstration relies on the relationship between arithmetic and geometric weighted sums, but I don't see it.
Is the claim true? And if so, can you help me see how to demonstrate it.
Answer: You forgot to mention $p_1 + p_2 = 1$ which follows from the web site you linked. I will use $s,t$ for $\sigma_1, \sigma_2$ and $p,q$ for $p_1, p_2 = 1-p_1$ to simplify notation.
Sufficient to show that
$$ps^4 + qt^4 \geq \left(ps^2 + qt^2\right)^2.$$
Note that
$$
\begin{split}
0 &\leq \left(s^2 - t^2\right)^2 = s^4+t^4 - 2s^2 t^2 \\
2s^2 t^2 &\leq s^4 + t^4\\
2pq s^2 t^2 &\leq s^4pq + t^4pq = s^4p(1-p) + t^4q(1-q)\\
2pq s^2 t^2 &\leq s^4p+ t^4q -s^4p^2 - t^4 q^2 \\
2pq s^2 t^2 + s^4p^2 + t^4 q^2 &\leq s^4p+ t^4q \\
\left(ps^2 + qt^2\right)^2 &\leq s^4p+ t^4q \\
\end{split}
$$
as desired.
Comment: @gt6969b any suggestions for how I might approach generalizing this proof for the case of more than two components, i.e. showing that $\sum_i p_i \sigma^4_i \geq (\sum_i p_i \sigma^2_i)^2 \mbox{where} \sum_i p_i = 1$?
Comment: @brittUWaterloo I'm sorry, no immediate thoughts on it.


How to validate datetime object in SPARQL? (Virtuoso 22007 Error DT006)

Question: I get the following error.
Virtuoso 22007 Error DT006: Cannot convert -0359 to datetime : Incorrect month field length

SPARQL query:
define sql:big-data-const 0
#output-format:text/html
define sql:signal-void-variables 1 select ?item  bif:year(xsd:dateTime( str(?dob))) as ?m{
?item <h://f.cm/ns/common/topic/notable_types> <h://f.cm/ns/people/person> .
?item <h://f.cm/ns/people/person/date_of_birth> ?dob
} limit 675

If I change the limit to 674, it works.
What I suspected was that some datetime field is wrong somewhere and printed ?dob, which revealed that one of the values is -0359.
Solution is to validate the value before applying bif function.
But, how can we validate datetime in SPARQL?
Answer: Well, I found this question via Google because I had the same problem. Looking elsewhere for help, I found the following solution:
SELECT * {

  ?s ?p ?o

  FILTER ( datatype(?o) = xsd:datetime )
  FILTER ( coalesce(xsd:datetime(str(?o)), '!') != '!')

}

This worked for me.
Note that I found the answer to this at SemanticWeb.
Comment: @Richard Sorry, I don't recall after this long; I probably just copied and pasted it from my code, so it would be as shown... :(
Comment: No luck with same approach here. Also no luck with: FILTER (regex(str(?o), '^[0-9][0-9][0-9][0-9]-[01][0-9]-[0-3][0-9]')) FILTER (xsd:datetime(?o) > '" + minBirthDate + "'^^xsd:datetime). What is coalesce(...) here?
Comment: Coalesce in the above query does what the name suggests: it concatenates the result of the conversion of ?o to a datetime with an exclamation mark. If the result of that is just an exclamation mark, then that means that the datetime is empty and hence, ?o was not a valid datetime. Since we filter on results that do NOT coalesce to just '!', we filter on values that are indeed a valid datetime. Does that make it more clear to you?
Comment: @TextGeek ... a bit late, but does your minBirthDate really have xsd:datetime or just xsd:date (like mine) :) `FILTER ( datatype(?sdate) = xsd:date )
  FILTER ( coalesce(xsd:date(str(?sdate)), '!') = '!')`


Por que a minha view não está apresentando o design do css?

Question:

  <link href="/css/app.css" rel="stylesheet">
  <title>Controle de estoque</title>

Listagem de Produtos

  <?php foreach($produtos as $p): ?>

    <?= $p->nome ?>
    <?= $p->valor ?>
    <?= $p->descricao ?>
    <?= $p->quantidade ?>

 <?php endforeach ?>

Answer: Porque o caminho está errado. Se você está usando os arquivos de css na pasta public (que é o recomendado) deverá adicionar da seguinte forma:
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css"/>

Answer: Talvez você não esteja apresentado o caminho correto para o arquivo.
tente isso.

<link href="../css/app.css" rel="stylesheet">

é sempre bom limpar o cache do navegador também :)
Comment: não resolveu. Eu estou usando o laravel 5.5, e parece que ele não vem instalado algumas coisas, será que é por isso?


Atualizar versão do Entity framework

Question: Acabei de atualizar minha versão do .Net 3.5 para 4.5.1.
O meu Entity Framework estava na versão 3.5, eu queria saber se ele já atualiza para a versão mais nova depois da troca de framework.
Comment: Você já percebeu que as perguntas e respostas devem contar apenas perguntas e respostas? Não incluímos textos que podem ser consideramos apenas ruído no que é mais importante. Isto inclui saudações e agradecimentos. As perguntas e respostas devem servir mais ou menos como a FAQ para todas as pessoas. Não é uma postagem sua para outra pessoa. Por acaso você está postando uma pergunta que deve servir para todos. Não somos um fórum ou rede social. As **perguntas** e **respostas** devem reinar absolutas.
Comment: Exatamente, então não transforme ela em uma coisa que pareça ser só sua. http://meta.pt.stackoverflow.com/questions/2068/o-stack-overflow-em-portugu%C3%AAs-%C3%A9-um-f%C3%B3rum
Answer: Na verdade creio ser impossível que seu Entity Framework esteja na versão 3.5, até porque a versão mais antiga distribuída é a 4.1.10311.
De qualquer forma, para atualizar, vá em View > Other Windows > Package Manager Console e digite:

Install-Package EntityFramework -Version 6.1.1

Isto deve atualizar seu Entity Framework para a versão estável mais recente na data desta resposta.
Comment: Aparentemente faltam mais configurações, e algumas coisas devem ter ficado defasadas.

Atualizar versão do Entity framework


How to call/submit Form from another page in custom module?

Question: I would like to set cron function in my custom module. I have created one form which is called with submit button from UI. Now I would like to submit/call that form from another page (.module file) where I have written my hook_cron function, how it would be possible?
In Drupal 7, I use
<code>$form_state['values'] = "";
drupal_form_submit('customfeedimport_main_pagecallback_submit', $form_state);
</code>
But I am new to Drupal 8, so how to perform this cron thing in Drupal 8?
Also what should be included in the namespace, use?
Answer: You can do it with the FormBuilder::submitForm() function.
To register a new user (taken from the docs):
<code>// register a new user
$form_state = new FormState();
$values['name'] = 'robo-user';
$values['mail'] = 'email@example.com';
$values['pass']['pass1'] = 'password';
$values['pass']['pass2'] = 'password';
$values['op'] = t('Create new account');
$form_state->setValues($values);
\Drupal::formBuilder()->submitForm('user_register_form', $form_state);
</code>
You might have to include the namespace for the FormState class before this code if not done already.
Comment: Hello AjitS, I have tried but it's giving me an error. Can you please provide me the full code with a namespace, so I can get know better.


Increasing a VM's CPUs beyond the host's CPU count

Question: I recently noted a Hyper-V VM with consistently high CPU usage. It's a terminal server with several people logged in concurrently, all running several apps each. I increased the VM core count, and this did help, as expected.
However, when overall CPU usage runs above 90% for this VM, usage on the host server running Hyper-V doesn't exceed 20%. And that's while running a few other VMs.
The physical server has six cores with hyperthreading enabled. VM cores don't seem to correlate to actual physical cores on the host as far as I can tell. So if the host has a lot more CPU power left, can/should I continue adding more cores to the VM, even exceeding the physical core count?
The host has six cores with hyperthreading enabled. Is setting this VM to have 12 cores optimal? How can I best understand the optimal strategy here?
Answer: With hyperthreading enabled, your host has 12 logical cores. Resources allocation is dynamic, so your other VMs can still use available CPU resources on your host, while your terminal server is having 12 CPUs allocated, however, I would not do it. You can alternatively, reserve let's say 6 CPUs for your terminal server and see if it helps. Check for some additional information: https://www.hyper-v.io/several-tips-hints-full-throttle-hyper-v-performance/


Train/Test splitting for seasonal adjustment

Question: At work, I just started dealing with seasonal adjustment of monthly time series on credit data, so being new to the topic it is quite possible that my question is pretty trivial.
From what I've read so far, procedures like TRAMO-SEATS and X13-ARIMA-SEATS never mention the need to split the data into train/validation/test sets, which is instead a common practice in the context of machine learnign algorithms.
Indeed it seems to me that the seasonal adjustment algorithms use the entire time series and, every time a new observation comes in, it gets added to the input dataset as well, often leading to significant change in the seasonal adjustment factor and in the parameters of the underlying ARIMA model (automatically estimated by the seasonal adjustament procedures).
I am a bit perplexed from a methodological point of view. Is it correct that every time new data is added, the seasonally adjusted series changes in its entirety? How are these variations conceptually justified? Wouldn't it be more correct to use the train/test split to define a single model so that adding a new observation does not lead to changes in the past of the seasonally adjusted series?
Thanks and any insight would be appreciated.
Answer: I understand your point, and the closest thing I can think of is the SLIDINGSPANS spec. It provides a model stability analysis over the data set.
With SLIDINGSPANS, you specify the length and the number of sub-spans, start, etc., and the X-13ARIMA-SEATS program compares the different features of seasonal adjustment from overlapping sub-spans of the time series data.
To learn more, see the reference manual of the X-13ARIMA-SEATS:
https://www2.census.gov/software/x-13arima-seats/x-13-data/documentation/docx13as.pdf


Paris VI or ENS Lyon for master's student interested in algebra?

Question: I have the opportunity to study in France during the forthcoming autumn, either at Paris VI (6), or at ENS Lyon, and I have trouble deciding which offer I should take. I'm mainly interested in algebra (commutative algebra, representation theory and category theory in particular). Any advice, or just general thoughts on the matter, from people with knowledge of either or both universities is much appreciated!
Comment: Yes, UPMC. I'm not sure I get your meaning correctly, but my impression is indeed that Paris 6/UPMC is inclined a bit more towards analysis/applied math, which if correct is a disadvantage given my interests.
Answer: I am a former student of the ENS Lyon, so my opinion may be biased, but you are warned ! I also studied 1 year at Paris 6 (Jussieu).
Both are labs of a very good level and I think you'd enjoy the experience in both cases.
Advantages of Lyon :

It is a smaller structure than a university, with only students with a very good level. The infrastructures are nice and there is much conviviality. Professors are on the whole closer and more available to students than in a university.
Given the interests you stated, François Bruneault and Laurent Berger are two very good specialists that you can interact with.
Lyon is a nice town (OK, less relevant).

Advantages of Paris :

It is one of the biggest and best universities in France : you'll have more people to talk with than in Lyon.
It's Paris, so there will be lots to see and other universities to visit (in particular Orsay university, which is probably the best in France as far as maths go). On the other hand though, people tend to not know each other in classes, which is not very nice (especially for a foreign student).

In conclusion : I'd say it depends on where you are in your studies. If this is the last year of masters (Master 2 in the french system, right before the beginning of a PhD), then I'd suggest you base your decision mostly on the courses (the resumes should be online) and the specialists if you want to do PhD in France.
Otherwise, I suggest Lyon.
Comment: Thank you for a quick and helpful answer (it's upvoted, but I'll wait a bit longer before "accepting" an answer)! I'm at the end of my master's studies (so last year it is), and will probably apply to a PhD-program in my home country Sweden, but time will tell.
Comment: OK. then I like I said in the answer, you should be specialized enough that the content of the courses and the people in your area of interests should be determinant. I don't know who the proeminent algebraists are in Paris 6, but you can probably check it online.


Does $x_n\sim y_n\implies \sum_{n\geq 1}x_n\sim\sum_{n\geq 1}y_n$

Question: Suppose that $x_n,y_n\geq0$ for all $n$. I know that if $x_n\sim y_n$ and that $\sum_{n\geq 1}y_n$ converge, then $\sum_{n\geq 1}x_n$ converge. But to me, it doesn't imply that $\sum_{k\geq 1}^nx_k\sim\sum_{k=1}^n y_k$, take for example $x_n=\ln\left(1+\frac{1}{n^2}\right)$ and $y_n=\frac{1}{n^2}$.
Now I have that $$f_n(k,p)=\binom{n}{k}p^k(1-p)^{n-k}$$ and $$\rho_\lambda(k)=\frac{e^{-\lambda}\lambda^k}{k!}.$$ I have shown that if $$f_{n}(k,p_n)\sim_\infty \rho_\lambda(k)$$ if $\lim_{n\to\infty }np_n=\lambda$. Now, have to compute $$\lim_{n\to\infty } \sum_{k=1}^n kf_n(k,p_n).$$
In the correction it's written that since $f_n(k,p_n)\sim_\infty \rho_\lambda(k)$, we conclude that
$$\lim_{n\to\infty } \sum_{k=1}^n kf_n(k,p_n)=\sum_{k=1}^\infty k\frac{e^{-\lambda}\lambda^k}{k!}=\lambda.$$
I don't really understand why the fact that $f_n(k,p_n)\sim_\infty \rho_\lambda(k)$ imply that $$\lim_{n\to\infty } \sum_{k=1}^n kf_n(k,p_n)=\sum_{k=1}^\infty k\frac{e^{-\lambda}\lambda^k}{k!}.$$
Don't answer that a binomiale can be approach by a poisson law if $n$ is big a $p$ very small. I know this and it's not my question !
Comment: @5xum Landau notation, I assume: https://en.wikipedia.org/wiki/Big_O_notation#Family_of_Bachmann.E2.80.93Landau_notations
Comment: Where does this come from -- is it a textbook?
Comment: What does $x_n\sim y_n$ mean?
Answer: You are right for the fact that $x_n\sim y_n$ and that $\sum y_n$ converge doesn't implies $\sum_{k=1}^n x_k \sim_n \sum_{k=1}^n y_k$, in this case, you have the equivalence $\sum_{k=n}^\infty x_k \sim_n \sum_{k=n}^\infty y_k$.
For your problem, I might be wrong, but I think you can pose
$\phi_n(k) = \left\{\begin{array}{cl} f_n(k, p_n) & if\quad k\leqslant n\\
0 & otherwise\end{array}\right. $ and write the sum as $$ \sum_{k=1}^n kf_n(k,p_n) = \sum_{k=1}^\infty k\phi_n(k)$$
by hypothesis you have  $\phi_n(k) \to \rho_\lambda(k)$ for all $k$, so you might be able to invert the limit to conclude $$  \lim_{n\to\infty}\sum_{k=1}^n kf_n(k,p_n) = \lim_{n\to\infty}\sum_{k=1}^\infty k\phi_n(k) = \sum_{k=1}^\infty \lim_{n\to\infty}k\phi_n(k) = \sum_{k=1}^\infty k\rho_\lambda(k)$$


Django: Proxy Meta-class ignoring verbose_name_plural

Question: Django-admin is pluralizing a model that I have running as a proxy class.
The normal case here works fine:
class Triviatheme(models.Model):
    [  ... elided ... ]
    class Meta:
        db_table = u'TriviaTheme'
        verbose_name_plural='trivia themes'

But for a main content table, I have a parent model called 'Content', and a proxy class:
class News(Content):
    DTYPE='News'
    class Meta:
        verbose_name_plural='News'
        proxy = True

But with the Meta in Content is still pluralizing 'News' resulting in 'Newss', so its ignoring the verbose_name_plural field, but not the proxy field.
Similarly, overriding the field in the parent class seems to have no effect. What am I missing? Is there a better way of implementing a large table model with a discriminator column?
Note that this is reverse engineering a DB from a different app, so the model is pretty well set and I can't just change the schema.
edit:
I'm on python 2.6 / Django 1.2.1
I'm also using a Manager class to handle the discriminator, but its still not working.
Comment: What version of Python/Django are you using?  On Python 2.6/Django 1.2.1, I tried your example and it works fine as far as I can tell:  Content becomes Contents and News remains News when pluralized.
Comment: What does the 'Content' class look like?
Answer: FWIW I tested this with Django 1.1.1 and Django 1.2.1 and it worked as expected in both cases.
Comment: I redid this from scratch and it started working, so it was probably some screwy configuration.


Farsi regular expression in Python

Question: I have this Python regular expression code in Python 3 that I do not understand. I appreciate any help to explain what exactly it does with a few examples. The code is this:
# encoding=utf-8
import re
newline = re.sub(r'\s+(((زا(ی)?)?|ام?|ات|اش|ای?(د)?|ایم?|اند?)[\.\!\?\،]*)', r'\1 ', newline)

Answer: here is your regular expression:
\s+(((زا(ی)?)?|ام?|ات|اش|ای?(د)?|ایم?|اند?)[\.\!\?\،]*)

and here is a visualization:

Debuggex Demo
Your replacement is r'\1 ' which means replace what you found with the 1st group followed by space. I don't read farsi, but here is another example:
\s+((a|b)[./?]*)

Debuggex Demo
so let's execute some code:
>>> newline = '     a?    b?        a.'
>>> re.sub('\s+((a|b)[./?]*)', r'\1 ', newline)
'a? b? a. '

This eats extra spaces preceding a particular group of characters (the leading \s+) and changes it to the identified group 1 followed by one space (r'\1 ').
Comment: provided your `newline` is unicode, you'd get the same thing, because there no extra spaces. `r'\1 '` will preserve everything in group 1 except the spaces.
Comment: Thanks for the answer. Based on the above figure, isn't the first group Group 1? Then what you said becomes confusing. Can you elaborate a little more please? For example if I have: `newline = 'رفته اند'`, what should I get after running the code?

Farsi regular expression in Python