Valor de Textbox criado dinamicamente na Page da Multipage (que também é criada dinamicamente) não se matém quando muda de Page

Question: Boa Noite,
Estou fazendo um controle no excel, no codigo há criação automatica de Pages e também de controles, como o TextBox, criados dinamicamente dentro dessas Pages.
A Page 1 já vem os controles já colocados, eu só copio e colo nas outras Pages que serão inseridas automaticamente.
Porém o valor dos outros controles nas outras Pages não se conserva.
Nas fotos abaixo, tem-se a pagina 1 e 2, perceb-se que a ifnormação da pagina 1 não vai para pagina 2 e isto está correto, é isso que eu quero, informações diferentes em cada pagina.
Porém, ao colocar informação na Page 2 (ou em qualquer outra Page que não seja a Page 1) essa informação não fica no textbox, ou seja simplemente some.
Obs: Essas páginas são criadas por meio do SpinButton, onde ao crescer a quantidade, adciona paginas e ao apertar para baixo do spin, remove as paginas. E as paginas criadas são baseadas no valor da caixa de texto, onde o valor do spinbutton é referenciado.
Código abaixo:
<code>*- Evento change da Page*

Private Sub MultiPage1_Change()
    Dim varA As Integer
    Dim clt As Control
    varA = Me.MultiPage1.Value
    var = Me.MultiPage1.Pages.Count

       MultiPage1.Pages(0).Controls.Copy
    If varA > 0 Then

             With MultiPage1.Pages(varA)
             .Paste
             For Each ctl In .Controls
              Select Case TypeName(ctl)

                    Case "TextBox": ctl.Value = ""

              End Select
           Next ctl
           End With
    End If
end sub

*-Evento do SpinButton*

Private Sub DPNs_SpinDown()
    Dim pag As Page
    Dim var As Integer
    var = Me.DPNs.Value
    varA = MultiPage1.Pages.Count
          MultiPage1.Pages.Remove var
       If var = 0 Then

         MultiPage1.Pages.Remove var
        MultiPage1.Pages.Controls.Remove
         End If

    If varA < 0 Then

        MsgBox ("Paginas Removidas com Sucesso")

End If

End Sub

Private Sub DPNs_SpinUp()

     MultiPage1.Pages.Add ("PartNumber" & DPNs.Value + 1)

End Sub

*-Código da Caixa de texto ao lado do SppinButton*

Private Sub QtdPN_Change()
Dim NovaVar As Integer

        NovaVar = Val(QtdPN.Text)
        If NovaVar >= DPNs.Min And NovaVar <= DPNs.Max Then
        DPNs.Value = NovaVar
        End If

End Sub

*- Codigo Change SpinButton*
Private Sub DPNs_Change()

QtdPN.Text = DPNs.Value

End Sub

</code>
Answer: Esse código está adicionando TextBoxes a cada seleção de página que o usuário faz. Então, se a Page for selecionada, por exemplo, 3 vezes, haverá um total de 3 * o número de TextBoxes em Pages(0), resultado das colagens realizadas a cada ativação.
Para resolver isto, elaborei uma rotina em que a criação e eliminação de Pages do MultiPage são feitas adequadamente no evento do SpinButton. Adapte o código à sua realidade.
<code>Option Explicit

Private Sub DPNs_SpinDown()
'excluir page do Multipage1
    If MultiPage1.Pages.Count > 1 Then    'não é possível excluir a única página existente
        MultiPage1.Pages.Remove Me.MultiPage1.Pages.Count - 1
    End If
    Me.QtdPN = DPNs.Value
End Sub

Private Sub DPNs_SpinUp()
'adicionar page ao Multipage1
    Dim oPage As MSForms.Page
    Dim CTL As MSForms.Control
    Dim intPageCount As Integer

    intPageCount = MultiPage1.Pages.Count    'inicia em 1

    MultiPage1.Pages.Add ("PartNumber" & intPageCount)
    Set oPage = MultiPage1.Pages(MultiPage1.Pages.Count - 1)
    MultiPage1.Pages(0).Controls.Copy
    oPage.Paste
    For Each CTL In oPage.Controls
        If TypeName(CTL) = "TextBox" Then
            CTL.Text = ""
        End If
    Next
    Me.QtdPN = Me.DPNs.Value
End Sub
</code>


Layout for Android App

Question: I googled this think very much time , and I get nothing. I want to know if there is a way to create layouts for android apps in the illustrator , and be able to use them like you made in an XML file. I know this is a dumb question , but I'm newbie in android apps , and I'm very curios , because I want to make a very custom grid view wich I can't make it like in old way ,or even through code.. or I think I can do it with math code , but it will be very painful !! Thank you every one for interest.
Comment: http://stackoverflow.com/help/how-to-ask
Comment: What do you mean by "in the illustrator" ? Do you mean Adobe Illustrator, or the "Design" tab in the IDE layout editor?
Answer: There are some Toolkits for Android you can find them under:
http://developer.android.com/design/downloads/index.html
But as far as I know it is not possible to create an xml layout for android under adobe illustrator. However a grid layout is a grid. If you want something special you have to use a relative layout. You could also use canvas or drawables, it depends of what you want.
First of all you have to do it programmatically, under the following link is a tutorial of how you can build up an hexgrid.
https://github.com/riotopsys/Hexgrid
If you're done with it you can add a circle button to every corner. Just use a drawable button for this.
Comment: ok man , thank you for your effort !! this is what I was looking for
Comment: I want an hexagon grid with 19 hexagon and in every corner of the hexagon to be an circle grid wich I can click at , and change his aspect . And also in every hex Grig I want an circle grid... How do you think I  can accomplish that ?
Comment: Added tutorial in answer

Layout for Android App


Javascript find() method not working for nested object/array/json values

Question: I am trying to figure out why the nested find() method is not working. Here is my data structure
const arr = [
    {id: 1, name: "one"},
    {id: 2, name: "two"},
    {id: 3, name: "three"},
    {id2: [
        {id3: 30, name: "thirty"},
        {id3: 50, name: "fifty"},
        {id3: 70, name: "seventy"}
        ]
    }
]

The idea is to access the id3 values for which I am using the nested find() method like this:
const ret = arr.find(function(el){
    return el.id2.find(function(elps){
        return elps
    })
})

Interestingly, I am intermittently getting two different errors.

TypeError: Cannot read property 'find' of undefined

OR I get

find is not a function...

I also tried using some() method for the second iteration but it returns the same errors.
If I use find() on the parent level(1st iteration) array it works fine like this:
const ret = arr.find(function(el){
        return el.id > 2
})

My question: What is that I am missing in second iteration that the find() method is not working there?
Comment: Not all of the objects in your array have an "id2" property, so that's where the `undefined` error is coming from. The `.find()` function called inside the outer `.find()` will return `true` for all the objects in the "id2" array, so it really doesn't make any sense.
Comment: What exactly is your desired result?
Answer: You can use Array.isArray() before implementing the nested find() to avoid using it on an undefined property or property where value isn't an array
It's not really clear what your expected result is so the following returns the main array object that contains a matching sub-array element

const arr = [
    {id: 1, name: "one"},
    {id: 2, name: "two"},
    {id: 3, name: "three"},
    {id2: [
        {id3: 30, name: "thirty"},
        {id3: 50, name: "fifty"},
        {id3: 70, name: "seventy"}
        ]
    }
]

const res = arr.find(({id2}) => Array.isArray(id2) && id2.find(({id3}) => id3 === 30))
console.log(res)


Flutuar 2 divs lado-a-lado com ponta triangular

Question: Essa está sendo difícil, e vou explicar o porquê, tenho duas divs como no print abaixo, o site é responsivo, elas devem flutuar lado a lado, porém, essas divs têm pontas triangulares, e elas devem escalar horizontalmente até determinado breakpoint que eu determinar, no caso, a div da cor vermelha em telas pequenas xs: 320px teria largura de 100% e a segunda eu iria ocultar. mas em telas grandes lg: 1200px, teriam de ficar da forma que está no print, mas não quero que quebre caso o monitor seja um pouco menor que 1200.
Já tentei de algumas formas aqui mas o bloco escuro sempre quebra.
Gostaria de sugestões.
Vejam o código que fiz: http://codepen.io/leandroruel/pen/OyJErX
Comment: Sugestão: poste o codigo que tens para podermos testar e fazer os ajustes necessários
Comment: dá uma olhada agora amigo.
Comment: Quando diz que não quer que ele quebre quer que ele suma ou fique a direita do bloco vermelho? ( já tenho ele pronto só falta esse detalhe e eu posto como resposta )
Answer: Vou postar como resposta mas não sei se quer que o bloco branco fique oculto ou fique a direita do bloco vermelho então qualquer coisa você me comenta abaixo que eu edito a resposta

products

Linha Racing

Terceiro bloco Coloque seu texto aqui

Aqui no site ele não abre o tamanho desejável então dei um fork no seu codepen e fiz outro
Edit: Atualizei o codepen
Comment: é...falta o bloco escuro, se você conseguir me mostrar um modo dele ficar lado a lado também e sumir em 320px
Comment: Amanhã eu édito então, agora to no celular...
Comment: @user3632930 esta atualizado o código no codepen também


wordpress manage theme option disabled

Question: I was trying to add phone number on the right hand side of my header.  So I went to Appearance customize and change under site title and tagline enter the phone number.
  But later Want to change to but all three options side title & tagline, navigation and static
  frontpage menu is disabled when i try to click the arrow it dosen't work.
Here's a link for website.
Click here for image
Answer: You may have a JavaScript error in your theme when viewing the customisation pane.  JavaScript errors can (sometimes) cause unrelated areas to not function properly as the JavaScript engine essentially falls over.
I would suggest trying the same with a stock theme (Twenty Twelve, for example), so you can find if it is a theme-specific problem.  If it is a problem with the theme then you can consult with the author of the theme.
Comment: Yes, Twenty Twelve theme works fine, Thanks for your help I will consult author of the theme

wordpress manage theme option disabled


Hyperlink expression in SSRS Report to pass parameter to ASP.NET app

Question: I have a basic SSRS report and I would like to be able to click on an item on my report to go to one of my asp.net pages (one intended for updating records) and I'd like to pass in the primary key to the asp page, so that on pageload it gets passed to a stored proc on page load and can populate text boxes and dropdown menus accordingly.  I'm just unsure of how to structure the expression for the hyperlink in the report designer in order to do so.  Maybe through a query string?

How do I structure the hyperlink expression in SSRS?
How do I accept the parameter in the c# codebehind on Page_Load to use in SQL Query?

Thank you for any help in illuminating this for me.  I've tried my own research on seemingly a ton of sources but none are overly clear to me.
Edit: Including an attempt to try and illustrate what I'm trying to do.
For the hyperlink expression in SSRS, I'm attempting with
="http://10.155.54.101/Update?CurrencyId="+Fields!CurrencyId.Value

Which generates the following error: [rsRuntimeErrorInExpression] the Hyperlink expression for the textbox 'Model' contains an error: Input string was not in a correct format.  Which is strange because I've seen that format in other sources be referenced as correct.  Eg. http://www.advancedssrs.com/2014/01/how-can-i-use-dynamic-hyperlinks.html
But either way, my c# codebehind for receiving the paramater (which I haven't been able to test yet) is as follows
if (Request.QueryString != null){
int CurrencyId = int.Parse(Request.QueryString["CurrencyId"]);
//Additional logic here
}

Am I roughly on the right track?
Comment: Possibly. Could try `Cstr(Fields!CurrencyId.Value)`
Comment: You may want to try an `&` sign instead of the `+` sign.
Comment: I made the substitution, same error.

="http://10.155.54.101/Update?CurrencyId="&Fields!CurrencyId.Value
Comment: Is the `Fields!CurrencyId.Value` an integer?
Comment: Hmm, yes it is.  Is it needing a string?
Comment: Perfect.  That worked.  Make that an answer and you can get the points haha.
Answer: The value in the hyperlink needs to be a string. Convert the value using Cstr()
="http://10.155.54.101/Update?CurrencyId=" & Cstr(Fields!CurrencyId.Value)

Comment: Shouldn't that be: `="http://10.155.54.101/Update?CurrencyId=" & Cstr(Fields!CurrencyId.Value)`


How create cluster plots for large datasets in R

Question: I use the CLARA algorithm from Kaufman and Rousseeuw to cluster a large dataset with N > 8*10^6 in R. The implementation of the algorithm itself allows the user to control execution time by e.g. limiting the samplesize to n=100.
However it seems that the use of the plot() function in R includes all data-objects to the plot which results in a very large processing time and very crowded plots (see the reproducible example below).
In theory it should be possible to only plot the best sample from CLARA instead of N. Is there an implementation for this or how can I work around this issue?
## generate 2.5 mio objects, divided into 2 clusters.
x <- rbind(cbind(rnorm(10^6,0,0.5), rnorm(10^6,0,0.5)),
           cbind(rnorm(1.5*10^6,5,0.5), rnorm(1.5*10^6,5,0.5)))

library("cluster")
# get clusters solution
clara.x<-clara(x,k=2,sampsize = 100)
# see medoids
clara.x$medoids

# plot the cluster solution
plot(clara.x) # takes long time. creates crowded plot
clusplot(clara.x) # did not finish

Answer: First off, it seems like plot() for clara objects gives two plots, the first being identical to that returned by clusplot(). If the former finished but the latter did not, I'm guessing that's just because you're clogging up the plot history. If you save large plots to png you won't run into this problem. They'll still take a while, but it won't interfere with whatever else it is you're doing.
Regarding reducing the number of plotted points, we can do this manually by adjusting the list elements of clara.x. You just have to choose which points you want to plot. Below, I give an example where I just use the samples from the clara method. But if you want to plot more you can choose with sample() or something:
# Manually shrinking clara object
samp <- clara.x$sample
clara.x$data <- clara.x$data[samp, ]
clara.x$clustering <- clara.x$clustering[samp]
clara.x$i.med <- match(clara.x$i.med, samp) # point medoid indx to samp

# plot the cluster solution
clusplot(clara.x)

One delicacy is that the medoid samples must always be in whatever indices you choose to plot, otherwise the 5th line above won't work. To ensure this for any given samp, add the following after the 2nd line above:
samp <- union(samp, clara.x$i.med)

ADDENDUM: Just saw the 1st answer, which is different from mine. He is suggesting to re-compute the clustering. A benefit to my approach is it maintains the original clustering computation and only adjusts which points you plot.
Answer: I'm not familiar with the CLARA method, so this answer responds directly to your question about how to "plot the best sample from CLARA."
A quick review of ?clara.object shows that the case numbers of the sample used in the final partition is found in the sample component, hence you can recover the observations by
best_samp <- x[clara.x$sample, ]

Output:
par(mfrow = c(1, 2))
plot(best_samp, main = "scatterplot")
clusplot(clara(best_samp, k = 2, sampsize = nrow(best_samp)),
  main = "clusplot")


When can a given element in a monoid be decomposed into the product of a given element and another element?

Question: Let me begin with the particular monoid that I was origionally interested in, which was the set of real valued functions of a single real variable with the composition operation. My question was this, given functions $f$ and $g$, when can we find $h$ such that $f = hg$? Now clearly if $g$ is invertible, then putting $h = fg^{-1}$ works. However, even where $g$ is not invertible, we can still sometimes find $h$. For example, with $f(x) = 2x^{2}$ and $g(x) = x^{2}$, we can set $h(x) = 2x$. A little more thought shows that if $g(x_{1}) = g(x_{2})$, then $f$ must likewise take on the same values at $x_{1}$ and $x_{2}$ if we are to find an $h$. Is this condition also sufficient? This all feels a bit messy and specific though. So here is my question:
Let (M,*) be a monoid. Let $a,b \in M$, with b non invertible. Can we say anything at all about when there will exist $c \in M$ such that a = cb ?
Comment: In a general monoid you will hardly be able to say anything more specific than: Such $c$ exists when it exists.
Answer: Let me answer your question in two steps.
Step one. The $\leqslant_\mathcal{L}$-preorder.
Let $M$ be a monoid. The notion you define is a relation (due to Green) known as the $\leqslant_\mathcal{L}$-preorder. It can be defined as follows:

$x \leqslant_\mathcal{L} y \iff Mx \subseteq My$.

This means that the left ideal generated by $x$ is contained in the left ideal generated by $y$. Equivalently

$x \leqslant_\mathcal{L} y \iff {}$there exists $z \in M$ such that $x = zy$.

The preorder $\leqslant_\mathcal{L}$ can be defined on any semigroup $S$. Let us denote by $S^1$ the monoid equal to $S$ if $S$ is a monoid and equal to $S \cup \{1\}$, where $1$ is an identity for $S$,
if $S$ is not a monoid. Then the definition is modified as follows

$x \leqslant_\mathcal{L} y \iff S^1x \subseteq S^1y \iff {}$ there exists $z \in S^1$ such that $x = zy$.

The preorder $\leqslant_\mathcal{L}$ is part of the Green's relations, which are thoroughly studied in any textbook on semigroup theory.
Step two. What can be said about the $\leqslant_\mathcal{L}$-preorder?
Consider the case you are interested in, or more generally the monoid $T(X)$ of all functions from a set $X$ to itself, under composition. Given $f \in T(X)$, let
$$
\ker(f) = \{(x,y) \in X^2 \mid f(x) = f(y) \}
$$
I claim that

$f \leqslant_\mathcal{L} g$ if and only if $\ker(g) \subseteq \ker(f)$.

Indeed, if $f = h \circ g$ and $g(x) = g(y)$, then $f(x) = f(y)$. For the opposite direction, it suffices to adapt your argument as follows: if $\ker(g) \subseteq \ker(f)$, then the relation $h = f \circ g^{-1}$ is actually a function such that $f = h \circ g$.
Since any monoid $M$ is isomorphic to a submonoid of $T(M)$, it is tempting to generalize this result to arbitrary monoids, which leads to the following question: if $S$ is a subsemigroup of $T$, what are the connections between the preorders $\leqslant_\mathcal{L}$ on $S$ and on $T$? Let me indicate a partial result in this direction:

Let $T$ be a subsemigroup of a semigroup $S$ and let $s, t \in T$ with
  $t$ regular in $T$. If $s \leqslant_\mathcal{L} t$ in $S$, then $s \leqslant_\mathcal{L} t$ in $T$.

A similar result holds without any regularity assumption in two cases: when $S$ is an ideal of $T$ and when $S$ is a local subsemigroup of $T$.

Let $T$ be an ideal of a semigroup $S$ and let $s, t \in T$. If $s \leqslant_\mathcal{L} t$ in $S$, then $s \leqslant_\mathcal{L} t$ in $T$.
Let $e$ be an idempotent of a semigroup $S$ and let $T = eSe$. If two
  elements $s$ and $t$ of $T$ satisfy $s \leqslant_\mathcal{L} t$ in
  $S$, then $s \leqslant_\mathcal{L} t$ in $T$.


I have some problem about edit DataTable by DTedit package in shiny r

Question: my.callback.update, my.callback.insert, my.callback.delete functions don't work and the table after editing don't save.
I tried making this in shiny r
app.R
library(shiny)

library(shinydashboard)

library(DTedit)

ui <- dashboardPage(

  dashboardHeader(title = "EditDatatable"),

  dashboardSidebar(

    sidebarMenu(

      menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard"))

      )
  ),

  dashboardBody(

    tabItems(

      tabItem(tabName = "dashboard",

       fluidPage(

         fluidRow(

           uiOutput('mycontacts')

         )

       )

      )

    )

  )

)

server <- function(input, output) {

  load("D:\\editDatatable/mydata.RData")

 my.insert.callback <- function(data, row) {
    mydata <- rbind(data, mydata)
    return(mydata)
  }

  my.update.callback <- function(data, olddata, row) {
    mydata[row,] <- data[1,]
    return(mydata)
  }

  my.delete.callback <- function(data, row) {
    mydata[row,] <- NULL
    return(mydata)
  }

  # save(mydata, file = "D:\\editDatatable/mydata.RData")

  output$mycontacts <- renderUI(

    DTedit::dtedit(input, output,

                  name = 'mycontacts',

                  thedata = mydata,

                  edit.cols = c('name', 'email', 'useR', 'notes'),

                  edit.label.cols = c('Name', 'Email Address', 'Are they an R user?', 'Additional notes'),

                  input.types = c(notes='textAreaInput'),

                  view.cols = c('name', 'email', 'useR', 'notes'),

                  my.callback.update = my.update.callback,

                  my.callback.insert = my.insert.callback,

                  my.callback.delete = my.delete.callback)

)}

shinyApp(ui, server)

In the result I must take:
https://www.r-bloggers.com/editable-datatables-for-shiny-applications/
Help me, please. Thanks!
Comment: 1. Please provide a reproducing example with data or dummy data. 2. Looks like you are not defining your callback functions.
Answer: Unfortunately, the documentation currently (21st June 2020) shown on the README of jbryer/DTedit is misleading about the contents of data/olddata/row, as is mentioned in some of the comments on JBryer's blog page about DTedit.
Here is revised documentation as described on my current modified version of DTedit, describing what data/olddata/row actually contain.
my.insert.callback <- function(data, row) {
  # 'data' contains the dataframe *after* the row has been inserted/added
  # 'row' is the row number where data has been inserted
  mydata <<- rbind(mydata, data[row,])
  # in this case, 'mydata' should just be the same as 'data'
  return(mydata)
}

my.update.callback <- function(data, olddata, row) {
  # 'data' contains the dataframe *after* the row has been updated
  # 'row' is the row number where data has been updated
  # 'olddata' is the previous version of the data
  mydata[row,] <<- data[row,]
  # in this case, 'mydata' should just be the same as 'data'
  return(mydata)
}

my.delete.callback <- function(data, row) {
  # 'data' contains the dataframe *before* the row has been deleted
  # 'row' is the row number where data is to be deleted
  mydata <<- mydata[-row,]
  # in this case, 'mydata' should just be the same as data[-c(row),]
  return(mydata)
}

An example of the correct use of callback functions is shown in the dtedit_demo of jbryer/DTedit.
Even more examples are shown in my vignette of DTedit on RPubs, but quite a few of those examples are specific to modifications I made to DTedit.


Customizing Windows Authentication in ASP.NET Core

Question: I noticed that I can enable Windows Auth in my ASP.NET Core app by enabling windowsAuthentication parameter in my launchSettings.json file:
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      // ...
    }

Is there an easy way to make the authentication a bit more restrictive and allow only users who belong to a specific group in my domain?
I remember implementing this once manually and now I wonder if a feature like this is supported by .NET automatically.
I use .NET6.
EDIT
Something I have in mind (it's not a valid code, rather loud-thinking):
app.UseRouting();

app.Use(async (context, next) =>
{
    if (userBelongsToGroup(@"MySuperGroup"))
    {
        await next();
    }
    else
    {
        context.Response.StatusCode = 401;
        return;
    }
});

app.UseAuthorization();

Comment: Does this answer your question? [Windows authentication on ASP.NET Core 5 MVC for AD groups](https://stackoverflow.com/questions/66671364/windows-authentication-on-asp-net-core-5-mvc-for-ad-groups)
Comment: Hi @mason and thanks for your comment. I'm searching for something more like this https://stackoverflow.com/questions/53191160/how-to-check-if-user-is-member-of-group.
Comment: Anyway, both your link and mine make me think there's no way to make everything work automagically.
Comment: Btw. I've updated my question to make it clearer about my expectations.
Answer: I decided to implement my own IApplicationBuilder extension and return 401 if a user does not belong to a specified group:
public static class CheckAuthorizationMiddleware
{
    [SupportedOSPlatform("windows")]
    public static IApplicationBuilder EnsureADGroup(this IApplicationBuilder app, string groupName)
    {
        return app.Use(async (context, next) =>
        {
            var groups = (context.User.Identity as System.Security.Principal.WindowsIdentity).Groups;
            var names = groups.Select(group => group.Translate(typeof(System.Security.Principal.NTAccount)).ToString());

            if (names.Contains(groupName))
            {
                await next();
            }
            else
            {
                context.Response.StatusCode = 401;
                return;
            }
        });
    }
}

In my case it works just fine, but if there are better ways of implementing this, don't hesitate to post a comment and tell me about it :).
Answer: Maybe you could try with authorize filter as below;
public class AdminRequired : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
             var claims = context.HttpContext.User.Claims.ToList();
            if (somelogic)
            {
                UnauthorizedResult result = new UnauthorizedResult();
            }
        }
    }

add [TypeFilter(typeof(AdminRequired))] on the target action
Comment: Would be nice, but I don't use MVC. My app just returns a single HTML with a bundled JS logic.
Comment: Unless you meant something else than an MVC action. Then can you please tell a bit more details? :)


Creating UIActionSheet

Question: I would like to create this kind of menu, of course with other menu buttons. Is there any default viewcontroller representing it, or do I have to get images and create this by myself.
Comment: The title and popularity of this question is much better than the duplicate. It would be nice to have this question reopened so that updated answers could be added.
Comment: Vote to reopen please.
Comment: @Suragch you are right. it is more helpful and understandable than other links
Answer: You need to use a UIActionSheet.
First you need to add UIActionSheetDelegate to your ViewController.h file.
Then you can reference an actionsheet with:
  UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@"Select Sharing option:" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:
                        @"Share on Facebook",
                        @"Share on Twitter",
                        @"Share via E-mail",
                        @"Save to Camera Roll",
                        @"Rate this App",
                        nil];
   popup.tag = 1;
  [popup showInView:self.view];

Then you have to handle each of the calls.
- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex {

  switch (popup.tag) {
    case 1: {
        switch (buttonIndex) {
            case 0:
                [self FBShare];
                break;
            case 1:
                [self TwitterShare];
                break;
            case 2:
                [self emailContent];
                break;
            case 3:
                [self saveContent];
                break;
            case 4:
                [self rateAppYes];
                break;
            default:
                break;
        }
        break;
    }
    default:
        break;
 }
}

This has been deprecated for iOS 8.x
https://developer.apple.com/documentation/uikit/uialertcontroller#//apple_ref/occ/cl/UIAlertController
Comment: +! for being the only one to call it a `UIActionSheet` (as well as providing a good answer).
Comment: with iOS 8 there is a new UIAlertController https://developer.apple.com/library/ios/documentation/uikit/reference/UIAlertController_class/index.html#//apple_ref/occ/cl/UIAlertController
Comment: I was literally working on my app as I saw the question! It comes from my code verbatim ;)
Comment: it is also working without  adding UIActionSheetDelegate .. I want to know how...
Comment: re the Sep 24, '14 comment and edit, there is a new UIAlertController and UIActionSheet is deprecated as of iOS 8, but to say that it has "changed" is not fully accurate. It might be better to include the link to the class reference but say that it is deprecated rather than changed.
Comment: NOTE: `[popup showInView:[UIApplication sharedApplication].keyWindow];` does not work alot of the time on iPad apps, show it in your current UIView instead.
Comment: @AlbertRenshaw you are correct. You can use self or comparable and show in current view.
Answer: Take a look at the UIActionSheet documentation.
NSString *actionSheetTitle = @"Action Sheet Demo"; //Action Sheet Title
NSString *destructiveTitle = @"Destructive Button"; //Action Sheet Button Titles
NSString *other1 = @"Other Button 1";
NSString *other2 = @"Other Button 2";
NSString *other3 = @"Other Button 3";
NSString *cancelTitle = @"Cancel Button";
UIActionSheet *actionSheet = [[UIActionSheet alloc]
                              initWithTitle:actionSheetTitle
                              delegate:self
                              cancelButtonTitle:cancelTitle
                              destructiveButtonTitle:destructiveTitle
                              otherButtonTitles:other1, other2, other3, nil];
[actionSheet showInView:self.view];

Answer: It is called an UIActionSheet: You create one like so:
    NSString *actionSheetTitle = @"Action Sheet Demo"; //Action Sheet Title
NSString *destructiveTitle = @"Destructive Button"; //Action Sheet Button Titles
NSString *other1 = @"Other Button 1";
NSString *other2 = @"Other Button 2";
NSString *other3 = @"Other Button 3";
NSString *cancelTitle = @"Cancel Button";
UIActionSheet *actionSheet = [[UIActionSheet alloc]
                              initWithTitle:actionSheetTitle
                              delegate:self
                              cancelButtonTitle:cancelTitle
                              destructiveButtonTitle:destructiveTitle
                              otherButtonTitles:other1, other2, other3, nil];
[actionSheet showInView:self.view];

Implement the UISctionSheetDelegate to respond to button action.
Take a look at this tutorial for more info: http://mobile.tutsplus.com/tutorials/iphone/uiactionsheet_uiactionsheetdelegate (Code is from this tutorial)
Answer: What you are looking for is called an actionsheet. Read more about it here http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIActionSheet_Class/Reference/Reference.html

Creating UIActionSheet


Como consertar indexação de um site no Google

Question: Tenho um site que já está indexado pelo Google, mas como já publiquei no endereço quando o site ainda estava em testes, o Google indexou alguns resultados como URLs quebrados, páginas teste, descrições erradas , etc.
Preciso criar um novo domínio para indexar tudo de maneira correta, ou há alguma forma manual para fazer a re-indexação desse site?
Answer: O google re-indexa automáticamente o site. Existem ferramentas do Google para isto. Dê uma iolhada nesta pergunta sobre isso: Como remover um site do Google?
À parte disso eu diria que o google gosta de estabilidade. Um dominio demasiado novo não vai receber muita atênção do Google, por isso mudar de dominio demasiado facilmente é mau.
O que você deve fazer é criar um site map e fazer redirects das páginas que não existem.
Sobre sitemap, é um ficheiro som nome sitemap.xml que deve estar na toor do site com informação sobre os links do site. Pode gerar um automaticamente aqui: http://www.xml-sitemaps.com/ e depois editar para corrigir detalhes.
O Google tem uma página (em Inglês) bem informativa sobre o sitemap: https://support.google.com/webmasters/answer/183668?hl=en
Fica um exemplo da sintaxe:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
  xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
  <url>
    <loc>http://www.example.com/foo.html</loc>
    <image:image>
       <image:loc>http://example.com/image.jpg</image:loc>
    </image:image>
    <video:video>
      <video:content_loc>
        http://www.example.com/video123.flv
      </video:content_loc>
      <video:player_loc allow_embed="yes" autoplay="ap=1">
        http://www.example.com/videoplayer.swf?video=123
      </video:player_loc>
      <video:thumbnail_loc>
        http://www.example.com/thumbs/123.jpg
      </video:thumbnail_loc>
      <video:title>Grilling steaks for summer</video:title>
      <video:description>
        Get perfectly done steaks every time
      </video:description>
    </video:video>
  </url>
</urlset>


Object to string doesn't return expect result

Question: I'm using selenium on Python and I am converting the result of
name = browser.find_element_by_css_selector('elementname')

to string.
It is returning 'WebElement' and what I am doing to convert it is
fname = type(name).__name__

I need it to return the actual element, in which case, it'd be a username of whoever's profile 'browser' is.
I just don't know why I am returned 'WebElement'.
Thanks!
(I'm sure I don't need to provide the URL and element name, right?)
Comment: what exactly is not clear about the [documentation for type()](https://docs.python.org/3/library/functions.html#type) combined with the [documentation of the return type of find_element()](http://selenium-python.readthedocs.org/api.html?highlight=find_element_by_css_selector#selenium.webdriver.remote.webdriver.WebDriver.find_element) plz? I am not sure how to explain it, because to me it is obvious that the only thing that `type(WebElement()).__name__` should return is "WebElement", otherwise the world would stop spinning or something
Answer: find_element_by_css_selector() method returns a WebElement instance. Instead, you need the value of the .text property:
name = browser.find_element_by_css_selector('elementname')
print(name.text)

Comment: Thanks, you helped a lot!


Probability distribution vs probability space

Question: I was trying to understand the difference between the concepts of probability distribution and probability space for what concerns the assignment of probability over the sample space. Wikipedia gives the following definition for probability distribution:

A probability distribution is the mathematical function that gives the
probabilities of occurrence of different possible outcomes for an
experiment. It is a mathematical description of a random phenomenon in
terms of its sample space and the probabilities of events (subsets of
the sample space).

Which actually is the same definition which it gives also for a probability space, even if for this last one more formally introduces the concepts of a sample space $Ω$, an event space F (a σ-algebra) and a probability function P giving measures of probability for the events. Also, I would like to point out that a probability function is indeed one of the possible ways to uniquely define a probability distribution.
I would like to know if there is some difference between the two terms, if the difference is more of a contextual convention nuance, or if this is the actual formality and indeed which in case is the actual difference.
Comment: To begin with, Wikipedia's *characterization* -- it's not a definition -- is limited to probability spaces with only countable numbers of events of nonzero probability: essentially, discrete spaces.  It would be *far* better to characterize a distribution as a function assigning probabilities to *events* rather than outcomes.  Thus, your question really seems to be a matter of distinguishing colloquial descriptions from rigorous definitions.
Comment: I assume nothing: I am applying a standard definition.  When a probability measure is defined on all *individual* outcomes, that immediately implies the discrete sigma algebra is in use.  Please consult any advanced textbook on probability theory.  The reason why the Wikipedia quotation is not a definition is that it uses mathematically meaningless qualitative words to explain what kind of function a probability is, without supplying any criteria one can actually use to distinguish probability functions from any other kind of function.
Comment: @whuber why you say it's limited to discrete variable spaces? It seems to me that is more of your assumption than a limitation of Wikipedia's reported *characterization* (however you want to call it, I would say definition as it defines it, but in case tell why). What you have reported subsequently it's more the definition of a probability function than of a probability distribution, which can be described, by the way between the others, from a probability function. Also, in case, are you stating that they are the same for what concerns probability assignment over the sample space?
Answer: These two concepts are so strikingly different that it is really difficult for me to understand how they can be confused.  The confusion may stem from the ambiguous colloquial description you quoted (link?) which can be easily eliminated by presenting them with rigorous mathematical notations.
Short Answer: A probability space is a triple $(\Omega, \mathscr{F}, P)$, while a probability distribution is a (set) function. So they are very different.
Longer Answer: A probability space is a triple $(\Omega, \mathscr{F}, P)$ that contains a sample space $\Omega$, a $\sigma$-field $\mathscr{F}$, and a probability measure $P$, while a probability distribution (of a random variable $X$ that is a measurable function from $\Omega$ to $\mathbb{R}$) is a probability measure (i.e., a set function) defined on another measurable space $(\mathbb{R}^1, \mathscr{R}^1)$ where the random variable $X$ takes value on.
More Elaborations:  As I made it clear above, to make sense of the term "probability distribution" (let's denoted it by $\mu$), a random variable $X$ must be defined in advance on the probability space $(\Omega, \mathscr{F}, P)$. In particular, $\mu$ is different from the original probability measure $P$, but it is a probability measure induced by $P$ (sometimes called "push-forward measure") as follows:
\begin{align*}
\mu(A) = P(X^{-1}(A)) = P(\{\omega \in \Omega: X(\omega) \in A\}), \quad
A \in \mathscr{R}^1.
\end{align*}
Here $\mathscr{R}^1$ stands for the Borel field generated by open sets in $\mathbb{R}^1$. For this reason, $\mu$ is usually denoted as $P\circ X^{-1}$ or $P_X$. By any means, $\mu$ is a set function, which is obviously a different object compared to the probability space.
For completeness, I am quoting the formal definitions of these two concepts from an authoritative mathematics textbook (Probability and Measure (3rd edition) by Patrick Billingsley):

(Probability space) If $\mathscr{F}$ is a $\sigma$-field in $\Omega$ and $P$ is a probability measure on $\mathscr{F}$, the triple $(\Omega, \mathscr{F}, P)$ is called a probability measure space, or simply a probability space.

(Probability distribution) The distribution or law of the random variable is the probability measure $\mu$ on $(\mathbb{R}^1, \mathscr{R}^1)$ defined by
\begin{align*}
\mu(A) = P[X \in A], \quad A \in \mathscr{R}^1.
\end{align*}

Comments on your Quotation:

A probability distribution is the mathematical function that gives the probabilities of occurrence of different possible outcomes for an experiment.

In my opinion, this sounds more like a description of $P$ in the original probability space, instead of $\mu$ on $(\mathbb{R}^1, \mathscr{R}^1)$.

It is a mathematical description of a random phenomenon in terms of its sample space and the probabilities of events (subsets of the sample space).

Again, this "It" is better (if I have to) interpreted as $P$ -- accordingly the sample space and subsets of the sample space in this quotation correspond to $\Omega$ and $\mathscr{F}$ respectively.
In summary, I think the author of your quotation had confused "$P$" and "$\mu$" -- when he/she drafted this paragraph, he/she probably had $P$ in his/her mind and tried to elaborate it in words, for the random variable $X$, which is a prerequisite to define the term distribution, looks completely slipped away.
Comment: Re "very different:" not really, once you remember that part of a function is its domain; that its domain is a sigma algebra; and that algebra determines its underlying space (which is the union of the elements of the algebra). In the Wikipedia characterization the algebra is generated by all singletons ("outcomes"). In the special circumstances envisioned in Wikipedia, from a nonzero function $f:X\to\mathbb R$ we recover $\mathfrak F=\mathcal P(X)$ (the power set), $\Omega=\bigcup_{A\in\mathfrak F}A=X,$ and $\Pr:\mathfrak F\to\mathbb R$ *via* $\Pr(A)=\sum_{\omega\in A}f(\omega).$
Comment: I am assuming you are trying to argue that $P$ and $(\Omega, \mathscr{F}, P)$ are not "very different" (which is slightly different from OP's original question unless he interprets "probability distribution" as "probability measure").  I think that depends on how "tolerant" you are in viewing two mathematical objects are the same or different.  For me, $(\Omega, \mathscr{F}, P)$ and $P$ are still "very different" in spite of their connections as you pointed out, because the latter is only a part/a component of the former.
Comment: My point is that the *definition* of $P$ includes its domain $\mathfrak F,$ so the only distinction you are making is to insist that the ordered pair $(\Omega, \mathfrak F)$ is not the same as $\mathfrak F.$ Agreed, but I find the distinction to be of little interest, because it's a mere notational matter having no underlying substance.
Comment: @whuber To be honest, your perspective is really new to me and I have to say I couldn't accept that.  And I don't see any benefits of taking this view to intentionally blur the boundary of $(\Omega, \mathscr{F}, P)$ and $P: \mathscr{F} \to [0, 1]$. Also, the main point of my answer is not trying to compare $(\Omega, \mathscr{F}, P)$ with $P$, but $(\Omega, \mathscr{F}, P)$ with $\mu$.
Comment: @Zhanxiong probably you are too smart to even be on the platform if you cannot understand how they can be confused. But not enough to 1)understand that it may happen that most people don't grasp concepts that are easy to others; 2) to carefully read a question before answering. The key part in the question was 'for what concerns the assignment of probability'. Also, as said, the quoted text is from Wikipedia for probability distribution, so you can access it just by reading the 'Probability distribution' on Wikipedia.
Comment: @Zhanxiong What you said to be 'more like a description of P' it's not. A probability function is defined on a σ-algebra and not on the sample space (relevant difference when it comes to continuos variables). "It is a mathematical description of a random phenomenon in terms of its sample space and the probabilities of events (subsets of the sample space)" this indeed is what the probability function does in the probability measure space and it is from Wiki again, and not me, which was causing confusion. By the way thanks to the definition you reported from the textbook I think I got my answer.
Comment: so thank you Zhanxiong. Point is that I think the probability distribution is just the mapping (distribution indeed) from the sample space to their probability. Something underlying the probability assignment itself, and that is part of the probaility space in that you have an underlying/latent mapping from the sample space to the probability measures (intermediated by the  σ-field). So for what concerns the probability assignment there is no difference as indeed a probability distribution is part of a probability space. Would you mind checking/brainstorming if it fits to you too @whuber
Comment: Also sorry for replying in many messages, it there a way to overcome the per comment characters limitation? @Zhanxiong I'm new to the platform so tricks are appreciated


C++ Calculation always printing out 11

Question: I'm currently writing a program to give the user a checksum based off numbers from a part of an ISBN that they input. My calculation for the 13-digit ISBN is giving me the right answers, but for some reason, the calculation for the 10-digit is always giving me 11, no matter what I put in.
cout << "Enter the digits one at a time, as if they were to be read from right to left." << endl;

cin >> digit_one;
cin >> digit_two;
cin >> digit_three;
cin >> digit_four;
cin >> digit_five;
cin >> digit_six;
cin >> digit_seven;
cin >> digit_eight;
cin >> digit_nine;

checksum = (11 - (((10, 9, 8, 7, 6, 5, 4, 3, 2) * (digit_one, digit_two, digit_three, digit_four, digit_five, digit_six, digit_seven, digit_eight, digit_nine)) % 11));

cout << "The checksum for this ISBN is " << checksum << endl;

Is there something simple that I'm missing? Thanks for the help in advance.
Comment: Comma operator doesn't do what you seem to think it does. Yes. Inconceivable. I know.
Comment: `(10, 9, 8, 7, 6, 5, 4, 3, 2) * (digit_one, digit_two, digit_three, digit_four, digit_five, digit_six, digit_seven, digit_eight, digit_nine)` will compile but it's pretty much nonsense, and most of all it doesnt' do what you think it should.
Answer: You seem to misunderstand how operator , works. (2, 3) yields 3, not a tuple like it would in Python.
In the same vein (2,3,4) * (1,2,3) is pretty much equivalent to 4 * 3.
So, in your code
checksum = (11 - (((10, 9, 8, 7, 6, 5, 4, 3, 2) * (digit_one, digit_two, digit_three, digit_four, digit_five, digit_six, digit_seven, digit_eight, digit_nine)) % 11))

is no different than
checksum = (11 - ((2 * digit_nine) % 11))

It's then safe to assume that your digit_nine is 0¹ and that's why finally checksum has the value of 11 - 0
¹ or a multiplication of 11 and not a digit at all
Comment: Thank you very much! As it turned out, the only reason I thought the 13-digit ISBN checksum calculator was working was because it coincidentally gave the right answer for the example I was using.

C++ Calculation always printing out 11


how to find tuples in haskell with same numbers

Question: How would you filter tuples in Haskell that have doubles within them such as (1,1) and (2,2) but not to remove them just to find them?
So far all i have is the start line
FilterDoubles.

Comment: what about example input/output. show at least as much effort as you would expect someone writing an answer for your question!
Comment: All you have is… what? The function's name? Also, what would you filter? A list of tuples?
Comment: what do you want to filter - lists? Foldables? - or do you want a function that can deal with tuples of different *sizes*?
Comment: yeh the functions name and it would be filtering a list of tuples.
Answer: Let
> let xs = [(1, 2), (3, 3), (4, 3)]

to filter (select only)
> filter (uncurry (==)) xs
[(3,3)]

to mark
> [(a == b, t) | t@(a, b) <- xs]
[(False,(1,2)),(True,(3,3)),(False,(4,3))]

play with and understand this expressions yourself!
Comment: Can you comment your -1 please?
Comment: it's not form me - but don't worry to much - probably someone disagreed with you answering a slightly bad question (it was probably no Haskeller here - but there are SO sheriffs that patrol every negative question and downvote/flat, etc. what they see as not helping encourage good questions and answer)
Comment: IMO your answer is fine and correct as far as we can know from the question and the only clarifying comment


qTip2 and Drupal 6 troubleshooting

Question: I am currently trying to implement a tooltip using the jQuery extension, qTip2. I have installed both of the files included in the extension (jquery.qtip.min.js and jquery.qtip.js in my /theme/js/ location, and their appropriate CSS sheets in /theme/css) and declared them in my theme's .info.
At the moment, I'm trying to write a function that displays the tooltip "Hello World" whenever someone hovers over an element of with the attribute #T6roll. I have the following as a script in my /sites/js/ location:
<code>Drupal.behaviors.magds = function (context) {
  // Sounds, if using class "sound", these "#T1roll, #T2roll, #T3roll, #T4roll" can be removed, ul.dropdown li a,
  $('ul.links li a, .sound, #T1roll, #T2roll, #T3roll, #T4roll').mouseover(function(){$.fn.soundPlay({url:Drupal.settings.magds.themeAbsolute+'flash/mouseover.wav',playerId:'embed_player',command:'play'});$("#sound").html("mouseover.wav");}).mouseout(function(){$.fn.soundPlay({playerId:'embed_player',command:'stop'});});

  // IE helpers
  if ($.browser.msie && ($.browser.version < 8)) {
    $('#main-menu li').hover(function() {
      $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
    });
  };
};

/*
 * implements jquery.qTip.js
 */

 (function($){
    $(document).ready(function() {
        $('a#T6roll).qtip({
            content: 'Hello World!',
            position: { target: 'mouse'}
        });
    });
 })(jQuery);
</code>
However, the site does not seem to be executing this. Is there any ideas as to what might be the cause of this? At first, I thought that it might be the qtip syntax, but I kept it as simple as can be to debug and it's not functioning.
Answer: After doing some research, it turns out that there is active development being done in the jQuery_Update module. Specifically, you may reference this post .
The issue with the jQuery_Update module is that it would only update your Drupal 6 jQuery install to v. 1.3.0. With the patch that is applied in the aforementioned post, you are able to update all the way to jQuery 1.7.
An alternative to this solution would have been to load jQuery from another location and use the noConflict() function. Drupal has some excellent documentation regarding this.

qTip2 and Drupal 6 troubleshooting


Why would change with "sed" via Putty not reflect in Cpanel?

Question: I did a word replace with "sed" via Putty and i see that the word was replaced but when I open the file in cpanel there is no change to the file.
Here's the command
sed 's/word1/word2/g' file.php

Why would this happen?
Answer: sed 's/word1/word2/g' file.php

prints out the changed version of the file. If you want to modify the file in-place, use the -i option:
sed 's/word1/word2/g' -i file.php


IRF for VAR GARCH (Impulse Response Function)

Question: When there is ARCH effects on VAR residuals $\varepsilon_t$, we can use a GARCH model to remove them : $\zeta_t = \Sigma_{t|t-1}^{-\frac{1}{2}} \varepsilon_t$.
Following [Lutkepohl, New Introduction to Multiple Time Series Analysis], coefficients of the IRF correspond to the coefficients of the well-known Moving-Average representation :
$\Delta P_{t} = J \mathbf{\Delta P}_{t} = \sum_{i=0}^{\infty} J \mathbf{\Phi}^i J^{\tau} J \mathbf{E}_{t-i} = \sum_{i=0}^{\infty} J \mathbf{\Phi}^i J^{\tau} \Sigma_{t-i|t-i-1}^{\frac{1}{2}} \Sigma_{t-i|t-i-1}^{-\frac{1}{2}} \varepsilon_{t-i} = \sum_{i=0}^{\infty} \mathbf{\Psi}_{i,t} \zeta_{t-i}$
And so the impulse response for a given $t$ after $N$ periods is the corresponding MA coefficient : $\mathbf{\Psi}_{N,t} = J \mathbf{\Phi}^N J^{\tau} \Sigma_{t-N|t-N-1}^{\frac{1}{2}}$.
I am not sure about the indices of $\Sigma$, should I use forecast of it ? Thanks for your help.
EDIT : Maybe I could directly apply IRF on VAR residuals, is it a necessary condition to remove ARCH effects to use IRF ? I don't think so, and so I could use : $\Delta P_{t} = \sum_{i=0}^{\infty} J \mathbf{\Phi}^i J^{\tau} \varepsilon_{t-i} = \sum_{i=0}^{\infty} \mathbf{\Psi}_{i,t} \varepsilon_{t-i}$.
And so the impulse response after N periods is the corresponding MA coefficient : $\mathbf{\Psi}_{N} = J \mathbf{\Phi}^N J^{\tau}$, which not depends on t anymore.
Answer: Since in the GARCH model the variance covariance matrix of the residuals $\Sigma_t$ is time varying you would have $t = 1, \ldots, T$ covariance matrices, each of which is associated to an impulse response. That's to say that the impulse responses will be time varying as well i.e for $t = 1980$ the impulse response function of output to a monetary policy shock is allowed to have a different shape with respect to impulse response for $t = 2000$.
This is completely unrelated to the time span you want to observe the effect of a shock on a given variable $t - N$.
That's to say you don't need to forecast anything, you just need to obtain the $\Sigma_t$ for $t=1, \ldots, T$, fix a time span and calculate the impulse responses.
Answering the second part, if you have GARCH effects in the true DGP and you estimate an homoskedastic VAR by OLS, you would get inefficient estimates of the coefficients (higher variance) and of the impulse responses as well.
Comment: Will autocorrelation yield inconsistent estimates? Biased for sure (even without autocorrelation) but inconsistent? Also, ignoring GARCH will not yield inconsistent, only inefficient estimates. Therefore I think at least your last comment is wrong.
Comment: Thanks @Giorgetto, that's exactly what I had in mind. But one thing I'm wondering, : maybe I could directly apply IRF on VAR residuals, is it a necessary conditions to remove ARCH effects to use IRF ? I don't think so, and so I could use :

$\Delta P_{t} = \sum_{i=0}^{\infty} J \mathbf{\Phi}^i J^{\tau} \varepsilon_{t-i} = \sum_{i=0}^{\infty} \mathbf{\Psi}_{i,t} \varepsilon_{t-i}$

And so the impulse response after $N$ periods is the corresponding MA coefficient : $\mathbf{\Psi}_{N} = J \mathbf{\Phi}^N J^{\tau}$, which not depends on $t$ anymore.
Comment: I have tried to answer also this bit
Comment: Thanks @Giorgetto, your answer was very clear. But using VAR-GARCH residuals instead of VAR residuals won't remove the serial correlation, it will juste remove ARCH effects, and so coefficients estimates will still be biased and inconsistent.
Is their a way to remove the serial correlation ? Papers don't mention this serial correlation issue before using IRF.
Comment: Ok I understand, thank you very much for your time, I accepted your answer :)
Comment: You are right I have tried to clean the answer
Comment: Thanks @RichardHardy for your precisions, I will finally construct impulse response functions with $\mathbf{\Psi}_{N,t} = J \mathbf{\Phi}^N J^{\tau} \Sigma_{t-N|t-N-1}^{\frac{1}{2}}$.


webform + form builder: how to clone an existing form

Question: I am using webform + form builder to manage some forms on my site.
I can't find a way to clone the form (with all its elements) to a new form?
I know that I can clone elements inside the same form, but I can't export them to another form (and I can't export the form itself).
There is a way to do it?
Thanks
Answer: Use node clone module to clone that webform node. Then, you will have a new node with webform fields.


Example of weakly convergent sequence, not convergent in norm

Question: I need to find example of sequence $(f_n)_{n=1}^{\infty}$ in $C[a,b]$ which converges weakly to $f \in C[a,b]$, such that $||f_n||_u \to ||f||_u, n \to \infty$, where $$||f||_u = \underset{x \in [a,b]}{max }|f(x)|,$$ but $(f_n)_{n=1}^{\infty}$ doesn't converge to $f$ in norm.
Can you help me, please?
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Answer: Say $[a,b] = [0,1]$ and take for $f_n$ function which is:
a. 1 at 0
b. 0 at $\frac{1}{2n}$
c. 1 at $\frac{1}{n}$
d. 1 at 1
e. and linear between these points
The weak limit of $f_n$ is function which is identically $1$
since we have point-wise convergence and functions are bounded.
At the same time the norm of the difference is $1$.


math domain error no PYTHON

Question: Eu sei que se a raiz for menor do que zero ela não ira existir, mas, algo acontece, mesmo eu implementando que se o valor de delta for menor do que zero é para escrever o erro ele ainda continua mostrando "math domain error" não sei o motivo. Deixo o código aqui em baixo para melhor julgamento.
a = float(input("Insira um valor para A: "))

b = float(input("Insira um valor para B: "))

c = float(input("Insira um valor para C: "))

d = b ** 2 - 4 * a * c

print("Delta: ",d)

delta = math.sqrt(d)

print("Raiz quadrada de delta: ",delta)

if d > 0:

x1 = (-b + delta)/ (2*a)

x2 = (-b - delta)/ (2*a)

print("X1 = ", x1, "X2 = ", x2)

elif d == 0:

x = -b / (2*a)

print("Valor de x = ",x)

elif d < 0:

print("Essa raiz é menor do que zero")

Comment: Comece por corrigir a indentação para que jogue a 100% com o código tal como o tem escrito, assim como colocar os imports que está a utilizar
Answer: O erro acontece exatamente nessa linha:
delta = math.sqrt(d)

E acontece porque você manda que ele calcule a raiz quadrada de d, que pode ser negativo, antes de verificar se ele realmente é negativo.
Você tem que primeiro verificar se ele é negativo, e só se não for tentar calcular a raiz:
import math

a = float(input("Insira um valor para A: "))
b = float(input("Insira um valor para B: "))
c = float(input("Insira um valor para C: "))

d = b ** 2 - 4 * a * c
print("Delta: ", d)

if d > 0:
    delta = math.sqrt(d)
    print("Raiz quadrada de delta: ", delta)
    x1 = (-b + delta) / (2 * a)
    x2 = (-b - delta) / (2 * a)
    print("X1 = ", x1, "X2 = ", x2)

elif d == 0:
    delta = math.sqrt(d)
    print("Raiz quadrada de delta: ", delta)
    x = -b / (2 * a)
    print("Valor de x = ", x)

elif d < 0:
    print("Essa raiz é menor do que zero")

Answer: Sei que isto foi a muito tempo, porem estou aprendendo e utlizei em 3.9 e tive que mudar os (d) para (delta) e math.sqrt(d) para sqrt(delta):
from math import sqrt

""" codigo original, tive que inserir valores para que sublimetext me deixe probar
a = int(input("Digite o valor de A: "))
b = int(input("Digite o valor de B: "))
c = int(input("Digite o valor de C: "))
"""

a = 2
b = 400
c = 6

delta = b**2 - 4*a*c
raiz_delta = sqrt(delta)

if delta > 0:
    delta = sqrt(delta)
    print("Raiz quadrada de delta: ", delta)
    x1 = (-b + delta) / (2 * a)
    x2 = (-b - delta) / (2 * a)
    print("X1 = ", x1, "X2 = ", x2)

elif delta == 0:
    delta = sqrt(delta)
    print("Raiz quadrada de delta: ", delta)
    x = -b / (2 * a)
    print("Valor de x = ", x)

elif delta < 0:
    print("Essa raiz é menor do que zero")

math domain error no PYTHON


Button Click event fires twice, even with ClickMode set to "Press"

Question: A XAML Button's Click even fires twice with a left-button mouse click.
I added  the XAML Button Property ClickMode = "Press", but that made no difference.  The Microsoft documentation for ClickMode indicates that that should have solved the problem.
I discovered this with a breakpoint in the C++ code for the Click event handler, which stopped the code twice for each button click.
XAML code within a Grid on a Page container:
        <Button x:Name="button_listFiles" Grid.Column="1" Grid.Row="0" Content="List" HorizontalAlignment="Center"
                        Click="button_listFiles_Click" ClickMode="Press"></Button>

C++ Click event handler:
    void MainPage::button_listFiles_Click(IInspectable const& sender, RoutedEventArgs const& e) {

        MainPage::counter++;

        textBox_directoryName().Text(to_hstring(counter));
    }

The MainPage::counter++; counts the number of times the handler is called and textBox_directoryName().Text(to_hstring(counter)); displays the result on the XAML page, used for attempted debugging.
Comment: The docs folks are slowly working on adding documentation samples for C++. If the C# example says `object` then replace it with `Windows::Foundation::IInspectable` and input parameters are generally `const&` in C++ for efficiency.
Comment: Sorry, I cannot reproduce this problem. Perhaps you can look at the stack for both calls to see where they are coming from.
Comment: @kennykerr, It did **not** happen on the Blank App (C++/WinRT), so I looked at my code and commented out what I think is the registration of the button event, `button_listFiles().Click({ this, &MainPage::button_listFiles_Click });` in `MainPage::MainPage()` and the double firing stopped.  I am having trouble with the registration notion even after having read the Microsoft documentation.  Can I include it once for the original compile and then remove it?
Comment: The C++/WinRT Blank App template does not include a call to register the handler. I'm not a Xaml expert, but it looks like the Xaml compiler does this in the background. So it makes sense that you would receive two calls if you added your own registration on top of that.
Comment: Thanks. I now understand I can follow standard C++ and write a prototype Click event in the .h file and a definition in the .cpp file.  But, how do I determine the prototype for a Click or any event from the Microsoft documentation?  The working Click event prototype is `void b2_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);` but the Microsoft page for "ButtonBase.Click Event" does not have that, and only a C# example, viz., `void submitButtonClick(object sender, RoutedEventArgs e)`, even with "C++/WinRT" selected as the language.  Am I missing something?
Comment: Related... I tried to add a `PointerPressed` event for a XAML TextBlock.  The event handler in the .cpp file has as its second argument the type `PointerRoutedEventArgs` which is declared in "winrt/Windows.UI.Xaml.Input.h".  At first, I put the `#include` statement for Input.h in the .cpp file containing the event handler and got a "Linker Tools Error LNK2019".  This puzzled me since this `#include` statement came after the one for pch.h.  When I moved it to pch.h, the linker error disappeared.  Perhaps I could have added it to the .h file associated with the .cpp file, but I did not try that.
Answer: Just to close this out, the answer is the several comments between me and Kenny Kerr.


Hibernate Query.list() is returning no value

Question: Hibernate Query.list() is returning no value. even it is generating proper query i have checked the value of sessionFactory also it is also printing nothing

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/es5</property>

<property name="hibernate.connection.password">root</property>

<property name="hibernate.connection.username">root</property>

 <property name="hibernate.connection.pool_size">10</property>

 <property name="show_sql">true</property>

 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

 <mapping resource="com/d2d/bean/hibernate.hbm.xml"/>

 </session-factory>

package com.d2d.util;
import org.hibernate.SessionFactory;
  import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory
 {
  static SessionFactory sf = null;

    static
     {
        Configuration cfg = new Configuration();
       cfg  = cfg.configure("hibernate.cgf.xml");

        sf = cfg.buildSessionFactory();
         System.out.println(cfg);
       }

      public static SessionFactory getSessionFactory()
      {
           return sf;
        }

       }

    ****this is the class where i want to access persistance class****

package com.d2d.services;
import java.util.List;

  import org.hibernate.Criteria;
 import org.hibernate.Query;
 import org.hibernate.Session;
import org.hibernate.SessionFactory;

 import com.d2d.bean.Seller;
 import com.d2d.util.HibernateSessionFactory;
 import com.d2d.util.HibernateTemplate;

  public class SellerManager
   {

      static Seller seller;
    public static Seller getSellerFromId(String id)
    {
       seller = (Seller) HibernateTemplate.getObject(Seller.class, id);
         return       seller;
      }

    public static Seller  getSellerByEmail(String email)
    {

           SessionFactory sf =                     HibernateSessionFactory.getSessionFactory();
         Session session = sf.openSession();

          Query q =session.createQuery("FROM Seller s where s.email ='"+email+"'");

         System.out.println(sf);
          //-----this is printing nothing-----------
         List list = q.list();

            boolean status = false;
          Seller seller2 = null;
         for(int i=0;i<list.size();i++)
         {
            Seller seller1 = (Seller)list.get(i);
            if(email.equals(seller1.getEmail()))
            {
               status = true;
               seller2 = seller1;
            }

       }
        System.out.println("seller is"+seller2);
        return seller2;

       }

   }

      package com.d2d.util;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateTemplate
{

    static SessionFactory sf = null ;
    public static Object  addObject(Object user)
     {
        Object id = null;

        System.out.println(user);
        try
        {
            System.out.println("add object start...");

            sf  = HibernateSessionFactory.getSessionFactory();

            Session session = sf.openSession();

            Transaction tx = session.beginTransaction();
            id = session.save(user);
            tx.commit();
            session.close();
        }

        catch(Exception ex)
        {
            System.out.println(ex);
        }
        return id;

     }
    public static Object getObject(Class obj,Serializable id)
    {
        Object o = null;
        try
         {
            SessionFactory sf = HibernateSessionFactory.getSessionFactory();
            Session session =  sf.openSession();

            Transaction tx = session.beginTransaction();
            o = session.load(obj, id);
            tx.commit();
            session.close();

         }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
        return o;

    }

}
   please help me out................

Comment: Pease post your class code and hibernate.cfg file
Comment: Yes. We need persistent classes, and code with your query.
Comment: Based on the information provided in the question, the only possible guess is: Your database has no data
Answer: Hi Inder try running your query in query browser like oracle or MySql I think your query is returns nothing .Query.list() in java works only for select queries and not for updates and inserts.Query.list() returns nothing in a list if your query did not return any result set.
Comment: sir, i am trying for search query and it not returning anything , but the predefine functions in hibernate-session like session.save() is working properly.. thank you so much for your your attentions


Calling JS function from JSP tag

Question: I'm trying to call a JS function, escapeHtml(unsafe), in this tag
file.jsp
<form:form modelAttribute="messagingForm" id="messagingForm" action="${messagingSendUrl}">
[...]
    <foo:bar string="${escapeHtml(messagingForm.text)}" substring="${searchstring}"/>
[...]
</form:form>

I get this error: The function escapeHtml must be used with a prefix when a default namespace is not specified.
I have tried:
<foo:bar string="<spring:message code="escapeHtml('${messagingForm.text}')"/>" substring="${searchstring}"/>

I get this error: file.jsp(xx,17) equal symbol expected
and: java.lang.ClassNotFoundException
I tried:
<foo:bar string="<spring:message code='escapeHtml("${messagingForm.text}")'/>" substring="${searchstring}"/>

I get this error: file.jsp(xx,xx) Unterminated <foo:bar tag
====EDIT for Anthony Grist====
Well, I can do this:
<c:when test="${reply}">
    <button id="btn_msg_reply_dispatcher"
        title="<spring:message
          code="messaging.alt.replyvehicleanddispatcher"
          argumentSeparator=";"
          arguments="${vehicleName};${sender}" />"
        onclick="replyVehicleAndDispatcher(${vehicleInformationId}, ${sid}, '${sender}'); return false;">
    </button>
</c:when>
[...]

Comment: See edit for comment.
Comment: JSP is a server-side language, JavaScript is a client-side language. You can't execute a JavaScript function as part of your JSP tag because it doesn't exist yet. What are you actually trying to do?
Comment: Yes, you can do that. It's totally irrelevant though, because all you're doing is writing HTML that defines a JavaScript event handler; on the server-side that does absolutely nothing, it's just text. It's only when it's been parsed by the user's browser that it sets up the event handler, and it's only when the user clicks on it that the function is called. You can't call a JavaScript function to set the content of an attribute on a JSP tag, which seems to be what you're trying to do. You also can't use a JSP tag to set the content of an attribute on another JSP tag.
Answer: <c:set var="msg"><spring:message code="${messagingForm.text}" htmlEscape="true"/></c:set>
<foo:bar substring="${searchstring}" string="${msg}" />

Comment: substring='Sven Svensson'
string='This is Mumford & Sons;'
Comment: Ok, those are SUPPOSED to be the values in the console. Now there're no values, since the program crashes with above mentioned errors.
Comment: I couldn't build the code value with the '+'. This is what I did:

.

This doesn't call the function, though. It outputs:
escapeHtml('This is Mumford ')
Comment: Now, that wouldn't call my custom function, would it?
Comment: what is the value of `substring` and `string` in console?
Comment: aren't those the values you wanted? you are able to assign values to both string and substring, then which part isn't working? any error msg displayed?
Comment: use the attribute `htmlEscape="true"` in `spring:message`, check my update in answer, try both `true` and `false`
Comment: hmmm, have you btw tried `htmlEscape=true`?is it avoiding the html characters?
Comment: communicating between client and server side is not possible, why not write an equivalent to your custom function at the backend in java and return the appropriate value to the JSP?

Calling JS function from JSP tag


Delete from different tables in one query with prepared statements

Question: I want to delete multiple records with a specified value (non-unique) in one table and delete the record with that same specified value (unique) in another table using a prepared statement. This is what I got,
$stmt = $conn->prepare("DELETE FROM Books WHERE Genre_ID=? AND FROM Library WHERE Genre_ID=?");
$stmt->bind_param("ii", $genreID, $genreID);

The aim of the query would be to delete the specified Genre from the Library table by its ID and, of course, remove all the books from the Books table with that ID.
Comment: Can a book only have one genre? I'd suggest looking into foreign keys on setting up "on delete cascade" or similar. https://stackoverflow.com/questions/2914936/mysql-foreign-key-constraints-cascade-delete
Comment: See about JOINs
Answer: This would better be handled with two statements... one to delete from Books, and another to delete from Library.
To get this done in a single statement, we could use a join operation. But there is an issue with "missing" rows.
My suggestion:
Write a SELECT statement first, get that tested, and then convert it into a DELETE statement.
 SELECT b.*
      , l.*
   FROM `Books` b
   JOIN `Library` l
     ON l.genre_id = b.genre_id
  WHERE b.genre_id = ?

But this statement won't return any rows if there isn't at least one row in both Books and Library with a matching genre_id.
We can partly fix that with an outer join.
 SELECT b.*
      , l.*
   FROM `Library` l
   LEFT
   JOIN `Books` b
     ON b.genre_id = l.genre_id
  WHERE l.genre_id = ?

If there's at least one row in Library with the specified genre_id, we will get all of the Books with that same genre_id. But it won't return any rows if there isn't a matching row in Library.
And MySQL doesn't support full outer joins, so that's as far as we get. We can make either Library or Books the driving table... we can handle "missing rows" from one table or the other.

EDIT
As an ugly workaround
SELECT b.*
     , l.*
  FROM ( SELECT rb.genre_id
           FROM Books rb
          WHERE rb.genre_id = ?
          GROUP BY rb.genre_id
          UNION
         SELECT rl.genre_id
           FROM Library rl
          WHERE rl.genre_id = ?
          GROUP BY rl.genre_id
       ) r
  LEFT
  JOIN Books b
    ON b.genre_id = r.genre_id
  LEFT
  JOIN Library l
    ON l.genre_id = r.genre_id

Then we can convert that into a DELETE statement, replacing SELECT with DELETE
with the missing rows problem:
 DELETE b.*
      , l.*
   FROM `Library` l
   LEFT
   JOIN `Books` b
     ON b.genre_id = l.genre_id
  WHERE l.genre_id = ?

Note the same issue... this won't remove any rows from Books if there isn't at least one matching row in Library.

EDIT
or with the ugly workaround. convert the SELECT into a DELETE:
DELETE b.*
     , l.*
  FROM ( SELECT rb.genre_id
           FROM Books rb
          WHERE rb.genre_id = ?
          GROUP BY rb.genre_id
          UNION
         SELECT rl.genre_id
           FROM Library rl
          WHERE rl.genre_id = ?
          GROUP BY rl.genre_id
       ) r
  LEFT
  JOIN Books b
    ON b.genre_id = r.genre_id
  LEFT
  JOIN Library l
    ON l.genre_id = r.genre_id

Again, I recommend that this operation be performed as two separate statements, one to remove rows from Books and another to remove rows from Library.
I suspect there isn't a foreign key constraint between these two tables. If there was, the order that these deletes are performed would be important.


Forwarding custom page rule for known ip adresses

Question: I want to add some ip adresses to a blacklist, and i want to show these ip addresses in blacklist a custom web page that includes a "you are in blacklist" message on body.
How can i do this?
I have ubuntu server and apache.
I tried to add rule to ip tables but it only drops connection.
I do not want to drop connection i want to route it to a custom .html .
Thanks.
Comment: Define *"show"*, *"them"* and the processs of *staring*. Until done you can print a banner **"you are in a blacklist"**, stick it to a chassis of your server - whenever *they* will look at it, *they* will see your message.
Answer: If you are referring to HTTP protocol and remote web-clients, like browsers, then, to display a warning page to a set of such clients, basing on their IP address information, you can use mod_rewrite to rewrite the DocumentRoot of a given vhost (the one that you want to protect) to some path, say /blacklisted.html.
For example, consider the following approach:
RewriteCond %{REMOTE_ADDR} ^12\.34\.56\.78$
RewriteRule ^/.* /blacklisted.html

And /blacklisted.html is supposed to contain scary warnings and threats.


Property of normal subloops

Question: Let $w(x_1, . . . , x_n)$ be a loop term, and let $A$ be a normal subloop of
$Q$. Prove that $w(a_1A, · · · , a_nA) = w(a_1, . . . , a_n)A$ for every $a_1, . . . , a_n \in A$.
A subloop $A$ of $Q$ is normal if for all $x,y \in Q$ $xA=Ax$, $x(yA) = (xy)A$, and $(Ax)y=A(xy)$. So I'm not sure what exactly needs to be done here. It seems immediate if we can always reassociate the $a_i$ and then push them all to the other side of $A$ to get the resulting term.
Answer: Recall that the definition of term is recursive:

A variable symbol $x$ is a term, and
if $f$ and $g$ are terms, then $f\cdot g$ is a term.

Whenever a collection is defined recursively, you need to use induction to prove statements about that collection. So prove your statement for $w(x_1,\dots,x_n)=x_i$ and then, assuming your statement is true for $w_1$ and $w_2$, prove it is true for $w_1\cdot w_2$

Property of normal subloops


Executar query ao pressionar um botão e enviar para o modal

Question: Tenho o seguinte código em que quero clicar em um botão, e ao fazer isso executar uma Query e exibir os resultados em um Modal
Portanto, o botão:

Página em que executo o sql (Rota teste)
$query = ("select... exemplo")
$output = '';
$output .= '

   Nome

';
      for ($i = 1; $i < count($query); $i++) {
      $resul = $query[$i]["nam_per_sching_cla"];
      $output .= '

'. $resul . '

';
}
$output .= '
';
echo $output;

Função jquery com ajax para chamar a página php e enviar os dados para o modal:


Instead of Insert, Insert Value from (inserted)

Question: So I have a trigger on instead of insert. It runs a check, if that is okay I want a query to insert values into a table. The values needs to come from inserted though.
create trigger thisTrigger
on
instead of insert
if (a check)
insert into myTable values (pnr = (select pnr from inserted))
else

Obviously this MSSQL code is faulty. The question is, how do I write that insert query to allow me to get the values from inserted?
Thank you for your help!
Comment: and `Instead Of` trigger is an unusually heavy hammer to use for this purpose.  The normal practice for a case like this would be to use an `After` trigger to validate the changes, and if they are not valid, the raise an exception to force the changes to rollback.
Answer: You can use insert...select like this:
create trigger thisTrigger
on
instead of insert
if (a check)
insert into myTable select pnr from inserted
else
-- the rest of your code

Comment: Yes, it does however prevent you from doing this until a few minutes has passed since the creation of the question =)


How to use send POST request with AJAX in Razor Pages?

Question: I am trying to send a POST request with AJAX but getting status code 400 ("error"). This is my code.
namespace xx.WebApp.Pages.Dependency
{
    public class CreateModel : PageModel
    {
        public IActionResult OnGet(string test) {

            return Page();
        }

        [HttpPost]
        public async Task<IActionResult> OnPostAsync([FromBody] CreateDependencyRequest createDependencyRequest) {
            return new JsonResult("Test");
        }
    }
}

I troubleshoot it by sending a GET request and it works as expected. I test them by putting a breakpoint at the method.

This is how I send the GET request.
$.ajax({
    url: `/Dependency/Create?test=1`,
    type: 'GET',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(formData),
    success: function (data) {
        debugger
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger
        console.log(textStatus, errorThrown);
    },
    complete: function () {
        createButton.prop('disabled', false);
    }
});

This is how I send the POST request.
$.ajax({
    url: `/Dependency/Create`,
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(formData),
    success: function (data) {
        debugger
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger
        console.log(textStatus, errorThrown);
    },
    complete: function () {
        createButton.prop('disabled', false);
    }
});

Comment: Try this [solution](https://stackoverflow.com/questions/48373229/400-bad-request-when-post-ing-to-razor-page).
Answer: I managed to solve it already.
I just need to add this line at the program.cs (I am using .NET 6)
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

and in the form tag, I add the code below which will generate anti-forgery token.
@Html.AntiForgeryToken()

When you inspect it, you will get something like below:
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Hqu8a0DVdlNvQtHk7hhdjABEZXfJ0BowbqYa5n5gr9RoquzRPlAQ42Ye1cqxFfoAy5IWUcOuEgp_GB7QQTM_unQNoSWXo7cdKeNG-1qDI4ygZl0yVyyOKRDufd4SqahvcNz080bisB01SC-GIC2yJLCJkKlEaUtxH6vNpF9wiZxshBBa8ZWopjKrv1sK2Mifg">

and in the Javascript, get the hidden anti-forgery token
var token = $('input[name="__RequestVerificationToken"]').val();

and add it in the AJAX
$.ajax({
    url: `/Dependency/Create`,
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",token);
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(formData),
    success: function (data) {
        debugger
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger
        console.log(textStatus, errorThrown);
    },
    complete: function () {
        createButton.prop('disabled', false);
    }
});


Difficulty in understanding the proof of the Wold decomposition theorem

Question: The proof of the Wold Decomposition [1] of $x_t$ involves the definition of the process
$$w_t = x_t - P_{\mathcal{M}_{t-1}^x} x_t,$$
where $x_t$ is a stationary zero-mean process,
$\mathcal{M}_n^x = \overline{{\mathrm{span}}}\{x_t, -\infty \lt t \le n\}$, and $P$ denotes the projection.
If $x_t$ is a real-valued process (as opposed to a vector-valued one) and  $x_i \ne 0$ for some $-\infty \lt i \le (t-1)$, isn't $\mathcal{M}_{t-1}^x = \mathbb{R}$ and, consequently, $w_t=0$?
I guess it doesn't, since the rest of the proof would not make sense if it did. Could you please point out where my interpretation is wrong?
[1] Shumway, RH, Stoffer DS. Time Series Analysis and Its Applications with R Examples. 4th ed.
Answer: You project on an infinite dimensional space spanned by $x_{t-1}, x_{t-2},\ldots$  The fact that a single $x_{t-k}$ for some $k$ is zero does not make such infinite dimensional space become the real line, it continues to be an infinite dimensional space.
Comment: Your answer allows me to get to the heart of the question. Why is the space spanned by $x_{t−1},x_{t−2},...$ infinite dimensional? Since $x_{i}$ are real numbers, aren't all $x_{i}$ colinear, in the same way that two vectors (a,0) and (b,0) would be in $\mathbb{R}^2$? If not, could you please illustrate by showing what the projection of 5 is on the space spanned by 1 and 2?
Comment: No, $x_i$ are not real numbers, are random variables and if no linear combination of the past can predict perfectly the future, as is the case in regular processes, the "past" is infinite dimensional. You might want to read  chapter 7 of Anderson, T.W.(1970) The Statistical Analysis of Time Series. It requires a bit lengthy explanation that I cannot attempt in a comment.
Comment: Thank you, it makes much more sense now. I will also look for that reference to understand it further.
Answer: Reading the proof in more detail, it looks like the condition $\sigma_x^2 >0$ is required for the Wold decomposition theorem to apply. Above the theorem in the book this quantity is defined such that the situation you're describing falls under the case $\sigma_x^2 = 0.$
Comment: Hi: Below is the longest and most detailed proof of the wold decomp that I know of. It's been a looooooooong time but I remember reading it once ( over days. I find that these things are best consumed slowly )  and I recall that it was quite helpful. Maybe it can help with your overall goal in addition to your specific question ?  Good luck. https://personal.psu.edu/hxb11/WOLD.PDF
Comment: I don't see how the situation I am describing falls under the case $\sigma^2=0$. Maybe the grammar in the original question was ambiguous. I have improved it after your answer.


Is hitting the more right-handed keys on the piano necessary to gain the same volume?

Question: I'm just getting to the point that I can play some tunes by Classical composers and, on one piece by Haydn, which plays both hands somewhat to the right of middle-C, it seems that I need to hit the keys being played by the right hand significantly harder to get the same volume.  In fact, it seems that, if I don't, the keys played with the right hand are nearly overwhelmed.
So, I guess, in general, would it be expected that the right-hand keys were pressed a little harder?
Answer: This depends very much on the actual piano, and also on the acoustics of the room it is in. Opening the lid of an acoustic piano will reduce the muffling of high notes. There is usually some way to open the top of an upright piano, as well as a grand. Storing music books etc on top of a piano doesn't improve its sound quality!
If you were playing a Steinway model D or a similar "concert grand", it's unlikely you would feel there was any imbalance between the hands over that range, especially considering that Haydn's keyboard only extended for 2 1/2 octaves above middle C, which is a long way from the top note of a modern piano.
On a Yamaha grand designed and voiced for pop music rather than classical, you might find the right hand was louder than the left. (All models of Yamaha pianos tend to be "loud" in the treble in my experience, at least when they are new)
On a worn-out 50-year old cheap upright, you might well find what you described.
All of the above is talking about acoustic pianos. If your is digital, anything might happen, depending on quality the amplifiers and speakers or headphones, as well as on the piano itself.
Answer: As the melody is usually in the r.h. it is usually played a little louder (more heavily) than the l.h. If there are several notes played in the l.h.,a chord for example, then that will overpower the r.h. notes, as they are drowned out by the l.h.
It could be your piano, or possibly you are heavy handed with your l.h. It's all a bit relative, and experience will tell you  which hand to up or down the volume on.
Answer: I am a lefty and I always find playing almost all instruments including piano a bit difficult for the exact same reason as your question explains.
Generally musical instruments are designed favourably to the right-handed people, because they represent the majority.
So I think whether your music is played on the right side of the middle C or not, you are expected to play the right-hand a bit stronger than the left.


How to read up until a delimiter?

Question: I need to read up until a delimiter and exclude the first character and take the value and put it into a variable. The first field in the line can be varying length which is why I can't use a standard cut or other methods I am familiar with. How do I read up until the "|" delimiter and exclude the first character?
T1000|||||||||||||||

I need a variable to contain the 1000 which would exclude the first character of "T". Also the value will not always be a static 4 length so need it to read dynamically.
Comment: You're conflating several different things -- an ideal StackOverflow question asks only *one* question, so "how do I remove a prefix from a string in bash?" should be searched for separately (saying "searched for" rather than "asked" because it very much is already in our knowledgebase).
Comment: Also, do you really want to stop *reading* at the first `|` (so the next read operation will begin just after it), or do you just need to *discard everything after* the `|`? If the former, you have https://stackoverflow.com/questions/10931915/how-can-i-read-words-instead-of-lines-from-a-file, except that you want to use a `|` rather than a space. If the latter, you have https://stackoverflow.com/questions/27500692/split-string-in-shell-script-while-reading-from-file or https://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash/31405855
Comment: BTW, `cut` can be used perfectly well without knowing length; `cut -d'|' -f1` and there you are. That said, startup costs to `fork()` and `execve()` an instance of `cut` make it wildly inefficient compared to shell builtins (when not operating over a large enough quantity of data to amortize those costs), so it's best avoided anyhow.
Answer: The -d argument to read overrides its default use of a newline as the delimiter that terminates the read.
Thus:
IFS= read -r -d '|' firstCol      # see http://mywiki.wooledge.org/BashFAQ/001
firstColWithoutT="${firstCol#T}"  # see https://wiki.bash-hackers.org/syntax/pe
printf '%s\n' "$firstColWithoutT" # see http://mywiki.wooledge.org/BashPitfalls#echo_.24foo

Answer: txt="T1000|||||||||||||||"
var=$(echo ${txt: 1} | cut -d "|" -f1)

echo "$var"

How to read up until a delimiter?


A quite classic differential equation

Question:
Find all the derivable functions $f:\mathbb{R} \to \mathbb{R}$ such that $k \in \mathbb{R_+}$ exists with $$F(x)+kf'(x) = 0$$ for all $x \in \mathbb{R}$, where $F$ is the primitive of $f$ with $F(0) = 0$.

This seems to be quite a classic problem, however, I couldn't find a solution yet. I tried constructing $(e^xF(x))'$ or $(e^{-x}F(x))'$ type expressions, but with no success. Can you please help me with this?
Comment: Does it look more familiar with you write it as $y'' + (1/k) y = 0$?
Comment: $y'' + \omega^2 y = 0$ is a well known ODE, the solutions are the linear combinations of $ \sin(\omega x) $ and $\cos(\omega x)$. Compare https://en.wikipedia.org/wiki/Harmonic_oscillator
Comment: All linear differential equations with constant coefficients are "easily" solvable, see https://en.wikipedia.org/wiki/Linear_differential_equation#Homogeneous_equation_with_constant_coefficients, and  https://en.wikipedia.org/wiki/Linear_differential_equation#Second-order_case for the second-order case.
Comment: Can you expand a bit more?
Comment: Thanks! I didn't know of this type of equation! Since you made me curious, is $y'' = ky$, where $k > 0$, also a known ODE?
Comment: Ok, thank you for the references!
Comment: Please define "derivable".
Answer: Given the initial condition $F(0)=0,$ you have essentially defined $$F(x)=\int_0^xf(t)\,\mathrm{d}t,$$ so $$\int_0^xf(t)\,\mathrm{d}t+kf'(x)=0$$ for all $x\in\mathbb{R}.$ In differentiating, this results in the equation $$f(x)+kf''(x)=0$$ for all $x\in\mathbb{R}.$ There are two cases to consider here. One case is $k=0.$ If so, then trivially, $f(x)=0$ for all $x\in\mathbb{R}.$ The other case is $k\neq0,$ in which case $$f''(x)+\frac1{k}f(x)=0$$ for all $x\in\mathbb{R}.$ This equation can be rewritten as $$f''(x)-\frac{i}{\sqrt{k}}f'(x)+\frac{i}{\sqrt{k}}f'(x)+\frac1{\sqrt{k}^2}f(x)=\left[f'-\frac{i}{\sqrt{k}}f\right]'(x)+\frac{i}{\sqrt{k}}\left[f'-\frac{i}{\sqrt{k}}f\right](x),$$ so letting $g=f'-\frac{i}{\sqrt{k}}f$ reduces the equation to $$g'(x)+\frac{i}{\sqrt{k}}g(x)=0,$$ and this equation is separable. Once you solve it, the equation for $f$ can be solved using the integration factor. Anyway, the general solution can be written as $$f(x)=C_0\cos\left(\frac1{\sqrt{k}}x\right)+C_1\sin\left(\frac1{\sqrt{k}}x\right)$$ for all $x\in\mathbb{R},$ and this works even if $k\lt0,$ though it will just make the expression look awkward.
Comment: Thank you for the proof!

A quite classic differential equation


how to randomly sample from a numpy array of probabilities?

Question: I have a numpy array like this:
arr = [.2 , .1, .2, .3, .2 ]

Now what I want to do is sample from this array, such that the probability i get a certain index is dependent on the probability at the index. So for example, the probability i get index 3 is .3
Anyone know any nifty ways to do this?
Comment: look at the `p` argument in [`numpy.random.choice`](https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html)
Answer: You can do weighted sampling with a discrete probability distribution using np.random.choice by providing the sampling distribution as a parameter p:
import numpy as np

x = [.2 , .1, .2, .3, .2 ]

# sample from `x` 100 times according to `x`
n_samples = 100
samples = np.random.choice(x, n_samples, p=x)


Can someone explain orphanRemoval in Hibernate?

Question: My question is not how work "mappedBy". I know, just indicates the owner of the relation. My question is how orphanRemoval works.
And in my case I don't use the indication mappedBy at all.
I have the following entities:
<code>@Entity
@Table(name = "catalog_orphan")
public class CatalogOrphan extends AbstractBaseEntity<Long> {

    @OneToMany(orphanRemoval = true)
    private List<GoodOrphan> goodOrphans;

    public List<GoodOrphan> getGoodOrphans() {
        return goodOrphans;
    }

    public void setGoodOrphans(List<GoodOrphan> goodOrphans) {
        this.goodOrphans = goodOrphans;
    }
}

@Entity
@Table(name = "good_orphan")
public class GoodOrphan extends AbstractBaseEntity<Long> {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "catalog_orphan_id")
    private CatalogOrphan catalogOrphan;

    public CatalogOrphan getCatalogOrphan() {
        return catalogOrphan;
    }

    public void setCatalogOrphan(CatalogOrphan catalogOrphan) {
        this.catalogOrphan = catalogOrphan;
    }
}

@MappedSuperclass
public abstract class AbstractBaseEntity<ID> {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected ID id;

    @Column(name = "name")
    protected String name;
}
</code>
And I'm trying to test the functionality of removing orphans.
And I wrote the following test:
<code>@RunWith(SpringRunner.class)
@DataJpaTest
@TestExecutionListeners({
        TransactionalTestExecutionListener.class,
        DependencyInjectionTestExecutionListener.class,
        DbUnitTestExecutionListener.class
})
@DatabaseSetup("/persistCascade/orphan/catalog_good_orphan.xml")
public class CatalogOrphanTest {

    @Autowired
    protected TestEntityManager entityManager;

    @Test
    public void clearCollections() {
        CatalogOrphan catalog = entityManager.find(CatalogOrphan.class, 1L);

        catalog.getGoodOrphans().clear();
        entityManager.persist(catalog);

        entityManager.flush();
        entityManager.clear();

        CatalogOrphan catalogAfterCleanCollection2 = entityManager.find(CatalogOrphan.class, 1L);
        assertThat(catalogAfterCleanCollection2.getGoodOrphans().size(), equalTo(0)); // Does this mean that the connection has been deleted?

        GoodOrphan goodOrphan = entityManager.find(GoodOrphan.class, 1L);
        assertThat(goodOrphan.getCatalogOrphan(), is(notNullValue()));  // WHY???
    }
}
</code>
catalog_good_orphan.xml:
<code><dataset>
    <Catalog_Orphan id="1" name="Catalog#1"/>
    <Catalog_Orphan id="2" name="Catalog#2"/>

    <Good_Orphan id="1" name="Good#1" catalog_orphan_id="1"/>
    <Good_Orphan id="2" name="Good#2" catalog_orphan_id="1"/>
    <Good_Orphan id="3" name="Good#3" catalog_orphan_id="2"/>
    <Good_Orphan id="4" name="Good#4" catalog_orphan_id="2"/>

    <!-- without catalog -->
    <Good_Orphan id="5" name="Good#5" />
</dataset>
</code>
I don't understand the point at all "orphanRemoval = true".
Why does he work like that? As a result, we only remove the link to "GoodOrphan" from the "CatalogOrphan", and the link from "GoodOrphan" to "CatalogOrphan" remains.
what am i doing wrong? or is this correct behavior?
Comment: Possible duplicate of [Can someone explain mappedBy in hibernate?](https://stackoverflow.com/questions/9108224/can-someone-explain-mappedby-in-hibernate)
Comment: @crizzis thanks for the comment. But no, there is no answer to my question.
Comment: *what am i doing wrong?*: you're not using mappedBy. And so instead of having a bidirectional associations, you have two, separate, independent associations: a OneToMany (using a joint table), and a ManyToOne (using a join column). Here's how you define a bidirectional OneToMany association: https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-many-bidirectional
Answer: removeOrphan removes an item from the database when it is not linked to a parent anymore. It only works when you remove the item from the list in the same session. Note: removing from the list and remove the reference from the item to the parent are two different things, even though you (should) use the same foreign key in the database for these two references.
Note: It doesn't work when you remove an item from one list and add it to another. When you are lucky, you get an exception that tells you that it doesn't work.


Retorno a linha TEXT SVG

Question: Estou a criar um text svg dinamicamente, e quero por um retorno a linha do meio das duas váriaveis quando imprimo. Experimentei com o "\n" e o "br" mas não me faz.
var text_h_fin = document.createElementNS("http://www.w3.org/2000/svg", "text");
text_h_fin.setAttribute('x',10 );
text_h_fin.setAttribute('y', 20);
text_h_fin.setAttribute('fill', '#000');
text_h_fin.setAttribute('font-size', '14px');
text_h_fin.textContent = "1 linha" + "\n" + "2 linha";
svg.appendChild(text_h_fin);

Comment: Podes dar um exemplo visual do que queres fazer? Queres uma linha debaixo da outra?
Comment: Sim exactamente isso, mas não me está a funcionar. Onde imprimo: text_h_fin.textContent = "1 linha" + "\n" + "2 linha";
Comment: Essa quebra de linha é sempre no mesmo sítio ou dinamica? vais ter de fazer elementos diferentes para isso pois nõ há quebra de linha no text do svg.
Comment: Ah ok, então crio outro elemento. Obrigado @Sergio
Answer: Você pode quebrar uma linha criando outro objeto <text> ou usando elementos <tspan> variando a posição (atributo) dy que é relativa:
<text x="10" y="20" fill="#000" font-size="14px">
    1 linha
    <tspan dx="18px">2 linha</tspan>
</text>

Assim você pode mover todo um parágrafo ou bloco de texto sem precisar mexer nas posições de cada linha.
Veja: http://www.argonavis.com.br/cursos/xml/x500/SVG%2005_Texto.pdf

Retorno a linha TEXT SVG


TemporaryStreamWrapper error during installation

Question: In continuation to my previous question https://drupal.stackexchange.com/questions/208245/openatrium-installation-profile-error
I have another problem in the very next step i.e. during Site Configuration.

Firstly the theme seems to have broken because CSS is not being applied.
Secondly, I'm getting the error message.
"Warning: file_put_contents(temporary://fil3BF3.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (line 1936 of \includes\file.inc).
•The file could not be created."

I understand from some other posts that this is due to missing permissions on "sites/default/files" folder. But this folder is created on the fly during installation how do we give access to it.
In addition, I believe another possible cause can be due to permissions to "tmp" folder. Most of the other posts mention changing that path in "Admin -> configuration" somewhere, but for that OpenAtrium needs to be completely installed. Where can I change the path for "tmp" file through file system.
Appreciate a reply.
Answer:
Where can I change the path for "tmp" file through file system.

You can set the tmp path by appending the following line in the site settings.php
<code>$conf['file_temporary_path'] = '/tmp';
</code>
In Addition, all item stored in variable table in Drupal site's database can be set with <code>$conf</code> array in the same way.
Comment: Thanks for the reply, is this path relative to settings.php ?
Comment: It's relative to the root directory of Drupal.