How to predict survival curves with step changes over time

Question: I'm trying to predict the survival curves for customers, knowing that for some rare customers after a certain time the survival probability has a jump. Those jumps are due to endings of minimum contract duration. E.g., some customer commit to stay for 6 month. We know that those customers (usually) stay for 6 month. After that they can cancel there subscription on a monthly basis (thanks @EdM for the advice to include that information in my question). As far as I understand Cox Proportional Hazard and Accelerated Failure Models, they, in in layman's terms, take the average survival over time of the whole population and than multiply that with a constant, which is dependent on covariates. As those jumps are really rare and happen at different points of the lifetime, the average survival curves don't have any jumps in my case. With multiplying those curves with a constant, I can't model those jumps. Have I understood that correctly? If so, is there a way to predict remaining survival, knowing, that the survival probability will make a jump at a certain time?
Comment: If you do not know when these probability jumps might occur and they are rare, it seems unlikely you could ever model them.  Compare that to for example people buying car insurance: you may lose a few during a year if they dispose of their car, but many more at the end of every 12 months when their annual policies come up for renewal - that should be possible to model.
Comment: But we know when the jumps occurs. We just don't know how strong it effects the survival probability
Comment: It would help if you could give an example of how you determine that "for some rare customers after a certain time the survival probability has a jump." That makes it sound like you already have some type of survival model implemented. Or is your "survival" model some type of repeated-events model, and some customers have a big increase or decrease in something like the rate of placing orders? Please provide that information by editing the question, as comments are easy to overlook and can be deleted.
Comment: just did, thanks @EdM
Answer: A simple way to deal with this is to use the end of the initial minimum contract as time = 0 for your survival model instead of the start of the initial contract. For the few who end before that time, you could use a binomial regression (stayed the duration/didn't) unless the particular ending time is of interest. You could use the duration of the initial minimum contract as a covariate under my suggested time = 0.
Another choice if you want to keep time=0 as the start date of the initial contract, as you seem to be doing now, would be to include underInitialContract as a binary time-varying covariate in a Cox model. That would allow for different hazards depending on whether an individual was under that initial contract. Interaction terms of other covariates with that would allow for different associations with outcome depending on whether or not an individual was underInitialContract. I'm often skeptical of using time-varying covariates, but in this case it won't lead to the potential circular reasoning that can arise in general.


Angular 6 how to check if my pipe filter returns an empty array

Question: i have a list of dinosaures that i iterate throught it and then i added a search input to filter the list by login property like this
<input type="text" class="recherche" [(ngModel)]="loginToSearch" placeholder="Entrez votre recherche ici...">

          {{dinosaure.login}}

but i want to add a condition to display a message or form when there are no results returned by the filter , i tried many solutions that i found but none of them worked for me.
this is my filter :
   @Pipe({
     name: 'filter'
  })
export class FilterPipe implements PipeTransform {

      transform(value: any, args: any, loginToSearch: string): any {
        if (!value) {

         return null;
         }
      if (!args && !loginToSearch) {
              return value;
             }
         loginToSearch = loginToSearch.toString().toLowerCase();
             return value.filter(data => {
           return data.login.includes(loginToSearch);
                 });

                }

             }

Comment: @BELLIL i didn't find the right condition to put in the *ngIf that's why
Comment: For performances reasons you should use a filter or sort pipe. The official angular documentation recommends avoiding it.
Comment: why don't you just wrap your    in an *ngIf ?
Answer: I would recommend you to change the manner of work,
you can add an ng on (ngModelChange) to your front
so your input will be like this
<input type="text" class="recherche" [(ngModel)]="loginToSearch" placeholder="Entrez votre recherche ici..."  (ngModelChange)="onFilterValueChange()" >

and then in your component you declare a temporary list and you search your value
temporaryList = [];
onFilterValueChange(){
        if(this.loginToSearch){
         this.temporaryList = this.dinosauresList.filter(data => data.login.includes(this.loginToSearch));}
         else {  this.temporaryList  = this.dinosauresList;
        }}

and then in your html you can do

 Your error message

<ng-template #results>

          {{dinosaure.login}}

</ng-template>

If you insist to work with your pipe, you'll have to create a service that contains an event emitter that inform your component when your list is empty, if you create a stackblitz i will be able to give you more help
Comment: i have thought the same as you !
Comment: but i think there still problem when i delete from input it does not restore the array
Comment: and also i tried looking for one element and i found it but when i delete and look for another existing element it won't work it shows error message since the input is empty
Comment: sorry but i never used stackblitz but i could give you a github repository if you want just the front end part
Comment: can you take a look at my modified code ? i added a condtion in onFilterValueChange(), you should reinitialize if loginToSearch is empty
Comment: yes yes it works fine , there is just one tiny problem when i delete from the input it doesn't trigger the (change)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/208597/discussion-between-bellil-and-aouadi-slim).
Answer: You can do it using two ng-containers
The answer:
<input type="text" class="recherche" [(ngModel)]="loginToSearch" placeholder="Entrez votre recherche ici...">

<ng-container *ngIf="dinosauresList | filter: login : loginToSearch;let filteredDinosauresList">
  <ng-container *ngIf="filteredDinosauresList.length>0;else noResultsView">

          {{dinosaure.login}}

  </ng-container>
</ng-container>

Your error message for no results

Inside the first ng-container, we filter and assign the filtered list into a local template variable using let.

Then in the second ng-container we check the length of that filtered list to show the empty results view or not.

We can use the same local template variable inside the *ngFor in order to prevent multiple filter operations


how to find GCP services interdependencies

Question: Before I can use a particular service, I have to enable the API in my Google project. Sometimes when I do this, more services are enabled than the one I specified. for example, enabling cloudfunctions service actually enabling multiple APIs in the background like pubsub, storage etc.
I followed this article to find the service dependencies https://binx.io/blog/2020/10/03/how-to-find-google-cloud-platform-services-dependencies/. The command output in the above article shows the dependent services as below
<code>gcloud services list \
   --available --format json | \
jq --arg service cloudfunctions.googleapis.com \
    'map(select(.config.name == $service)|
        {
          name:      .config.name,
          dependsOn: .dependencyConfig.dependsOn
        }
    )'
</code>
the result is:
<code>{
  "name": "cloudfunctions.googleapis.com",
  "dependsOn": [
    "cloudfunctions.googleapis.com",
    "logging.googleapis.com",
    "pubsub.googleapis.com",
    "source.googleapis.com",
    "storage-api.googleapis.com",
    "storage-component.googleapis.com"
  ]
}
</code>
when i am executing this command, i am not getting the output as above. the  ""dependsOn":" section is showing as "null"
below is the output of the same command when i executed in cloudshell.
<code>  {
    "name": "cloudfunctions.googleapis.com",
    "dependsOn": null
  }
]
</code>
does there any alternate way to identify the service interdependencies. can someone help on this please
Comment: Edit your question and show the problem you are having using that article as your starting commands. Stating **not giving the output as advertised** is not a problem statement. Show what you tried, what data was returned and what you expected.
Answer: I do not see the dependencyConfig section output by the command on my system.
When I look at the API documentation, the Service resource does not contain the section dependencyConfig.
It appears that Google has removed that item from the API that the command gcloud services list uses to display service information.


Open_Basdir Restriction in effect File(/foo/bar) is not within the allowed paths (.../foo/bar)

Question: I am running PHP 5.2.6 with open_basedir set. Now I get the following message of a path not being in the the list of allowed dirs, but it is in the list:
<code>"is_dir() [function.is-dir]: open_basedir restriction in effect.
   File(/srv/www/www.example.com/httpdocs/pdf_files) is not within
   the allowed path(s):
   (/srv/www/services.example.com:/tmp:/srv/www/www.example.com/httpdocs/pdf_files:/usr/share/phpmyadmin/:/etc/phpmyadmin/)"
</code>
What is wrong here?
Answer: The problem was that the path did not exist.


A question about powers of complex numbers

Question: I have been running in circles trying to conceptualize the solution to this and am looking for a little guidance. I think the biggest problem is in trying to visualize how taking powers of a complex number cause that number to move in the complex plane. For example: visualizing the location of $z^n$ vs. the location of $z$ (for some integer $n$).
In general, I can see that it is not true that $|1+z^2|>|z^2|$ holds for some $z$ in the complex numbers as it does over the reals. For example, we could take $z=i$ as a counterexample. However, is there some bound we could put on $z$ (like $|z|>1$) that would make it true?
Thanks for the help.
Comment: It's not immediately obvious. Take a look at this for example https://en.wikipedia.org/wiki/Mandelbrot_set
Comment: Note that $|1+z^2|>|z^2|$ can be written as $|1+w|>|w|$ where $w=z^2.$ Given any $w$ there is some $z.$  This is true when $w=a+bi$ where $a>\frac12.$ The set of $z$ includes $c+di$ with $|c|\geq|d|,$ but there are more.
Answer: While I'm not sure it will help with your broader goal of visualizing powers of complex numbers, we can determine the exact set of points $z$ such that $|1+z^2|>|z^2|$.
First let's consider the related inequality $|1+w|>|w|$ for a complex number $w$. Squaring both sides and using the fact that $|a|^2 = a \overline a$, the inequality is equivalent to
\begin{align*}
|1+w|^2 &> |w|^2 \\
(1+w)(1+\overline w) &> w \overline w \\
1 + w + \overline w &> 0 \\
2\mathop{\rm Re(w)} &> -1.
\end{align*}
In other words, $|1+w|>|w|$ if and only if $w$ lies in the right half-plane $\mathop{\rm Re(w)} > -\frac12$.
Now we only have to determine the set of complex numbers $z$ such that $\mathop{\rm Re(z^2)} > -\frac12$. If we write $z=x+iy$, then $z^2 = x^2 + 2ixy - y^2$ and thus $\mathop{\rm Re(z^2)} = x^2-y^2$. The solutions of $x^2-y^2 > -\frac12$ comprise the region between the two branches of the hyperbola $y^2-x^2 = \frac12$. Therefore these are the complex numbers $z$ such that $|1+z^2|>|z^2|$ (the light-colored region in the graph below; notice $z=i$ lies outside this region, as you have observed).
Comment: Wow! Very thorough reply. Thank you, this helped a lot. Cheers.


Computing $\frac{\partial}{\partial W} || t_n -W^T \phi (x_n) ||^2$

Question: In Ch 3.1.5 of Pattern Recognition and Machine Learning how do we take the derivative wrt $W$ of 3.33:
$$ln(p(T|X,W,\beta))=\frac{NK}{2}ln(\frac{\beta}{2\pi}) - \frac{\beta}{2}\sum_{n=1}^N || t_n -W^T \phi (x_n)||^2$$
I attempted to use the chain rule, but I think it might be easier for example to use differentials.
I computed:
$$\frac{\partial}{\partial W}ln(p(T|X,W,\beta))=- \frac{\beta}{2}\sum_{n=1}^N \frac{\partial}{\partial W}(t_n -W^T \phi (x_n))^T(t_n -W^T \phi (x_n)) $$
$$=- \frac{\beta}{2}\sum_{n=1}^N \frac{\partial}{\partial (t_n-W^T \phi (x_n))}(t_n -W^T \phi (x_n))^T(t_n -W^T \phi (x_n))\frac{\partial}{\partial W} (t_n-W^T \phi (x_n)) $$
$$=- \beta\sum_{n=1}^N (t_n -W^T \phi (x_n))\frac{\partial}{\partial W} (t_n-W^T \phi (x_n)) $$
where I used $$\frac{\partial (x^Tx)}{\partial x}=2x$$ but I'm not sure how to compute the derivative:
$$\frac{\partial}{\partial W} (t_n-W^T \phi (x_n))$$
Answer: From wikipedia, We have
$$\frac{\partial (Xa+b)^TC(Xa+b)}{\partial X}=(C+C)^T(Xa+b)a^T$$
hence
\begin{align}\frac{\partial }{\partial W^T}[(t_n-W^T\phi(x_n))^T(t_n-W^T\phi(x_n))]  &=\frac{\partial }{\partial W^T}[(W^T\phi(x_n)-t_n)^T(W^T\phi(x_n)-t_n)]\\
&=2(W^T\phi(x_n)-t_n)\phi(x_n)^T\end{align}
We want
$$\sum_{n=1}^N(W^T\phi(x_n)\phi(x_n)^T-t_n\phi(x_n)^T)=0$$
$$W^T\sum_{n=1}^N\phi(x_n)\phi(x_n)^T=\sum_{n=1}^Nt_n\phi(x_n)^T$$
$$\left(\sum_{n=1}^N\phi(x_n)\phi(x_n)^T\right)W=\sum_{n=1}^N\phi(x_n)t_n^T$$
$$W=\left(\sum_{n=1}^N\phi(x_n)\phi(x_n)^T\right)^{-1}\sum_{n=1}^N\phi(x_n)t_n^T$$
Comment: Thanks, this is really helpful.
Answer: $
\def\b{\beta}\def\l{\lambda}
\def\L{\left}\def\R{\right}\def\LR#1{\L(#1\R)}
\def\trace#1{\operatorname{Tr}\LR{#1}}
\def\grad#1#2{\frac{\partial #1}{\partial #2}}
$For typing convenience, define the elementwise application of the $\phi$ function as the vector
$$y=\phi(x) \quad\implies\quad y_n=\phi(x_n)$$
and use a colon as a product notation for the matrix inner product
$$\eqalign{
A:B &= \sum_{i=1}^m\sum_{j=1}^n A_{ij}B_{ij} \;=\; \trace{AB^T} \\
A:A &= \big\|A\big\|^2_F \\
}$$
When applied to vectors this corresponds to the ordinary dot product.
Write the objective function in terms of the above, then calculate its differential and gradient.
$$\eqalign{
\l &= \log(p) \\
 &= \l_0 - \tfrac\b 2\LR{y^TW-t^T}:\LR{y^TW-t^T} \\
d\l &= -\b\LR{y^TW-t^T}:\LR{y^TdW} \\
  &= -\b\LR{yy^TW-yt^T}:dW \\
\grad{\l}{W} &= -\b\LR{yy^TW-yt^T} \\
}$$
Set the gradient to zero and solve for the optimal $W$.
$$\eqalign{
yy^TW &= yt^T \\
W &= (yy^T)^+yt^T = (ty^+)^T \\
}$$
where $y^+$ denotes the pseudoinverse of $y$.
We can go a bit further. The pseudoinverse of a vector has
a closed-form
$$y^+ = \frac {y^T}{y^Ty}$$
which can be substituted to obtain
$$W = \frac{yt^T}{y^Ty}$$

Note that the properties of the underlying trace function allow the terms in the inner product to be rearranged in many different ways, e.g.
$$\eqalign{
A:B &= B:A \\
A:B &= A^T:B^T \\
C:\LR{AB} &= \LR{A^TC}:B \;=\; \LR{CB^T}:A \\
}$$


R reference classes - how to determine if you're in an inherited method?

Question: For a given reference class method, how can I determine if it is inherited? More generally, how to determine how far up the inheritance tree I am?
For example, if my setup is:
A <- setRefClass("A",
        methods = list(foo = function() whosMethod())
    )
B <- setRefClass("B",
        contains = "A",
        methods = list(bar = function() whosMethod())
    )
b <- B()

ideally, I want whosMethod() to give me something like
> b$foo()
[1] "A"         # or maybe a numeric value like: [1] 1L

> b$bar()
[1] "B"         # or maybe a numeric value like: [1] 0L

Note this is distinctly different from class(.self), which would always return "B" in the above example.
Motivation - custom events
I want to have inheritance-like behavior for other things besides methods, for instance custom events. My methods may raise(someEvent) and during instantiation I pass event handlers to handle those events, e.g.
MyDatabase <- setRefClass(....)
datasourceA <- MyDatabase(....,
    eventHandlers = list(
        someEvent = function() message("Hello from myObj!"),
        beforeInsert = function(data) {
            if (!dataIsValid(data))
                stop("Data is not valid!")
        }
    )
)

Now, if a child class defines a event handler that has already been defined by a parent class, then I need to know which event handler should be overridden. In particular, if a methodA() registers handlerA() for someEvent and methodB() in a child class registers handlerB() for the same event, when attempting to register handlerA() in methodA() I need to know that I am in an parent method so that if handlerB() is already registered, I do not override it.
It would also be nice to be able to call parent event handlers from child ones, like callSuper() available to methods.
Comment: Why do want to do this?
Comment: @hadley - added my motivation above. Thanks.
Comment: I did a little exploration, and I'd say it's not possible. Even if it was possible, I don't think there's a non-trivial definition that works well with multiple inheritance: you have an inheritance graph, not an inheritance tree.

Is there a reason you don't want to use the existing condition handling mechanism in R? i.e. http://adv-r.had.co.nz/Exceptions-Debugging.html#custom-signal-classes
Comment: @hadley, using the existing condition handling mechanism means that every time I use my object, I have to wrap it with `withCallingHandlers(...., condA = ...., condB = ....)`, listing every condition handler, which gets tiresome and which I may simply forget to do. I just want to be able to define some set handlers at instantiation and be safe in the knowledge that my events will be always be triggered at the point of `raise()`.
Answer: Try this:
Traverse the inheritance graph and get respective methods
methodsPerClass <- function(x) {
    if (!inherits(x, "envRefClass")) {
        stop("This only works for Reference Class objects")
    }
    ## Get all superclasses of class of 'x' //
    supercl <- selectSuperClasses(getClass(class(b)), directOnly=FALSE)
    ## Get all methods per superclass //
    out <- lapply(c(class(x), supercl), function(ii) {
        ## Get generator object //
        generator <- NULL
        if (inherits(getClass(ii), "refClassRepresentation")) {
            generator <- getRefClass(ii)
        }
        ## Look up method names in class defs //
        out <- NULL
        if (!is.null(generator)) {
            out <- names(Filter(function(x) {
                    attr(x, "refClassName") == generator$className
                },
                as.list(generator$def@refMethods))
            )
        }
        return(out)
    })
    names(out) <- supercl
    ## Filter out the non-reference-classes //
    idx <- which(sapply(out, is.null))
    if (length(idx)) {
        out <- out[-idx]
    }
    ## Nicer name for actual class of 'x' //
    idx <- which(names(out) == "envRefClass")
    if (length(idx)) {
        names(out)[idx] <- class(x)
    }
    return(out)
}

I'm sure that one could come up with some nicer way of filtering out non-reference-classes in order to get rid of the 'idx' parts at the end, but it works.
This would give you:
methodsPerClass(x=b)
$A
[1] "bar"

$B
[1] "foo"

$.environment
 [1] "import"       "usingMethods" "show"         "getClass"     "untrace"
 [6] "export"       "callSuper"    "copy"         "initFields"   "getRefClass"
[11] "trace"        "field"

Query which method(s) belong to which class in particular
whosMethod <- function(x, method) {
    mthds <- methodsPerClass(x=x)
    out <- lapply(method, function(m) {
        pattern <- paste0("^", m, "$")
        idx <- which(sapply(mthds, function(ii) {
            any(grepl(pattern, ii))
        }))
        if (!length(idx)) {
            stop(paste0("Invalid method '", m,
                "' (not a method of class '", class(x), "')"))
        }
        out <- names(idx)
    })
    names(out) <- method
    return(out)
}

This would give you:
whosMethod(x=b, method="foo")
$foo
[1] "B"

whosMethod(x=b, method=c("foo", "bar"))
$foo
[1] "B"

$bar
[1] "A"

whosMethod(x=b, method=c("foo", "bar", "nonexisting"))
Error in FUN(c("foo", "bar", "nonexisting")[[3L]], ...) :
  Invalid method 'nonexisting' (not a method of class 'B')

Run it for all methods of class 'B':
whosMethod(x=b, method=unlist(methodsPerClass(x=b)))
$bar
[1] "A"

$foo
[1] "B"

$import
[1] ".environment"

$usingMethods
[1] ".environment"

$show
[1] ".environment"

$getClass
[1] ".environment"

$untrace
[1] ".environment"

$export
[1] ".environment"

$callSuper
[1] ".environment"

$copy
[1] ".environment"

$initFields
[1] ".environment"

$getRefClass
[1] ".environment"

$trace
[1] ".environment"

$field
[1] ".environment"


Jar via Tomcat in IntelliJ

Question: I spended a few hours to resolve my problem with deploying jar file on tomcat but I lost all fights, and I must ask one question:
Is it possible to run the jar file via tomcat in intelliJ?
Best regards
Comment: You deploy *war* files to Tomcat, not *jar* files. Perhaps it would be a good idea for you to read up on how to write Servlet code, you know, because Tomcat is a Servlet Container.
Comment: instead of using intellij,try to go to tomcat folder and go to webapps and place your jar there and open tomcat
Answer: It's not possible deploy a jar in Tomcat anywhere. You can only deploy war files.
Normally when you distribute a web application in a jar (like a spring boot app) you don't deploy it in a server, it's a standalone application you run from the command line.
Comment: So, how to deploy Jar in IntelliJ? Which container I must use to run it?

Jar via Tomcat in IntelliJ


In Drupal 8, how to automatically create a term in a specific vocabulary from the field present in node/add page?

Question:
Steps to reproduce -

Create two new vocabularies at - SITE/admin/structure/taxonomy/add
Add them as fields to the article content type. Set number of values to be unlimited, set form display to Autocomplete (tags style)
The new vocab fields do not work like the Tags field

Could you help me learn how to automatically create a term in a specific vocabulary from the field present in node/add page?
Answer: Thanks to a colleague, I found the setting I had to use.

Go to - SITE/admin/structure/types/manage/article/fields/node.article.field_vocab_a_tag
Check - Create referenced entities if they don't already exist
Comment: This works for drupal 8 too.


h2o python H2ODataFrame apply raising error "ValueError: unimpl bytecode instr: LOAD_CONST"

Question: Using h2o python api and have a H2ODataFrame that raises the error

ValueError: unimpl bytecode instr: LOAD_CONST

when trying to use the apply method on the frame.
The frame in question here looks like:
predict     0_good      1_bad
0_NoDenial  0.999593    0.000407184
0_NoDenial  0.999571    0.000428798
0_NoDenial  0.998374    0.00162572
0_NoDenial  0.999343    0.000657361
0_NoDenial  0.999307    0.000693177
0_NoDenial  0.999895    0.000104678
0_NoDenial  0.999495    0.000504838
0_NoDenial  0.999627    0.000373012
0_NoDenial  0.997075    0.00292529
0_NoDenial  0.996358    0.00364194

<class 'h2o.frame.H2OFrame'>

The code that raises the error looks like:
preds['predict'] = preds['1_bad'].apply(lambda x: '1_bad' if x > custom_thresh else '0_good', axis=1)

With the full error looking like:
/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/frame.pyc in apply(self, fun, axis)
   3034         assert_is_type(fun, FunctionType)
   3035         assert_satisfies(fun, fun.__name__ == "<lambda>")
-> 3036         res = lambda_to_expr(fun)
   3037         return H2OFrame._expr(expr=ExprNode("apply", self, 1 + (axis == 0), *res))
   3038

/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/astfun.pyc in lambda_to_expr(fun)
    133     code = fun.__code__
    134     lambda_dis = _disassemble_lambda(code)
--> 135     return _lambda_bytecode_to_ast(code, lambda_dis)
    136
    137 def _lambda_bytecode_to_ast(co, ops):

/home/mapr/anaconda2/lib/python2.7/site-packages/h2o/astfun.pyc in _lambda_bytecode_to_ast(co, ops)
    147         body, s = _opcode_read_arg(s, ops, keys)
    148     else:
--> 149         raise ValueError("unimpl bytecode instr: " + instr)
    150     if s > 0:
    151         print("Dumping disassembled code: ")

ValueError: unimpl bytecode instr: LOAD_CONST

I've never seen this kind of error before and quick googling did not tell much more. Does anyone know why this is happening and what can be done about it? Thanks.
Answer: for this scenario you might just want to use the h2o ifelse() method
(preds['1_bad'] < .0005).ifelse('good','bad')

or if you create a new column that consists of your thresholds and append it to your original frame you could do
(preds['1_bad'] < preds['my_thresholds']).ifelse('good','bad')


Hover effect using Styled Components in in React don't work

Question: Don't know why hover effect code on button in StyledComponents is not working, in React app.
Can You please look at the code ? Thanks !
<code> export const StyledButton = styled.button`
  width: 12vh;
  background-color: ${colors.buttonColor};
  -webkit-box-shadow: 0px 0px 35px -4px rgba(237, 38, 38, 0.51);
  box-shadow: 0px 0px 35px -4px rgba(237, 38, 38, 0.51);
  height: 4vh;
  margin-top: 5vh;
  border-radius: 5px;
  padding-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;

  & :hover {
    background-color: hotpink;
  }
`;

    <StyledButton>
          <Link to="/main" style={{ textDecoration: "none" }}>
            <StyledParagraph>Go without</StyledParagraph>
          </Link>
        </StyledButton>
</code>
Comment: you have an extra space, it should be `&:hover`
Answer: Do you need correct selector.
In styled components, if you are styling the component itself, you don't need to write "&:hover", you can write ":hover" instead.
Both selectors are correct, use either one. If I apply styles to the styled component itself, I usually don't write the "&" sign.
Instead
<code>  & :hover {
    background-color: hotpink;
  }
</code>
Do you need write
<code>  :hover {
    background-color: hotpink;
  }
</code>
Below code with correct selector for hover.
<code>export const StyledButton = styled.button`
  width: 12vh;
  background-color: ${colors.buttonColor};
  box-shadow: 0px 0px 35px -4px rgba(237, 38, 38, 0.51);
  height: 4vh;
  margin-top: 5vh;
  border-radius: 5px;
  padding-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;

  :hover {
    background-color: hotpink;
  }
`;
</code>


bootstrap navbar fixed top and body padding top

Question: I am trying to create fixed top navigation when scroll the window and from the point when top area becomes invisible. I did it but I have problem with body padding top when top area becomes visible again. Padding is added automatically to body, but should not, need only to be applied when navbar has an fixed-top class. See the picture (when top area becomes visible)
How to fix that problem with padding?
Site is live here

JavaScript

//FIXED NAVBAR ON SCROLL

$(document).scroll(function(event) {

  var wintop = $(window).scrollTop(); // Winodw Scroll Positon
  var topArea = $('.top-area').outerHeight(); // Header Logo Div Height

  if (wintop > topArea) {
    $('.navbar-default').addClass('navbar-fixed-top'); // Fixed Menu
    $('body').css('padding-top', parseInt($('.navbar-fixed-top').css("height")) + 1);
  } else {
    $('.navbar-default').removeClass('navbar-fixed-top'); // Unfixed Menu
  }
});

I have bootstrap navigation (navbar navbar-default) which is below top-area on site, this is code

Maršala Tita br. 54, Gložan 21412, Srbija

firstname.lastname@example.com

+381 21 788 584

+381 21 788 584

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
        Toggle navigation

      </button>

          <?php $currentPage=( basename($_SERVER[ "SCRIPT_NAME"])); ?>
          <li <?php if ($currentPage=='index.php' ) { echo "class='active'"; } else {echo '';} ?>>Početna

            O nama

Naša kompanija

Istorijat

Nagrade i priznanja

Rukovodstvo

Proizvodi

            Reference

Fabrika Knjaz Miloš, Aranđelovac

            Partneri

Partner 1

Partner 2

Partner 3

Partner 4

Partner 5

Partner 6

          <li <?php if ($currentPage=='novosti.php' ) { echo "class='active'"; } else {echo '';} ?>>Novosti

            Download

Download 1

Download 2

Download 3

Download 4

Download 5

Download 6

          <li <?php if ($currentPage=='kontakt.php' ) { echo "class='active'"; } else {echo '';} ?>>Kontakt

          <form class="navbar-form vertically-absolute-middle">

              <input placeholder="Unesite pojam za pretragu ovde" class="form-control" id="s" name="s" value="" type="text">

          </form>
          <button class="close">

          </button>

Answer: Just remove the padding-top in the else statement :
$(document).scroll(function(event) {

  var wintop = $(window).scrollTop(); // Winodw Scroll Positon
  var topArea = $('.top-area').outerHeight(); // Header Logo Div Height

  if (wintop > topArea) {
    $('.navbar-default').addClass('navbar-fixed-top'); // Fixed Menu
    $('body').css('padding-top', parseInt($('.navbar-fixed-top').css("height")) + 1);
  } else {
    $('.navbar-default').removeClass('navbar-fixed-top'); // Unfixed Menu
    $('body').css('padding-top', '0px');
  }
});

Comment: Thanks a lot, that's it... but do you know how to completely remove class from body when is padding 0px? http://prntscr.com/b1s9ct
Comment: You can play with `addClass()` and `removeClass()` and you set a default value for `padding-top` in the `body` tag.
Comment: Yes, I know, but nothing happens when I add $('body').removeClass('padding-top');
Comment: no, it's not good again. Because, when body has not padding, body looks like  but it should be just
Comment: Yes but you can't avoid that when you use javascript to toggle class or style. It is working though.
Comment: Please mark this subject as solved if it solved your issue ;)
Answer: Please try this:
$(document).scroll(function(event) {

  var wintop = $(window).scrollTop(); // Winodw Scroll Positon
  var topArea = $('.top-area').outerHeight(); // Header Logo Div Height

  if(wintop > topArea){
    $('.navbar-default').addClass('navbar-fixed-top'); // Fixed Menu
    $('body').css('padding-top', parseInt($('.navbar-fixed-top').css("height"))-109);
    } else {
    $('.navbar-default').removeClass('navbar-fixed-top'); // Unfixed Menu
  }
});


Content Types linked to Content Types

Question: Using Drupal (v7.22) I'm creating a site that lists different cars. The editor of the site wants to be able to add different stats to the cars. But they don't know exactly which stats they will need so want the ability to add stat themselves. So for example they can set up two different stats where they fill in values:
Content
  Content Type (Stat)
  Title = Stat A
  Default Value = 10
  Min Value = 0
  Max Value = 50

Content
  Content Type (Stat)
  Title = Stat B
  Default Value = 20
  Min Value = 0
  Max Value = 40

Then they can add those stats to a new Content Type that they have created. When they add a type of Stat it will include the Default Value but it can be changed:
Content Type
  Title = Car
  Stat A Value = 10
  Stat B Value = 20

Content Type
  Title = Lorry
  Stat B Value = 30

Finally they can create Content of that Content Type and the Stats will use the value for that Stat by default but they can change it. I will create rules so that the entered values must be within the min/max set by the Stat.
Content
  Content Type = Car
  Title = Car Name
  Stat A Value = 15
  Stat B Value = 18

Can this be done with Drupal?
Answer: I'm hoping this answer works for you. If you're wondering if you can set a default value for a field in a content type when adding new content, the answer is yes.
Comment: I'm actually looking for the ability to basically set a Content Type as a field within another Content Type. Or something to that effect
Comment: Ohh, I think I understand. You mean basically like predefined templates of a content type? So if you had a content type of "Car", you could have a predefined set of values for like "Ford Explorer", "Chevy Suburban", "Kia Rio", etc.?

Content Types linked to Content Types


How do I do a correlation between Likert scale and a dichtonomous?

Question: I have conducted a survey and collected 182 responses from 6 different groups and I am about to analyze my data:

group1: 101 responses
group2: 47 responses
group3: 15 responses
group4: 13 responses
group5: 6 responses

Some of in some of questions I used likert scale,
for example:

A How much is quality of life important to you?

1 not important at all...2.......3.............4........................5 very important

and  three kind of  personal questions:

B 1. where did you live prior to relocate to NYC?

1. SF  2. Austin 3. other U.S. areas  4. non U.S. area

C 2. please indicate your age.

1. below 40  2. between 41 and 50   3. over 50

D 3. were you born in NYC?

1. Yes  2. No

I am trying to:

Do a correlation between each group of responses and each single of likert scale questions.

Do a correlation between likert scale questions( I think in this section I have to use spearman)

Do a correlation between C questions and likert scale ones and D and likert scale ones.
Also between D and C and B.
Answer: Don't do correlations at all. Do ordinal logistic regressions instead and, if the assumption of proportional odds is really violated, try multinomial logistic.
Surely "Quality of life" is the dependent variable and the others are independent.
Correlations (of whatever sort) do not treat one variable as the dependent and others as independent - they treat all variables equally.  Also, correlations look at the relationship between two variables.  Regression lets you control for multiple variables.
Ordinal logistic regression is good when the DV is ordinal, but the usual method assumes proportional odds.  Although there are models that do not make that assumption - or make it partially - they are relatively little known, so multinomial might be better


PDO - Duplicate entry on file upload

Question: I'm developing a module that uploads CSV file.
<code>/**
 * Implements hook_menu().
 */
function geo_points_menu(){
    $items['geo-points-upload'] = array(
        'title' => 'Geo points',
        'description' => 'Upload users',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('geo_points_form'),
        'access arguments' => array('access content'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu',
    );

    return $items;
}

function geo_points_form($form, &$form_state) {
    $form = array();

    // Use the #managed_file FAPI element to upload a file.
    $form['file_fid'] = array(
        '#title' => t('File'),
        '#type' => 'managed_file',
        '#description' => t('The uploaded file will be processed.'),
        '#default_value' => variable_get('file_fid', ''),
        '#upload_validators' => array(
            'file_validate_extensions' => array('csv'),
        ),
        '#upload_location' => 'public://csv_uploads',
        '#process' => array('geo_points_my_file_element_process')
    );

    $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Import'),
    );

    return $form;
}

/* It disables the default upload button that comes with this #managed_file form */
function geo_points_my_file_element_process($element, &$form_state, $form) {
    $element = file_managed_file_process($element, $form_state, $form);
    $element['upload_button']['#access'] = FALSE;

    return $element;
}

function geo_points_form_submit(&$form, &$form_state) {
    // Load the file.
    $file = file_load($form_state['values']['file_fid']);
    dpm(csv_to_array($file->uri));
    file_usage_delete($file, 'geo_points');
//    // Change status to permanent.
//    $file->status = FILE_STATUS_PERMANENT;
//    // Save.
//    $uploaded = file_save($file);
//    if ($uploaded == TRUE) {
//        dpm(csv_to_array($file->uri));
//    }
//    else {
//        drupal_set_message(t('The file could not be uploaded. Please contact the site administrator.'), 'error');
//    }

    //$file_path = $file->uri;

    //Function call to process file contents.
    //csv_import_create_node($file_path);

}

/**
 * @param string $filename
 * @param string $delimiter
 * @return array|bool
 */
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}
</code>
When I upload the same file more than one time I'm getting the following exception:
<code>PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://csv_uploads/points2014-01-16T14-22-48.csv' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => points2014-01-16T14-22-48.csv [:db_insert_placeholder_2] => public://csv_uploads/points2014-01-16T14-22-48.csv [:db_insert_placeholder_3] => text/csv [:db_insert_placeholder_4] => 84 [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 1390315536 ) in drupal_write_record() (line 7170 of C:\wamp\www\drupal7_poc2\includes\common.inc).
</code>
I have 2 questions:
1. How avoid this exception.
2. After I upload the file and read it's content I don't the file anymore, can I read the stream only without saving the file?
Answer:
Use a try...catch block and recover in whatever way makes most sense to your application.
The file is already on the disk by the time you get access to it (in the /tmp folder), so no. If you don't explicitly choose to keep it, it will be deleted either by a system job or the system module's cron run.

PDO - Duplicate entry on file upload


How to create radio button in AS400 using DSPF record file and AS400

Question: 0001.90      A                                 13  3'Warehouse . . . . . .'
0002.00      A            WAREHOUSE      2Y 0B 14  9SNGCHCFLD
0002.10      A                                      CHOICE(1 '>W1')
0002.20      A                                      CHOICE(2 '>W2')

This is my Source code. this does not display the output as a radio button. expected output screen like enter image description here. This code gives the output asenter image description here. how to display the radio button using fixed format RPGLR and DSPF at RECORD type
Expected output Screen enter image description here
Comment: Not Sure about TN5250, but the documentation states nothing about enhanced display capabilities. Termina Emulation sounds like it is emulating a dumb 5250 terminal, which cannot diplay enhanced stuff.
I recommend using IBM I access client solutions, which should work.
Comment: Mocha does **not** support enhanced (pseudo-graphical) display.
Comment: Did you try to display the radio button without the > character?
What client are you using to display the screen? I guess the character is interpreted by the client.
Answer: First off, when you compile the DSPF using CRTDSPF, make sure you specify
ENHDSP(*YES)
Second, what 5250 client are you using?  If not IBM's then contact your vendor to see if the client supports the 5250 GUI elements.
Remember 5250 is not a "dumb" terminal protocol.  The client does a considerable amount of processing.
Comment: hi Charles. Thank you for you answer. Please give some detailed answer. Am new in AS400.  Thanks
Comment: Seems pretty detailed to me, did you do the things he suggested? What client are you using?
Comment: I am using Mocha TN5250
Comment: @Charles ENHDSP(*YES) is default.
Comment: @PoC it may be the currently shipped default...doesn't mean it's the OP's default.


Subrings of fraction fields

Question: Let $R$ be an integral domain and let $S$ be a ring with $R \le S \le \text{Frac}(R)$ (fraction field).
Question: Is there a multiplicatively closed subset $U \subseteq R\setminus \{0\}$ such that $S=R[U^{-1}]$ ?
Comment: Any non-Prüfer domain $R$ will provide some example. Indeed, any $U^{-1}R$ is flat over $R$, but if $R$ is not a Prüfer domain, then it has some overring $S \supset R$ which is not flat over $R$.
Comment: In the case that $R$ is a PID this is proven in my answer [here.](http://math.stackexchange.com/a/137887/38268)
Answer: There are lots of examples arising from integral closures. For example, $k[x^2,x^3] \subseteq k[x]$ with field of fractions $k(x)$ is no localization since $k[x^2,x^3]^* = k^* = k[x]^*$.
Comment: @BenjaLim It's the group of units. The argument is that since the units of $R = k[x^2,x^3]$ are the same as the units of $S = k[x]$, the ring $S$ cannot arise from adjoining fractions to $R$, as this would enlarge the set of units. (At least, that's what I understood.)
Comment: @BenjaLim The field of fractions of $k[x^2,x^3]$ is $k(x)$ as well, since $x^2/x^3 = 1/x$, so $k[x^2,x^3]$ is our base ring $R$ and $k[x]$ is the extension $S$.
Comment: @K.Stm. But unless I am misunderstanding martin's example, shouldn't we want a ring containing $k[x]$ and not one that $k[x]$ contains?
Comment: I can't see what this answer has to do with "integral closures". It seems that the key point here is $U(R)=U(S)$.
Comment: @YACP: I just wanted to indicate the origin of this example (namely that it is part of a large class of examples). If $R$ is an integral domain, we may take its integral closure $S$ inside its field of fractions. So we are in the situation of the question, and may ask if $R \to S$ is a localization. But this is almost never the case. Of course, the example can also be understood without this origin.
Comment: For the algebro-geometric minded reader, the question is just: Is every birational dominant morphism of integral schemes a limit of open immersions? And of course this is wrong.
Answer: I've shown here that the ring $S=K[X]+YK(X)[Y]$ is not noetherian. Note that we have $K[X,Y]=R\subset S\subset Q(R)=K(X,Y)$. Since $R$ is noetherian, $S$ can't be a localization of $R$.
Answer: Let $U$ be the multiplicative set $\{r\in R\mid \frac 1r\in S\}$, which is the "obvious" (and maximal) candidate. Then clearly $R[U^{-1}]\subseteq S$. But is $S\subseteq R[U^{-1}]$?
Can we conclude $\frac1b\in S$ from $\frac ab\in S$?
Note how we would e.g. conclude $\frac13\in S$ from $\frac23\in S$: We'd use $2\cdot \frac23-1=\frac13$. Such is not possible in general.
Let $R=\mathbb Z[X]$ and $S=R[\frac X2]$.
Then if we assume $S=R[U^{-1}]$, there must be $g\in U$, $f\in R$ such that
$\frac X2=\frac fg$, i.e. $2f=Xg$. Since also $\frac 1g\in S\subseteq \mathbb Q[X]$, necessarily $g$ is constant, i.e. $g=2k$ with $k\in\mathbb Z\setminus \{0\}$. but $\frac1{2k}\notin S$ because the image of the homomorphism $S\to\mathbb Q$ induced by $X\mapsto 0$ is in $\mathbb Z$.
Comment: Do you mean $S=\mathbb{Z}[X/2]$?
Comment: @MartinBrandenburg: Since $X\in\Bbb Z[\frac X2]$ it makes no difference with what Hagen says. I suppose he just wanted to emphasise that $S\supset R$.
Answer: Another class of counterexamples (to which Martin's example belongs to) is:

If $R \lneqq S \le \text{Frac}(R)$ is finitely generated as $R$-module, then $S$ is no localization of $R$.

Proof: Suppose $S=R[U^{-1}]$ is generated by $s_i \in S\;(i=1,\ldots,n)$. By taking a common denominator, we can write $s_i=r_i/u$ with $r_i \in R, u \in U$. Thus $S$ is generated by $1/u$ over $R$. Therefore we find $r \in R$ such that $1/u^2=r/u$, i.e. $1/u=r$ is a unit in $R$. This yields $S=R(1/u) = Rr=R$. q.e.d.
In combination with BenjaLim's comment we obtain the corollary:

If $R$ is a PID, then no ring $R \lneqq S \le \text{Frac}(R)$ is finitely generated over $R$.

Subrings of fraction fields


Linear dependence of functions involving $e^x$

Question: On a test today I was given the following functions:
$$ f(x) = (-1+x)e^x$$
$$g(x)=-2e^x$$
We were asked to show if it was linearly dependent or linearly independent
So I showed that if I multiplied $g(x)$ by $\frac{1}{2}-x\frac{1}{2}$ I would get $f(x)$ for any value plugged into $g(x)$ and I said they were linearly dependent but I do not think that what I showed was correct.
Answer: $f$ and $g$ are linearly dependent if for some non-zero $A, B$:
$$
Af + Bg \equiv 0
$$
You have
$$
Af(x) + Bg(x) = e^x (-A + Ax - 2B)
$$
The only way for this to be exactly 0 for all $x$ is if $A=B=0$ - so $f$, $g$ are not linearly dependent.
Answer: $$f(x) = (-1+x)e^x$$ and $$g(x)=-2e^x$$ are linearly independent because none of them is a constant times the other.
The way to show that is to consider $$ c_1 f(x)+c_2g(x) \equiv 0$$ and show  that $$c_1=c_2 =0$$
That is done by assigning values to $x$ and  solve the resulting system for $c_1$ and $c_2$


Is it possible to use safari extension in ios application

Question: I am developing an iOS app with app extension feature.But using "App Extension" we could not customize safari content.Anyone having idea about "Safari Extension".Can we use safari extension in ios app?
Answer: Safari App Extensions are desktop only and have to bundled with a containing macOS app. On iOS you can have Content Blockers.
Comment: Desktop also has Content Blockers.


Determining PCA scores for a new data point

Question: I have done a principal component analysis (PCA) on a dataset (using prcomp in R) and now I want to determine what the principle component scores would be for a new sample(s). How can I do this?
I'm sure the information is encoded somewhere in the prcomp output, but I can't figure out which table, how to tie it back to a function, and I'm sure someone has already devised a command to do this (which I can't find).
Comment: Try `my_pca <- prcomp(USArrests, scale = TRUE)`. Component scores are then in object `my_pca$x`.
Answer: The code
require(graphics)

## the variances of the variables in the
## USArrests data vary by orders of magnitude, so scaling is appropriate
res<-prcomp(USArrests, scale = TRUE, retx=TRUE)

computes the principal components, in the result res$center you find the centers, in the result res$scale the scaling factors and in res$rotation you find the coefficients for transforming the centered data to the pcs.
As I use the option retx=TRUE in the above call to prcomp, res$x contains the prinicpal components computed by prcomp().
You can yourself compute res$x as follows (and this also for 'new' observations, see at the bottom):
# center and scale the data
c.fun<-function(df, center, scale) {
  return((df-center)/scale )
}
centeredData<-apply(USArrests, MARGIN=1, FUN=c.fun, res$center, res$scale  )

# compute the principal components
pcs<-t(res$rotation) %*% centeredData

# compare with results of prcom (option retx=TRUE gives ^cs in x)
head(t(pcs))
head(res$x)
    # check if results are the same
    sum(abs(t(pcs)-res$x))

If you want to compute the components for new data, then (I use fake data) you do:
# some fake 'new data'
newdata<-USArrests[1:10,]
centeredNewData<-apply(newdata, MARGIN=1, FUN=c.fun, res$center, res$scale  )
pcsnew<-t(res$rotation) %*% centeredNewData


Domain Time Skew

Question: A few months ago I attempted to get time straightened out in our environment but I never really got it working correctly. We have 4 domain controllers and the time difference always seems to be anywhere from 30 seconds off up to 300 seconds off. It randomly seems to correct itself then start to drift again. Time on workstations always seems to be 1 to 2 minutes off.
I used this guide. https://community.spiceworks.com/how_to/65413-configure-dc-to-synchronize-time-with-external-ntp-server
Here's some additional information.
PDCe: Physical Machine
DC2: VM
DC3: VM
DC4: VM
The virtual DCs are set to not sync time with their host.
Here's the w32tm /query /configuration from each DC.
PDCe

EventLogFlags: 2 (Local)
AnnounceFlags: 5 (Local)
TimeJumpAuditOffset: 28800 (Local)
MinPollInterval: 6 (Local)
MaxPollInterval: 10 (Local)
MaxNegPhaseCorrection: 172800 (Local)
MaxPosPhaseCorrection: 172800 (Local)
MaxAllowedPhaseOffset: 300 (Local)

FrequencyCorrectRate: 4 (Local)
PollAdjustFactor: 5 (Local)
LargePhaseOffset: 50000000 (Local)
SpikeWatchPeriod: 900 (Local)
LocalClockDispersion: 10 (Local)
HoldPeriod: 5 (Local)
PhaseCorrectRate: 7 (Local)
UpdateInterval: 100 (Local)

FileLogName: C:\Windows\Temp\w32time.log (Local)
FileLogEntries: 0-116 (Local)
FileLogSize: 268435456 (Local)

[TimeProviders]

NtpClient (Local)
DllName: C:\Windows\SYSTEM32\w32time.DLL (Local)
Enabled: 1 (Local)
InputProvider: 1 (Local)
AllowNonstandardModeCombinations: 1 (Local)
ResolvePeerBackoffMinutes: 15 (Local)
ResolvePeerBackoffMaxTimes: 7 (Local)
CompatibilityFlags: 2147483648 (Local)
EventLogFlags: 1 (Local)
LargeSampleSkew: 3 (Local)
SpecialPollInterval: 3600 (Local)
Type: NTP (Local)
NtpServer: time.nist.gov,0x1 time-a-g.nist.gov,0x1 time-a-wwv.nist.gov,0x1 time-a-b.nist.gov,0x1 (Local)

NtpServer (Local)
DllName: C:\Windows\SYSTEM32\w32time.DLL (Local)
Enabled: 1 (Local)
InputProvider: 0 (Local)
AllowNonstandardModeCombinations: 1 (Local)

DC2

EventLogFlags: 2 (Local)
AnnounceFlags: 10 (Local)
TimeJumpAuditOffset: 28800 (Local)
MinPollInterval: 6 (Local)
MaxPollInterval: 10 (Local)
MaxNegPhaseCorrection: 172800 (Local)
MaxPosPhaseCorrection: 172800 (Local)
MaxAllowedPhaseOffset: 300 (Local)

FrequencyCorrectRate: 4 (Local)
PollAdjustFactor: 5 (Local)
LargePhaseOffset: 50000000 (Local)
SpikeWatchPeriod: 900 (Local)
LocalClockDispersion: 10 (Local)
HoldPeriod: 5 (Local)
PhaseCorrectRate: 7 (Local)
UpdateInterval: 100 (Local)

[TimeProviders]

NtpClient (Local)
DllName: C:\Windows\SYSTEM32\w32time.DLL (Local)
Enabled: 1 (Local)
InputProvider: 1 (Local)
CrossSiteSyncFlags: 2 (Local)
AllowNonstandardModeCombinations: 1 (Local)
ResolvePeerBackoffMinutes: 15 (Local)
ResolvePeerBackoffMaxTimes: 7 (Local)
CompatibilityFlags: 2147483648 (Local)
EventLogFlags: 1 (Local)
LargeSampleSkew: 3 (Local)
SpecialPollInterval: 1024 (Local)
Type: NT5DS (Local)

NtpServer (Local)
DllName: C:\Windows\SYSTEM32\w32time.DLL (Local)
Enabled: 1 (Local)
InputProvider: 0 (Local)
AllowNonstandardModeCombinations: 1 (Local)

VMICTimeProvider (Local)
DllName: C:\Windows\System32\vmictimeprovider.dll (Local)
Enabled: 0 (Local)
InputProvider: 1 (Local)

DC3

EventLogFlags: 2 (Local)
AnnounceFlags: 10 (Local)
TimeJumpAuditOffset: 28800 (Local)
MinPollInterval: 6 (Local)
MaxPollInterval: 10 (Local)
MaxNegPhaseCorrection: 172800 (Local)
MaxPosPhaseCorrection: 172800 (Local)
MaxAllowedPhaseOffset: 300 (Local)

FrequencyCorrectRate: 4 (Local)
PollAdjustFactor: 5 (Local)
LargePhaseOffset: 50000000 (Local)
SpikeWatchPeriod: 900 (Local)
LocalClockDispersion: 10 (Local)
HoldPeriod: 5 (Local)
PhaseCorrectRate: 7 (Local)
UpdateInterval: 100 (Local)

[TimeProviders]

NtpClient (Local)
DllName: C:\Windows\system32\w32time.dll (Local)
Enabled: 1 (Local)
InputProvider: 1 (Local)
CrossSiteSyncFlags: 2 (Local)
AllowNonstandardModeCombinations: 1 (Local)
ResolvePeerBackoffMinutes: 15 (Local)
ResolvePeerBackoffMaxTimes: 7 (Local)
CompatibilityFlags: 2147483648 (Local)
EventLogFlags: 1 (Local)
LargeSampleSkew: 3 (Local)
SpecialPollInterval: 1024 (Local)
Type: NT5DS (Local)

NtpServer (Local)
DllName: C:\Windows\system32\w32time.dll (Local)
Enabled: 1 (Local)
InputProvider: 0 (Local)
AllowNonstandardModeCombinations: 1 (Local)

VMICTimeProvider (Local)
DllName: C:\Windows\System32\vmictimeprovider.dll (Local)
Enabled: 0 (Local)
InputProvider: 1 (Local)

DC4

EventLogFlags: 2 (Local)
AnnounceFlags: 10 (Local)
TimeJumpAuditOffset: 28800 (Local)
MinPollInterval: 6 (Local)
MaxPollInterval: 10 (Local)
MaxNegPhaseCorrection: 172800 (Local)
MaxPosPhaseCorrection: 172800 (Local)
MaxAllowedPhaseOffset: 300 (Local)

FrequencyCorrectRate: 4 (Local)
PollAdjustFactor: 5 (Local)
LargePhaseOffset: 50000000 (Local)
SpikeWatchPeriod: 900 (Local)
LocalClockDispersion: 10 (Local)
HoldPeriod: 5 (Local)
PhaseCorrectRate: 7 (Local)
UpdateInterval: 100 (Local)

[TimeProviders]

NtpClient (Local)
DllName: C:\Windows\SYSTEM32\w32time.DLL (Local)
Enabled: 1 (Local)
InputProvider: 1 (Local)
CrossSiteSyncFlags: 2 (Local)
AllowNonstandardModeCombinations: 1 (Local)
ResolvePeerBackoffMinutes: 15 (Local)
ResolvePeerBackoffMaxTimes: 7 (Local)
CompatibilityFlags: 2147483648 (Local)
EventLogFlags: 1 (Local)
LargeSampleSkew: 3 (Local)
SpecialPollInterval: 1024 (Local)
Type: NT5DS (Local)

NtpServer (Local)
DllName: C:\Windows\SYSTEM32\w32time.DLL (Local)
Enabled: 1 (Local)
InputProvider: 0 (Local)
AllowNonstandardModeCombinations: 1 (Local)

VMICTimeProvider (Local)
DllName: C:\Windows\System32\vmictimeprovider.dll (Local)
Enabled: 0 (Local)
InputProvider: 1 (Local)

Anyone have any ideas? I'd greatly appreciate any help.
Comment: Enable Windows Time Service logging on the DC's.  Also the /status /verbose switches provide more information. When you say "off", that needs to be relative to the DC, not the actual time. If time on a workstation is the same as the time on the DC that it is synchronizing from, that is the expected result even if the time is incorrect.  #1 get the PDCE working. #2 get the other DC's working.  https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/turn-on-debug-logging-in-windows-time-service
Comment: @GregAskew, thanks for the reply. I'm enabling logging on all the DCs now. The time is off relative to the DCs, not the actual time.
Answer: Are you saying the DCs are drifting from the PDCE as well?
Firstly, I suggest configuring the peer list on the PDCE to use 0x8 rather than 0x1.
w32tm.exe /config /syncfromflags:manual /manualpeerlist:time.nist.gov,0x8 time-a-g.nist.gov,0x8 [...] /reliable:yes /update
In the System event log, does the PDCE show it's successfully syncing time? I suggest filtering the log source to show events from Time-Service.
There should be one event 35 for each of the peers you have configured to show they're syncing time. Then followed by Event 37 for each peer to say the PDCE is receiving valid time. You may need to run w32tm /resync /rediscover or restart the service to trigger the events.
Check the peers too: w32tm /query /peers.
If any show State: pending, run w32tm /query /status and check each peer for a Last Successful Sync Time a long time in the past (e.g. more than an hour). If that's the case, you might have a networking issue or it's a bad source.
Next, does the PDCE show Events 139 followed by 143 (event 12 might appear as a temporary warning before 143), showing that it is advertising as a time source and then a good time source? At this point, the PDCE is advertising correctly. Or it should be. This can take a few minutes after rediscovering/restarting the service. Make sure there is no 144 event after 143 - this means the PDCE has stopped advertising as a time source.
Next, on your other DCs, run w32tm /query /peers. Check there's just the one peer (PDCE), that the state is Active, and that the Time Remaining is less than the PeerPoll\HostPoll intervals. Which is 1024 for yours, it seems.
C:\> w32tm /query /peers
#Peers: 1

Peer: PDCE.xxx.au
State: Active
Time Remaining: 593.4024152s
Mode: 1 (Symmetric Active)
Stratum: 2 (secondary reference - syncd by (S)NTP)
PeerPoll Interval: 10 (1024s)
HostPoll Interval: 10 (1024s)

In the System event log, the last Time-Source events should be 35 or 37, to say the DC is getting time from the PDCE. There should be a 139 event to say it's advertising as a time source. There should not be a 143 event (advertising as a good time source) unless it's most recently followed by a 144 warning (it's stopped advertising as 'good').
If there are any issues with any of the above, check that the NTP ports are open between the DCs - UDP 123. Obviously, if the PDCE isn't getting time from its upstream sources, check the port as well. There may be a local timesource you should use instead (we use the one configured internally as part of our DNS/DHCP solution managed by the Networks team, which is downstream from the Stratum 1 clock in our region).
If the most recent time events are warnings or errors on the DC - 35/37 aren't the most recent time events on the non-PDCEs - those will be worth investigating.
If the DCs are all fine with time sync, then the next thing is to look at the clients.
By the way, it's good to configure this with Group Policy. I highly recommend that there's a GPO targeted to the PDCE so that if you move the role, the time config goes with it. I also have a "default" time GPO just as a fallback in the DC policies - it's just the usual defaults - but really there to ensure that a former PDCE gets the regular time config back after the FSMO is moved. But GPOs can be done later, once the DCs are happy.

Domain Time Skew


Including hash values in ASP.NET MVC URL routes

Question: I need to implement hash value i.e the Url should look like this:

/home/index/#create

For this have added a route:
routes.MapRoute(
    "Default",    // Route name
    "{controller}/{action}/#{detail}",    // URL with parameters
    new { controller = "Login", action = "LogIn",  detail  =""}  // Parameter defaults
);

On accessing /home/index/#create, it is redirecting me to the default route.
How can this be done?
Comment: Based on some answers. I know with #hash, browser does not sending a request to the server BUT that only when the URL change for the second time within the same page. So this question still make sense. Think if user bookmark this URL! the #hash may refer to comment anchor or represent a selected menu. I still looking a right way to do this in route.
Answer: As stated there is no way to do this using routing. The only possible solution is to append the # fragment to your url when redirecting in the actions of your controller. Eg.
return Redirect(Url.Action("Index", "Home") + "#create");

Comment: IMO this should be the accepted answer.  The OP asked, "How can this be done?" and this is the only answer that gives you a reasonable workaround, rather than why you can't do it the way the OP originally wanted to.
Comment: I just spent 20 minutes trying to figure out how to make a "return View()" method to allow a hash parameter, or any other action result - this is perfect. Good answer!
Comment: Thank you for this answer! I recently had to implement the same thing, and this worked for me. However, I ran it in the HTML which required a slightly different syntax: `href="@Url.Action("Index","Home")#deep-link"`
Answer: You cannot fetch the value after the # symbol on the server simply because this value is never sent to the server. Only client side javascript has access to this so defining routes with hash doesn't make much sense.
Comment: It make sense. My `#hash` used to memorize selected menu (I don't want cookie). When user click a menu, the `#` changed and AJAX request to the server to update the respective content. By this way user able to bookmark the page with selected menu AND can use browser back button with readable `#menuname`. Next time when user browse with the `#`, then the loaded page is already have the selected menu without unnecessary AJAX request. I need to bind the hash value into route data because each `#` can be considered a different page.
Comment: You could use javascript to send this to the server as part of a form request.
Comment: NOTE: some APIs like Google's identity service use the value in the `#hash` to hold the token for exchange in the next call.  So it would be nice to have an answer that addresses that.
Answer: When a browser makes a request for a URL, it does not send anything after a hash to the server.  This route may enable you to generate route URLs containing the hash value but there is no way to do anything server-side when the user navigates to such a URL.  That's just the way the web works...
Answer: OAuth 2.0 Implicit Flow
If this has to do with OAuth 2.0 Implicit Flow, you should use Authorization Code Grant instead.


Find the vector form of the equation for the line of intersection of the planes $x+y+z=8$ and $x+z=0$

Question: So $n_1= \langle 1,1,1 \rangle$ and $n_2= \langle 1,0,1 \rangle$. If we cross multiply these we get $i-k$ or $\langle 1,0,-1 \rangle$. From here I set $y=0$ since the second plane has a $y$ value of $0$, and line up $x+z=8$ and $x+z=0$. From here I'm stuck and can't get an $x$ or $z$ value.
Comment: Why did you set $y = 0$? You found the normal vector which is great. All you need now is a point on the line. If you subtract $x+z=0$ from $x+y+z = 8$, you get $y = 8$. Great, now you can choose a point on the line by choosing an $x$ value, say $0$, and then you get $z = 0$. So $(0,8,0)$ is a point on the line. Do you know how to get the equation of a line given a point and direction?
Comment: Yes, thank you!
Comment: The two inconsistent equations that you've come up with tell you that there isn't any point in the intersection with $y=0$.
Answer: My favorite way: solve the system of equations
$$
\begin{cases}
x+y+z &=8\\
x+ z &=0\\
z&=t
\end{cases}
$$This gives $(x,y,z)=(-t,8,t)$.
Answer: Take any two distinct points of the line; just take a pair of solutions of the system$$\left\{\begin{array}{l}x+y+z=8\\x+z=0,\end{array}\right.$$such as $(0,8,0)$ and $(1,8,-1)$. Then $(1,8,-1)-(0,8,0)=(1,0,-1)$ and so your line is$$\{(0,8,0)+\lambda(1,0,-1)\mid\lambda\in\Bbb R\}.$$


Cosets & Lagrange's Theorem

Question: Let $G$ have order $pq$, where $p$ and $q$ are primes. Either $G$ is cyclic, or every element $x \ne e$ in $G$ has order $p$ or $q$.

So probably cases, right? I know I need to use Lagrange's Theorem, but I'm not sure how. So $G$ has $pq$ elements... Im just confused
Answer: Lagrange's theorem says every element has order dividing the order of the group. If there's an element with order equal to the order of the group, $G$ is cyclic. If there isn't, then every element has order strictly less than $pq$ and dividing it. There aren't that many divisors of $pq$ -- only $1,p,q$. That should do it.
Edit: Given your version of Lagrange's theorem -- for every subgroup $H\subset G$ of a finite group, we have $|H|\mid|G|$ -- take $H=\langle x \rangle$ for any element $x\in G$. Then $|H|=|x|$.
Comment: Lagrange's Theorem states that the order of a group is a multiple of a subgroup of that group.

Cosets & Lagrange's Theorem


Find a chain of functions to get a required output

Question: Let's say I have a following template:
template<class out_t, class in_t>
out_t my_cast(const in_t&) = delete;

And then several specializations:
template<>
B my_cast(const A& a) { /* stuff */ }
template<>
X my_cast<X, A>(const A& a) { /* stuff */ }
template<>
C my_cast<C, B>(const B& b) { /* stuff */ }
template<>
C my_cast<C, X>(const X& x) { /* stuff */ }

template<>
V my_cast<V, A>(const A& a) { /* stuff */ }
template<>
Z my_cast<Z, V>(const V& v) { /* stuff */ }

If I wanted to cast from A to Z, I'd have to combine two casts like that: auto z = my_cast<Z>(my_cast<V>(some_a));
This obviously is an example, I imagine cases where I'd have to go through tens of such casts, and coding this manually is clearly a no–go. Is there a way to automatically find those paths on compile time, so that my_cast<Z>(some_a) would be automatically resolved?
This can sadly lead to some ambiguities, like casting from A to C, which can be done in two ways: A→B→C, or A→X→C. In this case a compile error would satisfactory.
Comment: If a different syntax is good enough for you, you could define your casts as member functions: `some_type my_cast(std::integral_constant) {...}`, where `i` is an incremental ID. Using tag as the parameter lets you use SFINAE to count all possible casts from a type, and then you can iterate over them at compile-time. After that you can recursively traverse the graph of casts looking for the needed type. I'll try to experiment with it and maybe will make an answer later.
Answer: No, this cannot be done automatically. One level of automatic conversion is allowed but the compiler simply is not going to do more on its own.
Comment: Something tells me you underestimate template kung fu skills of SO residents. :) (it may requre a different syntax of conversion declarations, but still)
Comment: It seems doable with help of boost.hana, but it'd likely still be a nightmare.

…I shouldn't bother such old threads, should I?


Como gerar valor ao clicar em um input type submit

Question: Formulário para enviar os dados selecionados para exclusão.
<form action="index.php?pagina=../controller/controllerUser&acao=ok" method="POST" enctype="multipart/form-data">
                        Nome:
                        <input class="input-xlarge" type="text" value="<?php echo $nome; ?>" name="nome" autofocus="">

                        CPF:
                        <input class="input-large" type="text" name="cpf"  autofocus="">

                        Senha:
                        <input class="input-large" type="text" name="senha"  autofocus="">

                        Repetir a senha:
                        <input class="input-large" type="text" name="confirmarSenha"  autofocus="">

                        CEP:
                        <input class="input-medium" type="text" name="cep"  autofocus="">

                        Endereço
                        <input class="input-xlarge" type="text" name="descricao"  autofocus="">

                        Complemento
                        <input class="input-xlarge" type="text" name="complemento" autofocus="">

                    E-mail
                        <input class="input-xlarge" type="text" name="email" autofocus="">

                    Telefone
                    <input class="input-xlarge" type="text" name="telefone"  autofocus="">

                    Telefone Dois
                    <input class="input-xlarge" type="text" name="telefoneDois"  autofocus="">

                    Selecione um País
                    <select required="" name="id_pais">
                        <?php
                        $daoPais->selecionaTodosPaises();
                        ?>
                    </select>

                    Selecione um estado
                    <select required="" name="idEstado" id="idEstado" onchange="getValorEstado(this.value, 0)">
                        <option selected="" disabled="" value="nulo">Selecione o ESTADO</option>
                        <?php
                        $daoEstado->selecionaTodosEstados();
                        ?>
                    </select>

                    Selecione uma Cidade
                    <select required="" id="idCidade" name="idCidade">
                        <option selected="" disabled="" value="nulo">Selecione o ESTADO ANTES</option>

                    </select>

                    <input class="btn btn-large btn-primary" type="submit" value="salvar">
                    Cancelar
                    </form>

irá redirecionar para a pagina de controller que insere ou exclui até o momento.
if (isset($_GET["acao"]) and $_GET["acao"] == "ok") {

//primeiro inserir o endereço
//atributos de endereço
$descricao = $_POST["descricao"];
$complemento = $_POST["complemento"];
$cep = $_POST["cep"];
$idCidade = $_POST["idCidade"];

//objeto de endereco
$endereco = new EnderecoEntity("", $descricao, $complemento, $cep, $idCidade);

//dao de endereço
$daoEndereco = new EnderecoDao();
$idEndereco = $daoEndereco->inserirEndereco($endereco);

//depois inserir o usuário com id de endereço

$nome = $_POST["nome"];
$cpf = $_POST["cpf"];
$senha = $_POST["senha"];

$usuario = new UsuarioEntity("", $nome, $cpf, $senha, $idEndereco);

$usuarioDao = new UsuarioDao();
$idUsuario = $usuarioDao->inserirUsuario($usuario);

//depois inserir o telefone com id de usuário
$telefoneUm = $_POST["telefone"];
$telefoneDois = $_POST["telefoneDois"];

$telefone = new TelefoneEntity("", $telefoneUm, $telefoneDois, $idUsuario);
$telefoneDao = new TelefoneDao();
$telefoneDao->inserirTelefone($telefone);

//depois inserir email com id de usuário
$email = $_POST["email"];
$email = new EmailEntity("", $email, $idUsuario);
$emailDao = new EmailDao();
$emailDao->inserirEmail($email);
 }
if (isset($_GET["acao"]) and $_GET["acao"] == "deletar") {

$idEndereco = $_GET["id_endereco"];
$idPessoa = $_GET["id"];
//verificação de confirmação do usuário
?>

    //o ponto de erro é esse sei que vou perder os dados quando tentar retornar para esse form
    <form action="index.php?pagina=../controller/controllerUser&acao=deletarConcluido"> method="POST" enctype="multipart/form-data">

Atenção!

        Você realmente deseja excluir o usuário:
        <?php
        echo $_GET["nome"];
        echo'
';
        echo ' Não';
        echo ' <input type="submit" class="btn btn-danger" value="SIM">';
    ?>
    </form>

<?php
 if(isset($_GET["acao"]) and $_GET["acao"] == "deletarConcluido") {

    $idEndereco = $_GET["id_endereco"];
    $idPessoa = $_GET["id"];

    //Deletar email
    $emailDao = new EmailDao();
    $emailDao->deleteEmail($idPessoa);

    //deletar telefone
    $telefoneDao = new TelefoneDao();
    $telefoneDao->deleteTelefone($idPessoa);

    //Deletar usuario
    $usuarioDao = new UsuarioDao();
    $usuarioDao->deletePessoa($idPessoa);

    //Deletar endereço
    $enderecoDao = new EnderecoDao();
    $enderecoDao->deleteEndereco($idEndereco);
}
}

Comment: Creio que o problema seja a logica, e não o form. Descreva melhor o caso.
Comment: Coloca um hidden field no form.
Comment: o problema é que são dois forms diferentes, ou seja em um eu tenho uma tabela, e no outro apenas dois botões, se eu passar uma variavel nesse outro ele perde os valores anteriores, é a mistureba do php sem framework parece servelet.
Comment: Confesso que não entendi muito bem, mas porque perderia o valor se adicionar um hidden field? Estaria apenas acrescentado. Você pode executar apenas um form por vez, então se acrescentar o hidden no form que será executado, não vejo problema. Mas edite a pergunta e coloque esses forms pra eu poder entender melhor.
Comment: Fazer uma confirmação de exclusão para um trabalho mais adequado para javascript do php, poste o código dos dois forms.
Comment: o problema é que teria que submeter o outro formulário, acredito que se gerasse uma variável em javascript e passasse a mesma poderia dar certo
Comment: testei coloca no form do controller assim mas não deu certo
Comment: Só nao entendi porque você nao cria o botao deletar dentro deste formulario? Ai ao invez de você usar o get voce usa o post
Comment: @Andrei Coelho a funcionalidade do delete está ok, o que estou precisando é fazer uma confirmação neste form para realmente o usuário que quiser deletar fazer isso ou simplesmente desistir e não fazer isso.
Comment: Entendi. Acho que com javascript resolve. Coloquei a tag javascript nas tags para ver se aparece um profissional nesta linguagem
Comment: @rray acabei de postar o código, alguma sugestão?
Comment: Esse form é para criar um registro e excluir? ele será usado para fazer alterações tbm?
Answer: Voce pode fazer dessa forma:

Atenção!

        Você realmente deseja excluir o usuário:
        <?php
        echo $_GET["nome"];
        echo'
';
        ?>

        Não
        <a class="btn btn-primary" href="index.php?pagina=../controller/controllerUser&acao=deletarConcluido&id_endereco=<?php echo $id_endereco; ?>&id=<?php echo $id_pessoa; ?>">Sim

Poste o resultado e nós iremos melhorando se precisar.
Atualização:
Dessa forma você não precisa gerar aquele form em php, a página nem vai precisar ser recarregada para gerar a confirmação:

<a href="javascript:confirmarDelete('index.php?pagina=../controller/controllerUser&acao=deletarConcluido&id_endereco=<?php echo $id_endereco; ?>&id=<?php echo $id_pessoa; ?>')">Deletar

Lembrando que essa é uma forma básica de fazer, existem jeitos mais avançados e mais personalizados, mas isso já vai te dar uma boa base para iniciar.
Comment: sim já tinha tentado dessa forma, passa os parametros tranquilamente novamente, até tinha colocado em um comentário anterior, agora não sei por que ele não entra na verificação se existe a variável if(isset($_GET['acao'])) { faça algo.... mesmo mostrando a acao na url ele não está entrando nessa condição.
Answer: @Diego Machado ocorreu tudo bem só coloquei no form as variáveis pois o sistema está quase todo dessa forma então ficou da seguinte forma:

    <form action="index.php?pagina=../controller/controllerUser&novaAcao=deletarConcluido&id_endereco=<?php echo $idEndereco; ?>&id=<?php echo $idPessoa;?>" method="POST" enctype="multipart/form-data">

Atenção!

        Você realmente deseja excluir o usuário:
        <?php
            echo $_GET["nome"];
            echo'
';
            echo ' Não';
            echo '<input type="submit" value="Sim" class="btn btn-primary" >';
        ?>
    </form>

Dúvidas que ficaram:
1) essa é a forma mais correta de fazer?
2) essa forma está correta?
Comment: Vou ser sincero, não acho essa uma forma eficiente. Acaba complicando seu código. Provavelmente você deve ter uma lista com botões para deletar, que quando clicados levam para essa página, certo? Todos os dados deveriam estar no link, como mostrei. A confirmação deveria vir através de um javascript, veja esse exemplo simples: http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm
Dessa forma a página não precisa ser carregada, e você não precisa criar um formulário para confirmar. Você vai apenas redirecionar. Vou montar um exemplo depois para você.


GCP Stackdriver log event for failed API attempts due to insufficient access scopes

Question: I would like to monitor for Compute Engine service accounts that attempt API calls beyond their given Access Scope. This could be via the gcloud command or manual API interaction using the OAuth token from the metadata server.
Here is a specific example:

A Compute Instance is launched with the general GCP defaults, including the default service account and the default access scopes.
A user logs into a SSH session on that Compute Instance and gcloud auth list shows that the active account is the default service account.
The user runs gcloud compute instances list. This fails with Insufficient Permission: Request had insufficient authentication scopes due to the Access Scope limitation.

However, I can't find anything in StackDriver that relates to this attempt. I've configured Cloud Audit Logs for Admin Read, Data Read, and Data Write for all services.
I do see log events for successful API calls, for example if I remove the scope limitation and repeat the steps above.
I also see log events for failed API calls that had a proper access scope but lacked IAM permissions.
However, nothing for attempts that fail specifically due to access scope.
Does anyone know if this is possible?
Answer: It's possible. Using advanced logs queries. Go to Logging > Logs Viewer and use this query:
resource.type="api" to match the corresponding resource type.
Even though the information above is accurate is not related to your case. It was indeed a misunderstanding.
UPDATE:
I believe that if the user doesn't have permissions to execute gsutil command due to the scope limitation, the command will fail at a system level and that message won't be recorded (e.g. try running tail /var/log/auth.log with a regular user and find a record of that call). As stated here only specific information will be stored.
It might be a good idea using Anomaly Detection instead. Hope this help.
Comment: Thank you for the reply. However, this does not seem to discover any log entries of attempts to use a service account's OAuth token without proper access scope.
Example: Create a compute instance with default service account. SSH into instance and run `gcloud compute instances list`. Receive error `Request had insufficient authentication scopes`.
Nothing in Stackdriver.
Comment: I'd suggest you to find out [what roles does this service account has](https://cloud.google.com/iam/docs/granting-roles-to-service-accounts#viewing-roles). I think the problem is there.
Comment: You can also be more specific and execute:
`resource.type="api"
protoPayload.serviceName="compute.googleapis.com"
protoPayload.authorizationInfo.resourceAttributes.name="projects/some-project-name"`
Comment: Thanks for the replies, but I'm not sure we are on the same page here.

My comment is that API commands that specifically fail due to access scope limitations due not appear to add any entries to cloud audit logs.

There is no issue with the roles assigned to the account. The access scope limitations are intentional. We are looking to monitor for accounts that have been compromised and an attacker is attempting to access APIs that are blocked by the OAuth token's access scope.
Comment: I see. Well I ran this query `"google-cloud-sdk gcloud"
protoPayload.status.message="PERMISSION_DENIED"` and I was able to get that information. The first part will look for all the calls made to the API through the Cloud Shell and the second part for PERMISSION_DENIED error messages.
Comment: I do see PERMISSION_DENIED for calls that fail due to IAM permissions lacking, but not due to access scope limitations.

Access Scopes do not apply to a session in Cloud Shell, so you cannot test it that way. They apply only to OAuth tokens assigned to Compute Instances. You need to run the gcloud command from inside a compute instance using the assigned service account and access scope (not by activating a service account key file, which would negate the scope).

A specific scenario for this is outline in my original post.
Comment: I also do not think this is a log filtering issue. I can clear all filters, listing everything, and literally see 0 log activity when I reproduce the failure.

By the way, thank your for your replies - they are appreciated, but just working to make sure we are talking about the same thing.

https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam
Comment: Please see new UPDATE ^
Comment: Thanks. As state in my original post, I have already enabled cloud audit logging. I still see no log entries created for failures that occur due to access scopes.

Are you absolutely sure the failure you are seeing is access scope related? Are you able to share a redacted version of the log entry?
Comment: What I found was a log entry (INFO) in the logs with the executed command nothing more. See UPDATE.
Comment: Thanks mate. Yep, it looks like this simply is not logged.


Behaviour of set-intersection of objects

Question: I stumbled upon this uncertainty in one of my programs:
Suppose we have a Class deriving from int with a custom attribute.
class A(int):
    def __new__(cls, value, *args, **kwargs):
        return super(cls, cls).__new__(cls, value)

    def __init__(self, _, a):
        self.a = a

Objects of this class are now used in a Set.
set1 = {A(2, 5), A(3, 2)}
set2 = {A(3, 7), A(5, 5)}

How would I now know the output of the following operations?
x, = set1 & set2
print(x.a)

x, = set2 & set1
print(x.a)

x, = set1.intersection(set2)
print(x.a)
...

It appeared to me in various tests that the result is rather random, could somebody explain this behaviour?
Thank you in advance :)
Comment: @Raumschifffan: No, it's not, it will *always* be implementation-dependent. You said the two were equivalent, so Python assumes it doesn't matter which one wins. That's on you. You can do dumb stuff with a `dict` that performs a self-mapping (key and value are the same), so you can extract what is mapped to and choose whether or not to replace it, but it's a terrible brittle idea. If the rest of the value matters, make it part of the equality check.
Comment: You inherited from `int` without overloading the `__hash__` or `__eq__` methods. Which means you're saying all `A`s with the same *first* argument are equivalent, regardless of what the other arguments might be. It doesn't matter which object survives; you said they were all equivalent, so which object is picked as the survivor is an irrelevant implementation detail. If you cared, you'd define hashing and equality properly.
Comment: Also, `return super(cls, cls).__new__(cls, value)` is *wrong* (terrible things will happen if you inherit from this class). Just use `return super().__new__(cls, value)` and let Python do the right thing for you.
Comment: What exactly struggles you? Why changing the order changes the result? Or why it prints what it prints?
Comment: I discovered inconsistencies in the result, with sometimes having the same object on `a & b` as well as `b & a` returned. I guess I'd like to know how intersection works!
Comment: oh, so you say that the result is non deterministic? Are you sure? If so, it struggles me too :o
Comment: I'd say so, yes! Could be a bug on my side, but fairly confident it is.
Comment: @ShadowRanger Follow-up-question. Is it possible to define the survivor? `__eq__` only seems to affect set-intersection in a sense that they are tested for equality.
Answer: You intrigued me so much that I looked into source code and it became quite logical. We looped over smaller set and search every element in bigger one. When both sets has equal size, the order matters (that's why you get different results in your case), otherwise the elements taken will always belong to smaller set.


Computing the gradient knowing directional derivatives

Question: Suppose that the directional derivatives of f(x, y) are known at a given point in two nonparallel directions given by unit vectors u and v. Is it possible to find ∇f at this point?
I would like to know if the following is a valid way to solve this:
I was thinking of computing the tangent plane(assuming f is differentiable, which I believe is assumed in the problem) to the given point. Since the the tangent lines to the function in the direction of u and v must be contained in the plane, could I just take the cross product of
(u1,u2,directional derivative in the direction of u) x  (v1,v2,directional derivative in the direction of v)
and the resulting normal vector will be (a,b,c)
where
a= partial derivative with respect to x
b= partial derivative with respect to y
c = -1
Finally, the gradient would be --> (a,b)
Maybe, this is totally wrong, but I was trying to come up with a solution where the tangent plane was involved.
Thanks for your help!
Answer: Just solve the linear system of equation
\begin{align}
a=\mathbf{u}\cdot \nabla f = f_x(a, b)u_x+f_y(a, b)u_y\\
b=\mathbf{v}\cdot \nabla f = f_x(a, b)v_x + f_y(a, b) u_y
\end{align}
where you know $a, b, \mathbf{u}$ and $\mathbf{v}$. That is
\begin{align}
\nabla f = [\mathbf{u}, \mathbf{v}]^{-1}
\begin{bmatrix}
a\\
b
\end{bmatrix}.
\end{align}
Comment: Thanks. They had told me about this way already, but I was just wondering if there was any other alternative way, different to this one. Could you help me on that? Thank you!


Sql to select the maximum datetime row keeping values from another row

Question: I've got the next table (call it alarm_issues).

idal | idaction | dt
---- | -------- | -------------------
5    |        6 | 2016-09-23 15:02:50
5    |        7 | 2016-09-23 16:00:00
5151 |        7 | 2016-09-01 00:00:00
5151 |        6 | 2016-12-01 15:35:34

But I need to get the next table from the last:

idal | idaction | dt
---- | -------- | -------------------
5    |        7 | 2016-09-23 16:00:00
5151 |        6 | 2016-12-01 15:35:34

This means that I want "For each group of rows by idal value, I want only the most recent row by keeping tyhe idaction value". I've tried some things, but never works, because the idaction value it loses and mixes with the other (when you group by idaction field).
Answer: Here is one method:
select ai.*
from alarm_issues ai
where ai.dt = (select max(ai2.dt)
               from alarm_issues ai2
               where ai2.idal = ai.idal
              );

This uses a correlated subquery to choose the row, for each idal that has the maximum value of dt.
Here is another method:
select ai.*
from (select ai.*,
             (@rn := if(@i = @idal, @rn + 1,
                        if(@i := @idal, 1, 1)
                       )
             ) as rn
      from alarm_issues ai cross join
           (select @rn := 0, @i = 0) params
      order by idal, dt desc
     ) ai
where rn = 1;

Comment: Thanks, it's seems it works fine! Unfortunately, my "alarm_issues" table is a generated query and this final sql is pretty longer than yours, but it works!
Answer: try this
select t1.* from alarm_issues as t1 inner join
(
select idal,max(dt) as dt from alarm_issues group by idal
) as t2 on t1.idal=t2.idal and t1.dt=t2.dt


Residue theorem: understood it intuitively but cannot prove mathematically

Question: In my opinion, residue theorem's underlying principle is quite beautiful: one decomposes a contour integral into infinitely many small circular contour integrals around every point, and most of them are zero, except a few that encircle singularities. Those are called residues, and add them up. This is basically how residue theorem works.
However, when I try to prove it by Green's theorem, I face some difficulties. ($f=u+iv$)
$$\oint_C f(z)dz=\oint(u+iv)dx+i(u+iv)dy=\iint_D \frac{\partial (u+iv)}{\partial x}-i\frac{\partial (u+iv)}{\partial y}dxdy$$
I don't see how can this be transformed into a sum of residues/circular contour integrals around singularities.
Can you please show how?
Thanks in advance.
Answer: You are given a region $\Omega\subset{\mathbb C}$ with boundary cycle $\partial\Omega$ and a function $f:\>\Omega\to{\mathbb C}$ which is analytic apart from finitely many isolated singularities at the points $a_j\in\Omega$ $(1\leq j\leq m)$. The trick now is to draw tiny discs $B_j$ of radius $\epsilon>0$ centered at these points. Then we consider the punched domain $\Omega':=\Omega\setminus\bigcup_{j=1}^m B_j$ with boundary cycle
$$\partial\Omega'=\partial\Omega-\sum_{j=1}^m \partial B_j\ .$$
Note  the minus signs here! The function $f$ is analytic in $\Omega'$; therefore we may apply Green's, resp., Cauchy's,  theorem to $f$ and $\Omega'$. It follows that $\int_{\partial\Omega'}f(z)\>dz=0$, so that
$$\int_{\partial\Omega}f(z)\>dz=\sum_{j=1}^m\int_{\partial B_j}f(z)\>dz\ .$$
Here the LHS is independent of $\epsilon$. It follows that
$$\int_{\partial\Omega}f(z)\>dz=\sum_{j=1}^m\lim_{\epsilon\to0}\int_{\partial B_j}f(z)\>dz=2\pi i \sum_{j=1}^m{\rm res}(f, a_j)\ ,$$
by definition of the residue.
Comment: This is brilliant. Just one thing: how can I derive with details and rigor that $$\int_{\partial\Omega+\partial B}=\int_{\partial\Omega}+\int_{\partial B}$$ to 'convince' a starter in complex analysis? (I know this is almost trivial to you.)
Comment: Also, to my surprise, I cannot google a similar proof. Indeed, a formal proof of residue theorem is quite rare on the internet.
Comment: Already $\partial\Omega$ might consist of several disjoint closed curves. If you accept the  notion of boundary cycle as defined in your community, as well as the notion of integral over a chain (formal sum of smooth curves) then there is no problem with $\partial\Omega'=\partial\Omega-\sum_j\partial B_j$.


Markov Chain Reversibility and Stationary Distribution

Question: A librarian has three books, labelled $i$ =1,2,3. Everyday, the librarian picks a book i with probability $p_i$ (regardless of where it is on the shelf). By the end of the day, they return it to the shelf one position to the left of where it was previously (unless it was already the leftmost book, in which case it is put back where it was).
(a)Make Xn be the order of the books at the beginning of day n (before a book is selected that day). Show that (Xn,n≥0) is a reversible Markov chain with equilibrium distribution $\pi_{ijk}$ proportional to $p^2_i p_j$.
(b)Suppose that $p_i$ = i/6 and initially the books are in order 123.  Find the expected amount of days until the books are again in this order
Comment: Please indicate what you have tried. part (a) should be clear if you review the definition of reversibility. For part (b) you can use a general formula for the expected return time to a state in aMarkov chain. Also, please render questions on this site using mathjax: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: sorry would you mind explaining what you mean by part a) should be clear by the definition of reversibility. How do prove it?
Comment: The definition of reversibility requires $\pi(x) p(x,y)=\pi(y)p(y,x)$ to hold for all states $x,y$. Now just check this with the proposed equilibrium measure and the given transition rule.
Comment: so for example go from 123 to 213, when i check the reversibility condition it doesn't hold
Comment: It does hold- see my answer below
Answer: To check the reversibility condition $\pi(x)P(x,y)=\pi(y)P(y,x)$ there are just two types of transitions to consider: Swapping the first two books, and swapping the last two:
$$\pi_{ijk} \, P(ijk \,,\, jik) =(Cp_i^2 p_j)\, p_j=(Cp_j^2 p_i)\, p_i=\pi_{jik} \,P(jik \,,\, ijk) $$
$$\pi_{ijk} \,   P(ijk \,,\, ikj)=(Cp_i^2 p_j)\, p_k=(Cp_i^2 p_k)\, p_j=\pi_{ikj} \, P(ikj \,,\, ijk)$$
Comment: Thank you that was very helpful. Can you perhaps explain how you arrived at the stationary distribution?
Comment: $\pi$ was given in the question. If it was not given, you could obtain it e.g. by solving the linear equations in the definition of reversibility together with the constraint that the total sum equals $1$.


Do JavaScript engines have any specific optimizations for classes?

Question: I want to document the differences between classes and closures in JavaScript. Both class-based, object-oriented and functional JavaScript exist in the wild. For example in React, both class components and function components with hooks are supported.
I don't want to assert that you would ever choose one programming paradigm over another purely based on their performance, but is it possible that in modern JavaScript engines classes have a better chance to be optimized due to their language support?

I was under the impression that classes were just syntactic sugar for inheritance implemented with a prototype chain, but while this still appears to be a popular point of view, it is not correct.
In addition, their are new proposals such as decorators and private fields which continue to put more distance between classes and their alternatives. While decorators are just the composition of higher-order functions and private fields can be emulated, I expect that JavaScript engines may not perform identical optimization in all cases.
I am also aware that JavaScript engines employ techniques such as hidden classes to improve their performance. To my knowledge this optimization is not class specific. However, this made me curious...
Are their any optimizations that current JavaScript engines perform on classes, that are may not be applied in cases where classes are avoided? Would their be invariants that might be easier to identify and exploit due to the consistent nature of the class-based syntax?

I did try to read through the source code of the V8 engine, but it is large and complex, and I expect would take me a significant amount of time before I could even create a hypothesis. Therefore, I think this question is better left to someone with more experience than me in this domain.
So far my quest has led me from the parser to the abstract syntax tree and then to the bytecode generator used by the interpreter. I am aware that the interpreter (Ignition) is just the first stage of the JIT, and is followed by the compilers Sparkplug and Turbofan, which then transform the bytecode into machine code.
Indeed, classes do appear to have specific bytecode generation as seen in the BuildClassLiteral in the BytecodeGenerator class. However, I am unaware if this could yield better performance further into the pipeline of compilers.
Comment: Do you have more examples than React? According to my experience, React is the exception and not the norm. Angular and Aurelia use classes. Vuejs uses objects. React has function components and class components. I wouldn't say that **a lot of** modern libraries avoid classes and therefore this isn't an indicator for bad performance with classes.
Comment: The question wasn't aimed in particular at React, but rather the idea of avoiding object-oriented in JavaScript. I also implied the opposite, that classes might perform *better* due to their popularity. Without being exhaustive, there are definitely many libraries that are built without classes such as [`tinybase`](https://github.com/tinyplex/tinybase), [`jotai`](https://github.com/pmndrs/jotai) and [`zustand`](https://github.com/pmndrs/zustand). New frameworks such as [`solid`](https://github.com/pmndrs/zustand) and [`qwik`](https://qwik.builder.io/) also make some effort to avoid classes.
Comment: I understand that the question wasn't aimed at React, but your premise is based on React and I think your premise is wrong. Yes, not all modern libraries use classes, but they don't try to deliberately avoid them. Sometimes other design pattern fit better. Some developers don't like OOP and some even think it's an anti pattern. Some developers prefer functional programming. I don't think performance is the reason for this choice.
Comment: @jabaa: No. My premise was not to imply that performance was the reason for this choice. Nor to imply that these you should prefer one programming paradigm over another. I just wanted to establish that both OOP and non-OOP code exist and are popular. Then, is it possible that modern JavaScript engines have additional optimizations for classes due to their more rigid definition and syntactical support? What conclusion you draw from the answer to this question is up to you.
Comment: @AndyPreston: As I discuss in the question. This is not correct, while mostly syntactic sugar, JavaScript classes are [more than just syntactical sugar](https://stackoverflow.com/questions/36419713/are-es6-classes-just-syntactic-sugar-for-the-prototypal-pattern-in-javascript). In addition, as I discussed, the bytecode generated for JavaScript classes is unique: [BytecodeGenerator::BuildClassLiteral](https://github.com/v8/v8/blob/3b36641300ca404a214548a62f4dc130f3a0c2c6/src/interpreter/bytecode-generator.cc#L2743).
Answer: (V8 developer here.)
I think this can largely be answered with "no", but the question is rather broad.
One issue is that I'm not sure what you're comparing. Are you comparing classes to non-class-based (e.g. pre-ES6) OOP, or to some definition of "functional programming" that avoids using objects entirely? If the latter, then the the answer is both trivial (yes, engines have lots and lots of optimizations that deal with objects and hence are only applicable to objects) and useless (because that doesn't say anything about whether using objects or not using objects will be faster overall).
Comparing classes to class-avoiding OOP, there isn't a big difference in optimization potential, because classes don't provide additional guarantees or invariants. For example, you can still add and remove properties of class instances, you can change which prototype they point at, and what fields and methods are present on that prototype. Locking down these things might give more optimization opportunity, or at least would make existing optimizations more reliable and less speculative, but that's not what classes do today. As it stands, JavaScript classes are mostly for the benefit of JS programmers, not for the benefit of JS engines. If they affect JS performance, then that's probably mostly by making a few particularly inefficient coding patterns less likely (such as installing methods as fields in the constructor).
"Is it possible...?", sure, everything is possible. I'm not aware of an example, but that doesn't mean that there isn't or can't ever be one: as you note, the V8 source code is large and complex, and I'm far from knowing all of it in detail. I could try to make a few guesses and toy around with some examples, but even if I managed to find some artificially crafted case where class-based code is optimized better than some non-class-based alternative, would that really help you?

As a general note, keep in mind that "optimization" isn't something binary, in the sense that the situation is far more nuanced than "feature X is optimized, feature Y is not". To make an analogy: when cleaning up your house, there are clearly many more states than "this room is cleaned up" and "this room is not cleaned up". Even a statement like "I've spent the entire day cleaning up the kitchen" doesn't imply that the kitchen is the best-cleaned-up room now: maybe it was such a mess to begin with that it's still less clean than the bedroom, even though nobody has been working on the latter today. The existence of kitchen-specific clean-up techniques (such as running the dishwasher) doesn't imply that kitchens have a general tendency to be cleaner than other types of rooms. And also, there's always something more that one could do, if only there was a little more time left in the day...
Comment: Awesome, thank you so much for your answer! Yes, you're right the comparison should be about the difference between classes and non-classes that are still prototypical OOP (such as pre-ES6), not "functional programming".
Comment: This isn't really a specific question... As you addressed, the difference in optimization of classes and closures is far much more distinct, and also more important in my opinion. For example, both classes and closures can have private fields, but they accomplish this in different ways. I guess a good first step would be to create a good set of benchmarks and test cases to highlight these differences. Then, this would yield some conclusions, but also many more questions that could be discussed.
Comment: Some questions that I think I can answer, that might be interesting to ponder?

Q: Due to the class syntax being more concise than pre-ES6 OOP, it would result in smaller JavaScript bundles and thus parse time should be reduced. A: Yes? But, the performance impact is most likely negligible.

Q: Private fields (which are unique to classes), may provide future potential for optimization, that would separate them from pre-ES6 OOP.  A: Yes? Of course possible, but as you mention, there is only so much time in the day to implement these optimizations.
Comment: @scottwillmoore Private fields are a great example of a feature that helps JS developers but not engines. I'm not aware of any optimization that would be enabled by having private fields.