How can I get the value of the only field of a field in a json with json.net in a C# class

Question: I would like this json :
{
  "foo ": {
    "bar": 5
  }
}

To be deserialized in this class :
class MyClass
{
 int foo;
}

Like this :
void MyFunction(string _JSON)
{
    string json = _JSON;
    //json == {"foo ": {"bar": 5}}
    MyClass c = JsonConvert.Deserialized<MyClass>(json);
    //c.foo == 5
}

Comment: Why not just match the class structure to the JSON structure?
Answer: As @DavidG mentioned, match the class structure and you can easily get the value you want. You could go to the point of using this site to help you: https://json2csharp.com
The site will give you the c# class structure of:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>
(myJsonResponse);

public class Foo
{
    public int bar { get; set; }
}

public class Root
{
    [JsonProperty("foo ")]
    public Foo Foo { get; set; }
}

Answer: You can get value from a specific field from JSON by JObject like this:
void MyFunction(string _JSON)
{
    JToken jobject =  JObject.Parse(_JSON);
    MyClass c = new MyClass()
    {
        foo = Convert.ToInt32(jobject["foo"]["bar"].ToString())
    };
}

Answer: Deserialize it into a matching structure:
class MyJsonClass
{
    public MyJsonFoo foo { get; set; }
}

class MyJsonFoo
{
    public int bar { get; set; }
}

// and later...
var temp = JsonConvert.Deserialized<MyJsonClass>(json);

And then use that object to create your object:
var c = new MyClass { foo = temp.foo.bar };

Essentially what you have is an external dependency (an incoming JSON structure) which doesn't match your internal domain (MyClass).  Abstract that dependency behind a service (class, project, however complex it needs to be) which internally deserializes the result and returns the domain object.  That way MyJsonClass and MyJsonFoo can be encapsulated within that service and not pollute the domain.  The service is essentially just a translation layer between the two data structures.


SQLite - Store a list of files in a single table cell

Question: I'm making a Java web application where users can upload multiple text documents and I'm wondering about the best way use a database to display a particular user's uploaded documents.
So far, I've thought of a few ways, but none seem like a good solution.
Solution 1:
Keep an 'uploads' table alongside the 'users' table and then query it with something like:
<code>"SELECT * FROM uploads WHERE USER_ID = "+id+";".
</code>
Solution 2:
Add an uploads column to my 'users' table and store all the user's uploads as a string that I can crudely parse as a list:
<code>"SELECT uploads FROM users WHERE USER_ID = "+id+";"
</code>
could return a string: "upload1.txt,upload2.txt,upload3.txt"
Solution 3:
Skip the database entirely for the uploaded files and prepend USER_ID to the front of the file name:
<code>"<some user id>_upload1.txt"
</code>
It seems all three of these have pretty substantial drawbacks, so I'm pretty sure none of them are correct. I've only been teaching myself about databases for the past few days, so I'm sure there is a preferred way of doing it that I don't know about yet, but I can't figure out what it might be.
Answer: Solution 1 is best in my eyes. Good normalization and flexibility.


How can we export the full copy of PRODUCT with all the API's associated to it

Question: Is there a way by exporting the PRODUCT it gives the full definition of it including the with API's and policies associated with that PRODUCT.
That way i can make only two calls to export the complete product and import the complete product somewhere else.
Is there any other best practices to minimize below number of calls to export and import

Make GET call(s) to REST Management API to export the different API's from one subscription.
Make GET call(s) to REST Management API to export the policies from API's. (Unfortunately,  Exporting API's will not export policies associated with it).
Make PUT call(s) to REST Management API to import the different API's to another subscription.
Make PUT call(s) to REST Management API to set the policies associated to API's.
Make GET call(s) to REST Management API to export the different Product's from one subscription.
Make GET call(s) to REST Management API to get the list  of API's associated with PRODUCT.
Make PUT call(s) to REST Management API to create the Product in another subscription.
Make PUT call(s) to REST Management API to add the API's to Product.
Comment: What is the "PRODUCT"?
Comment: The product is the "group" to which an api can be added, there is a starter and an unlimited product default in api management, each product can have different policies
Comment: A product contains one or more APIs.
For example Starter and unlimited are the PRODUCTS that come with the initial subscription.
Answer: Well if you just want to clone your second service with the first one, you can use backup restore
https://azure.microsoft.com/en-us/documentation/articles/api-management-howto-disaster-recovery-backup-restore/
What it does essentially is copy all your metadata (Apis/Products/Subscriptions) to another service.
Or
You can create scripts to export your apis using the Azure Powershell commandlets
https://msdn.microsoft.com/en-us/library/mt613477.aspx
and then add it to the second service using the Import commandlets
https://msdn.microsoft.com/en-us/library/mt613484.aspx
Comment: Instead of using the PowerShell commandlets... can i use the custom tool to call REST management API to perform same.

Is that Recommended? any PROS or CONS
Comment: @Srav yes you can use a custom tool to call API via REST. Only CON I think of is how to refresh the shared access token that we generate for you.
Comment: Can't i use the approach stated to programatically create access token
https://msdn.microsoft.com/en-us/library/azure/dn798668.aspx#ProgrammaticallyCreateToken

Thank you for your help!
Comment: FWIW, I had the same question and ended up writing a bash shell script to perform a bunch of curl commands to do this. For me, shell scripts are more portable since half of my team is on Mac and half on Windows.
Answer: NO Recommendation or any other way to reduce the above effort at this time.
Comment: Have you tried using GIT to move the Api Configuration between instances.  [link](https://azure.microsoft.com/en-us/documentation/articles/api-management-configuration-repository-git/)


Cartesian product (complexity amelioration)

Question: I want to write a function that gives the cartesiant product of two sequences that's what i did but i thought that it can be interesting to have less complexity with I want to browsing once the first sequence s1 and n times the second using map and then append all the results:
`let cartesian_product a b =
    let na = length a in
    let nb = length b in
    init
    (na * nb)
    (fun j -> let i = j / nb in
      at a i, at b (j - i*nb))
`

that's what i did for the moment :
`let rec cartesian_product a b =
 let rec aux x b () = match b () with
  | Nil -> Nil
  | Cons(e, b) -> Cons ((x, e), aux x b)
 in
 match a () with
 | Nil -> nil
 | Cons (x, a)  -> append (aux x b) (cartesian_product a b)`

but i didn't use map (is there a better way for doing that)??
Comment: with an example : cartesian [0;1] [2;3] will yield [(0,2);(0,3);(1,2);(1;3)] . Is it the expected result ?
Comment: yes exactly here i am using sequences not lists but it's the same manipulation
Answer: Your aux function is essentially a specific case of map so you can write:
let rec cartesian_product a b = match a () with
  | Nil -> Nil
  | Cons (x, a)  -> append (map (fun e -> (x, e)) b) (cartesian_product a b)

As a rule of thumb when you feel the need to write a function called aux, take a step back and think whether you can use map or fold. In fact, you could improve my code by using a fold instead of deconstructing the sequence yourself.
Answer: Here an example of the algorithm with a structure of list :
let cartesian_product a b =
  let open List in
  let mk_tuple l n = map (fun x -> (n,x)) l in
   a |> map (mk_tuple b) |> fold_left append []

This will give you :
    cartesian_product [0;1] [2;3];;
    - : (int * int) list = [(0, 2); (0, 3); (1, 2); (1, 3)]


Exportar módulos no angular 8

Question: Estou tentando exportar um módulo com seus components para usar no app-module, porém estou tendo o seguinte erro ao abrir:
'app-AmbevComponent' is not a known element:
1. If 'app-AmbevComponent' is an Angular component, then verify that it is         part of this module.
2. If 'app-AmbevComponent' is a Web Component then add     'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress     this message. ("

Criei um módulo e dentro deste módulo criei um component, coloquei este mesmo component para ser exportado e importei o módulo no app-module.
No module exportei o component:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AmbevModuleComponent } from './AmbevModule.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule
  ],
  declarations: [AmbevModuleComponent],
  exports: [AmbevModuleComponent] <- exportei aqui
})
export class AmbevModuleModule { }

Meu compoment:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-AmbevComponent',
  templateUrl: './AmbevComponent.component.html',
  styleUrls: ['./AmbevComponent.component.css']
})
export class AmbevComponentComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

e o app.module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { ModalModule } from 'ngx-bootstrap/modal';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { AmbevModuleModule } from './AmbevModule/AmbevModule.module';

@NgModule({
   declarations: [
      AppComponent,
      NavComponent
   ],
       imports: [
      BrowserModule,
      BrowserAnimationsModule,
      BsDropdownModule.forRoot(),
      TooltipModule.forRoot(),
      ModalModule.forRoot(),
      AppRoutingModule,
      HttpClientModule,
      FormsModule,
      ReactiveFormsModule,
      AmbevModuleModule <- importei aqui
   ],
   providers: [],
   bootstrap: [
      AppComponent
   ]
})
export class AppModule { }

Coloquei no app.component.html a seguinte tag
<app-AmbevComponent></app-AmbevComponent>

Answer: O problema é que você declarou e exportou o próprio módulo AmbevModuleModule. Basta ajustar o declarations e o exports para o componente AmbevComponentComponent:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AmbevModuleComponent } from './AmbevModule.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule
  ],
  declarations: [AmbevComponentComponent ], // <- Correção
  exports: [AmbevComponentComponent ] // <- Correção
})
export class AmbevModuleModule { }

Comment: Marcelo, obrigado pela resposta, no caso eu declarei o component dentro do module e exportei o mesmo component, não está certo? Declarei o component e exportei ele dentro do module. No caso, o nome está como AmbevModuleComponent pois foi criado dentro de um diretório chamado AmbevModule.
Comment: @RonaldoAlves segundo seu post dentro do `AmbevModuleModule` foi declarado e exportado o próprio módulo `AmbevModuleComponent`. Por esta razão seu componente não foi exportado. Basta alterar onde deixei indicado para que seu componente, `AmbevComponentComponent`, seja declarado dentro do módulo e exportado.
Comment: Resolvido, valeu.

Exportar módulos no angular 8


Codeigniter DB escape and like

Question: I use CI 3, and I have a problem using escape and like clause. Here is my code :
$where = '(a.title LIKE \'%'. $this->db->escape($name) .'%\' OR agi.senior_artist LIKE \'%'. $this->db->escape($name) .'%\')'

The problem is $this->db->espace add quotes to the string, so I got an error. It works without the escape, and only $name but I prefer to espace the data.
Is there a native solution ?
Answer: You need to use
$this->db->escape_like_str()

instead
$this->db->escape()

when you use LIKE conditions
Read more
Comment: Oh nice ! I missed it in doc. Thanks !

Codeigniter DB escape and like


Why use infimum in definition of Quantile function?

Question: This question was already asked here (I don't know if I should just bump that question instead of creating my own or how should I do it. If I did something wrong, I'm sorry.).
The Quantile function is defined as follows:
$$Q(p)=\inf\{x\in \mathbb{R}:p\leq F(x)\}, \hspace{.1cm} 0<p<1$$
But I don't really see an example of a distribution function for which $\inf$ can't be replaced with $\min$, because CDF is necessarily a right continuous function.
And I don't think this answer is correct, because CDF is always defined on $\mathbb{R}$, it shouldn't matter what values the random variable obtains.
Answer: Because $F$ is right-continuous and nondecreasing, the superlevel sets of $F$ are of the form $[a,\infty)$ where $a>-\infty$ or else the entire line. When the superlevel set is the whole line, there is no min (among the reals), while the inf is $-\infty$. For $a=+\infty$ the superlevel set is empty and so the inf is $+\infty$. These cases can potentially arise when $p=0$ or $p=1$ respectively; for $p \in (0,1)$ one can indeed replace the $\inf$ with $\min$.
Comment: @JesperHybel Sure. I added a sentence clarifying this matter.
Comment: If we define $A(r) :=\{x\lvert Pr(X\leq x) \geq r\}$ does that then mean that for $r \in (0,1)$ open interval the inf could be changed to min?
Comment: thx for the quick reply. That is helpful.


Avisar quando o arquivo for alterado utilizando PHP ou JavaScript

Question: Tenho um formulário que salva os dados em um arquivo .txt. Gostaria de saber se tem como criar um aviso para saber quando um novo conteúdo for registrado nesse .txt através do PHP.
Answer: O que voce pode fazer é usar um Cron do Linux e seta-lo para rodar a cada x minutos ou segundos e ai voce fica verificando o arquivo. Voce pode fazer isso manualmente ou utilizar algum componente como esse:
https://github.com/peppeocchi/php-cron-scheduler
OU
Caso esse txt seja editado por algum outro programa, voce pode criar uma API com o PHP onde o programa que editou o txt envia uma mensagem dizendo que editou o file.


K-Fold cross validation for multi class

Question: Let say I have train set of categories $C_1,\ldots,C_s$. Each category has different size. I want to divide the data to 10 subsets, each one is 10% of the train set and then perform 10 rounds of leaving out one subset for test and train on the other 9 subsets. (I.e. I want to perform 10-fold CV).
Now, there are two methods for dividing the data to 10 subsets of 10% (the categories are of different sizes):

Divide randomly each category to 10 subsets of 10% and than each of the subsets for the 10-fold is concatenation of one subset from each category.
Divide the data randomly to 10 subsets of 10% withot considering the different categories.

The main difference is that in method 1 every subset of the 10-fold has same distribution in terms of num of examples from each category and the distribution corresponds to the sizes of $C_1,\ldots,C_s$.
The question is which methos is better /more correct?
Also, which methos usally used?
Answer: Making sure that the splits have (roughly) equal relative frequencies of each class is a form of stratification, so you're asking whether to do stratified resampling or not.
Practically relevant differences between the two approaches will occur only for data where at least some class has very few cases.
In such small-sample-size situations the answer is as usual: it depends. You need to think what it means in terms of your application and study and then decide whether or not to stratify. Also, you should report how and why you decided to do so.  The key is to think about to what situations exactly your generalization error should generalize.

To using the obtained classifier on data with the same relative frequencies as in the training data? => stratify
To using the obtained classifier on data with possibly slightly different relative frequencies? => do not stratify
You use a classifier that you know to be rather insensitive wrt. to the relative frequencies (e.g. because you specify prior probabilities)? => stratification doesn't matter much.
You have information about the relative frequencies of the classes in the real world and your study is small but nevertheless set up in a way to closely resemble these? => stratification is sensible.
You are studying the classifier algorithm rather than the application? => In that case, it may make sense to do both, and see whether the algorithm is sensitive to slight changes in the relative frequencies of the classes.

So IMHO more important than stratifying or not is to be think of the consequences.
Answer: From purely intuitive viewpoint, imposing exactly the same distribution of classes across all the folds seems not justified: this way you take it as ground truth that the distribution will be the same in all datasets in the world that model may encounter in the future.
To put differently, if $D$ is your data, $I$ is all your prior information about the world, and $f_{classes}$ is the frequency of classes in your dataset, $F_{classes}$ is the frequency of classes in the datasets you're about to see, then $Pr(F_{classes}=f_{classes} \big| D,I)$ is not 1. What does it equal to exactly depends on how you model it.
Then, if class distribution across all folds is forced to be the same, then cross-validated error estimate might be biased and not really estimate generalization error. So to say, we begin to use information that we don't really have -- it's a straight way to overfitting.
Nevertheless, it's only some intuitions, and I cannot derive it rigorously right away. Maybe I miss something important. Personally, I don't incur any restrictions on class distribution when sampling for CV, and know much research that also doesn't.
Of course, if the data is very imbalanced and some classes are very rare, than some restrictions is surely needed just to make sure that the observations of a given class are not too rare in absolute sense. Also, some more complicated CV schemes are used when, for example, comparing accuracy of different classifiers on one dataset, to find out if one of them is "significantly" better.

K-Fold cross validation for multi class


How to analyze data which might come from a few normal distribution concatenate together in order?

Question: For example, I have a series of values for example like the following:
data <- c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300))

I don't know the mean, don't know the sd of my data, and am particularly interested in the "sign of the mean" of my data (I can do a t-test but most often it is not significant, and even if it is, it only tells half of the story), and would be better to know if it changes over time. (how ever, I believe the data is not a time series, i.e. consecutive data points are independent of each other). But, I also doubt that my data might have different baseline distributions (assumed normal) at different time stages.
So, what is a standard way of analysing such data? You can see the sd of my data is quite big. Do I have to pretend it is a time series and decompose it to see the trend?
df <- data.frame(x=1:30000, data=data)
ggplot(df, aes(x=x)) + geom_bar(aes(y=cumsum(data)), width=1, stat="identity")

This is the graph of cumulative values of the data. Can we tell if it is from one normal distribution, or several normal distributions with different means and variances? If it is possible, what assumptions do I have to make?

Compared to this:
data <- rnorm(30000, 3, 1800)
df <- data.frame(x=1:30000, data=data)
ggplot(df, aes(x=x)) + geom_bar(aes(y=cumsum(data)), width=1, stat="identity")

Update:
I guess that changepoint package in R is good enough
> a <- cpt.meanvar(data=c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300)), method="BinSeg")
> summary(a)
Changepoint type      : Change in mean and variance
Method of analysis    : BinSeg
Test Statistic  : Normal
Type of penalty       : SIC with value, 20.61791
Maximum no. of cpts   : 5
Changepoint Locations : 10264 19013

> b <- cpt.meanvar(data=rnorm(30000, 3, 1800), method="BinSeg")
> summary(b)
Changepoint type      : Change in mean and variance
Method of analysis    : BinSeg
Test Statistic  : Normal
Type of penalty       : SIC with value, 20.61791
Maximum no. of cpts   : 5
Changepoint Locations :

PELT would give some small intervals thought I had penalty to include the number of change points.
> a <- cpt.meanvar(penalty="SIC1",data=c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300)), method="PELT")
> summary(a)
Changepoint type      : Change in mean and variance
Method of analysis    : PELT
Test Statistic  : Normal
Type of penalty       : SIC1 with value, 30.92686
Maximum no. of cpts   : Inf
Changepoint Locations : 10049 18984 18987
>
> a <- cpt.meanvar(penalty="SIC1",data=c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300)), method="PELT")
> summary(a)
Changepoint type      : Change in mean and variance
Method of analysis    : PELT
Test Statistic  : Normal
Type of penalty       : SIC1 with value, 30.92686
Maximum no. of cpts   : Inf
Changepoint Locations : 8810 8814 18962

Comment: You appear to be asking to identify a [tag:changepoint].  Do the threads with that tag help?
Comment: @whuber I haven't come across the concept of "changepoint"... so there is no tag.. but if you think it is relevant, you can add it.
Comment: Although the term may be new to you (which is why I mentioned it), it is not new to this community.  The tag exists: you can add it yourself or access it through the link in my comment.  You can also use our [search capability](http://stats.stackexchange.com/search?q=changepoint).
Answer: Please be careful when using the Binary Segmentation flag in the changepoint package.  If you are not familiar with changepoints then you may not be aware that this gives an approximate solution to the changepoint search - meaning that a more accurate segmentation may exist.  I would advise using method='PELT' as this provides an exact search approach and thus the most accurate segmentation.
You should also be aware that for changes in mean it is hard to detect a change if (mu_1-mu_2)/sigma < 0.7.  By hard I mean that the likelihood ratio test has power less than 0.8.
Comment: Actually I was more stupid than you image. I had thought BinSeg is Segment Neighbourhoods so it is exact... However, it seems in the example case in the post Binary Segmentation is superior to PELT in my test.
Comment: And I don't get why PELT would tend to give some very small intervals  see my updates
Comment: This is more a question of penalty choice, especially in your example where there are long periods between changes and the length of your data is relatively large.  The SIC (in particular) is a greedy penalty, especially when n is larger than 1,000.  Whilst there is not an "optimal" penalty I would advocate penalties that include a term based on segment length.  The next release of the changepoint package will include this type of penalty.


Invoking a C function dynamically at runtime without knowing its prototype

Question: I want to know if it is possible to achieve above. Apparently it is possible to load a library and invoke method of it using dlopen, dlsym methods in Linux. But it requires knowing the function prototype to cast the void * pointer to the respective type before invocation.
Assuming prototype metadata can be provided externally (using some descriptor file etc.)
Is there a way to accomplish this?
Comment: This is not possible in general, I believe (though maybe some hack using varargs might work). Do you have a specific purpose in mind?
Comment: C is not a Dynamic language like python or javascritp, you must know the prototype of your function
Comment: @larsmans In fact this is for some experimental code that I am trying to write for a RPC server like functionality where the parameters you get via a HTTP call would be used to invoke some function present in a library which can be loaded at runtime.
Answer: It's possible for sure, but don't expect anything portable. For example, you may be able to use the infamous libffi library. Dummy example in pseudo-C:
// We make some kind of descriptor structure and possible return and argument types
enum c_type {
    C_TYPE_CHAR,
    C_TYPE_INT,
    C_TYPE_FLOAT,
    C_TYPE_PTR,
    C_TYPE_VOID
};

struct func_proto_desc {
    enum c_type ret_type;
    int n_args; // Reasonable convention: -1 for variadic
    c_type *arg_types;
};

// Imaginary function that parses textual metadata and returns a function descriptor
void parse_func_desc(const char *str, struct func_proto_desc *desc);

// this is how to use it:
struct func_proto_desc fproto;
parse_func_desc("void (*)(int, float, const char *)", &fproto);

ffi_cif cif;
ffi_type *args[3];
void *vals[3];

int n = 42;
float f = 3.1415927;
const char *s = "Hello world!";

vals[0] = &n;
vals[1] = &f;
vals[2] = &s;

// Here you can set up the types according to the type description
// that the parser function returned
// (this one is an imaginary function too)
populate_ffi_types_from_desc(args, &fproto);

// Use libffi to call the function
ffi_prep_cif(&cif, FFI_DEFAULT_ABI, fproto->n_args, &ffi_type_void, args);
ffi_call(&cif, func_ptr, NULL, vals);

Something like this should get you started.
Comment: @chamibuddhika It uses heavy and evil assembly hacking :)
Comment: This seems feasible. Accepting this as the correct answer since I don't see any stumbling blocks with this approach. Will try this out and see. But just curious how this library achieves some thing which is not supported by the language it self.


Solving the given equation

Question: How to find general solution of matrix differential equation $\textbf{X}'(t)=\textbf{A}\textbf{X}(t)+\textbf{B}(t)$ by Green's Function/Matrix Method?
In here, $0<t<t_{max}$
\begin{equation}
\begin{aligned}
&\textbf{X}(t)=\left( \begin{array}{cccc}
x_{1}(t) \\
x_{2}(t) \\
x_{3}(t)\\
x_{4}(t) \end{array} \right), \textbf{A}
=
\left( \begin{array}{cccc}
a_{11} & a_{12} &a_{13} & a_{14}\\
a_{21} & a_{22} & a_{23} & a_{24} \\
a_{31} & a_{32}& a_{33} & a_{34} \\
a_{41} & a_{42} & a_{43} & a_{44}
\end{array} \right),\\
&\textbf{B}(t)=\left( \begin{array}{cccc}
b_{1}(t)\\
b_{2}(t)\\
b_{3}(t)\\
b_{4}(t) \end{array} \right).
\end{aligned}
\end{equation}
initial conditions:
$$x_1(0)=m_1$$
$$x_2(0)=m_2$$
$$x_3(0)=m_3$$
$$x_4(0)=m_4.$$
$\lvert A \rvert >0$
and $A$ has four distinct complex eigenvalues $\lambda_1=c i$,
 $\lambda_2=-c i$,
  $\lambda_3=d i$,  $\lambda_4=-d i$ where $a_{ij},c,d\in \mathbb{R}$ for $i,j=1,2,3,4.$
Respectively, the eigenvectors are $v_k$ for $k=1,2,3,4.$
Comment: See [fundamental matrix](https://en.wikipedia.org/wiki/Linear_differential_equation#Systems_of_linear_differential_equations), [Wronski matrix and determinant](https://en.wikipedia.org/wiki/Wronskian),...
Answer: It is rather simple, however, there will be a Green's matrix (tensor) not a green's function. The solution to the equation
$$X'-AX=B$$
May be written as
$$X(t)=X_{0}(t)+\int\mathcal{G}(t, t')B(t')dt'$$
Where
$$X'_{0}(t)-AX_{0}(t)=0$$
and $\mathcal{G}(t, t')$ is a $4\times4$ matrix satisfying
$$\frac{d}{dt}\mathcal{G}(t, t')-A\mathcal{G}(t, t')=I\delta(t-t')$$
Where $I$ is the identity. One way to find $\mathcal{G}(t, t')$ is via the Fourier transform
$$\mathcal{G}(t, t')=\frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}}\hat{\mathcal{G}}(\omega, t')e^{i\omega{t}}d\omega$$
and
$$\delta(t-t')=\frac{1}{2\pi}\int_{\mathbb{R}}e^{i\omega(t-t')}d\omega$$
Which gives
$$[i\omega{I}-A]\hat{\mathcal{G}}(\omega, t')=I\frac{1}{\sqrt{2\pi}}e^{-i\omega{t'}}$$
Hence
$$\hat{\mathcal{G}}(\omega, t')=\frac{1}{\sqrt{2\pi}}[i\omega{I}-A]^{-1}e^{-i\omega{t'}}$$
and
$$\mathcal{G}(t, t')=\frac{1}{2\pi}\int_{\mathbb{R}}[i\omega{I}-A]^{-1}e^{i\omega(t-t')}d\omega$$
Where you also need to invert the matrix $[i\omega{I}-A]$. Another approach would be to diagonalize the matrix $A$, $A=S\Lambda{S}^{-1}$ (which you've already done), then you do the transformation $\mathcal{G}\rightarrow\mathcal{G}'=S^{-1}\mathcal{G}S$ and you obtain
$$\frac{d}{dt}\mathcal{G}'(t, t')-\Lambda{\mathcal{G}'(t, t')}=\delta(t-t')$$
Or component wise
$$\mathcal{G}'_{lm}(t, t')=X_{0}(t), \ l\neq{m}$$
and
$$\frac{d}{dt}\mathcal{G}'_{ll}(t, t')-\Lambda_{ll}\mathcal{G}'_{ll}(t, t')=\delta(t-t')$$
Which is easy to solve...
Comment: Is it not much simpler to look at the solution formula $X(t)=U(t)X(0)+U(t)\int_0^tU(t')^{-1}B(t')dt'$ to find $G(t,t')=U(t)U(t')^{-1}$?
Comment: Unfortunately, I'm not a mathematician, but instead a physicist. So, I cannot recommend any sort of mathematically rigorous literature. However, if you are not looking for something really strict, I would say that any textbook with the name like "Methods of mathematical physics" will do it!))
Comment: Thank you all. Do you suggest me some good books in order to understand well and solve similar questions? I don' t understand well how to find Green's function and Green's matrix.

Solving the given equation


Docker and sensitive information used at run-time

Question: We are dockerizing an application (written in Node.js) that will need to access some sensitive data at run-time (API tokens for different services) and I can't find any recommended approach to deal with that.
Some information:

The sensitive information is not in our codebase, but it's kept on another repository in encrypted format.
On our current deployment, without Docker, we update the codebase with git, and then we manually copy the sensitive information via SSH.
The docker images will be stored in a private, self-hosted registry

I can think of some different approaches, but all of them have some drawbacks:

Include the sensitive information in the Docker images at build time. This is certainly the easiest one; however, it makes them available to anyone with access to the image (I don't know if we should trust the registry that much).
Like 1, but having the credentials in a data-only image.
Create a volume in the image that links to a directory in the host system, and manually copy the credentials over SSH like we're doing right now. This is very convenient too, but then we can't spin up new servers easily (maybe we could use something like etcd to synchronize them?)
Pass the information as environment variables. However, we have 5 different pairs of API credentials right now, which makes this a bit inconvenient. Most importantly, however, we would need to keep another copy of the sensitive information in the configuration scripts (the commands that will be executed to run Docker images), and this can easily create problems (e.g. credentials accidentally included in git, etc).

PS: I've done some research but couldn't find anything similar to my problem. Other questions (like this one) were about sensitive information needed at build-time; in our case, we need the information at run-time
Comment: Very hard problem to solve properly. Best solution I've found is Hashicorp's vault, but the project is very new:  https://www.vaultproject.io/
Answer: I've used your options 3 and 4 to solve this in the past. To rephrase/elaborate:

Create a volume in the image that links to a directory in the host system, and manually copy the credentials over SSH like we're doing right now.

I use config management (Chef or Ansible) to set up the credentials on the host. If the app takes a config file needing API tokens or database credentials, I use config management to create that file from a template. Chef can read the credentials from encrypted data bag or attributes, set up the files on the host, then start the container with a volume just like you describe.
Note that in the container you may need a wrapper to run the app. The wrapper copies the config file from whatever the volume is mounted to wherever the application expects it, then starts the app.

Pass the information as environment variables. However, we have 5 different pairs of API credentials right now, which makes this a bit inconvenient. Most importantly, however, we would need to keep another copy of the sensitive information in the configuration scripts (the commands that will be executed to run Docker images), and this can easily create problems (e.g. credentials accidentally included in git, etc).

Yes, it's cumbersome to pass a bunch of env variables using -e key=value syntax, but this is how I prefer to do it. Remember the variables are still exposed to anyone with access to the Docker daemon. If your docker run command is composed programmatically it's easier.
If not, use the --env-file flag as discussed here in the Docker docs. You create a file with key=value pairs, then run a container using that file.
$ cat >> myenv << END
FOO=BAR
BAR=BAZ
END
$ docker run --env-file myenv

That myenv file can be created using chef/config management as described above.
If you're hosting on AWS you can leverage KMS here. Keep either the env file or the config file (that is passed to the container in a volume) encrypted via KMS. In the container, use a wrapper script to call out to KMS, decrypt the file, move it in to place and start the app. This way the config data is not exposed on disk.
Comment: But in this case chef still needs the decryption keys... Correct? (Still better than having decrypted data and safer against accidental inclusion into GIT...) also, good idea using KMS, but even though we're on AWS we're trying to be as provider-neutral as possible
Comment: Yes, chef needs the decryption key. Something ultimately will need it of course. Also, not that you asked, but I [blogged my thoughts on the cloud lock in issue](http://blog.bwhaley.com/the-fallacy-of-lock-in).
Comment: Your blog post makes sense, but truth is we are actually going to move everything to Azure before the end of the year, so it's a real problem for us :)
Comment: Makes sense, in that case it wouldn't be wise to optimize with KMS. So instead just be careful to secure the decryption key on the chef server.


Interesting melodic resolutions: A specific example. What's happening?

Question: Listen to the intro of the following MuteMath song, Break The Same:

These guys are stellar and well known their innovative songwriting and grandois shows. I really like how the introduction to this song begins with the guitar riff carrying the melody and then the bass + keytar resolve the line very nicely at the end of the bar.
I would like to know if there's anything interesting happening here theory-wise, specifically in the intro/chorus bars. I would love to be able to emulate this sort of melodic convergence.
Answer: Its an awesome track, i enjoyed it; but technically nothing unusual happens until the Avant-garde bit at the end.
The general idea seems to be a variation around a C# minor theme (from the 9th fret on the g'tar);
First Bit
Bass: is playing F# B C#  then an open E string run  E/F# E/Ab B/C (I think :))
Guitar: is alternate picking Ab its 5th(Eb) / Ab its 4th(C#) /  Ab its flat 7(F#)
The rest is a variation on this at different velocity, if you figure out the first bit you'll have the rest no probs.
The picked notes by the guitar almost make up an Abmin7 chord, which I think i heard strummed as a chord in the quieter interludes and towards the end of the song.
And actually, the bass provides the B(flat 3rd), which is the missing tone from the guitar picking section.
Its ok to play C# Dorian over this Abmin7, since it shares the all the same notes as Ab minor; and all the notes of Abmin7 (Ab Eb F# B) appear in both Ab minor(C# Dorian) and C# Minor.  (And in fact I think the last section; before the drum bit ends up in Ab minor)
Thats the only thing going on in this really; and its brilliant; its the kind of thing i like to do a lot.
Comment: Thanks DRL. I'm a novice when it comes to analyzing harmonies, and you have helped me to understand what's going on. I appreciate it!
Comment: No probs, i don't think i've got it spot on; but its a start.
Answer: Sounds all diatonic to me. Just arrangement. I don't here what you are hearing. The guitar is playing a simple riff(nothing special). The keyboard has it's melody(kinda strange sounding IMO). The bass plays a simple ascending bass line. The drums do start off with a rather unusual but good sounding drum beat.
Doesn't seem much "special" going on here. Such as complex harmonies, complex polyphony(there is polyphony due to the different instruments but they are "accidental"), etc...
What I'm getting at is that individually the different melodies that each instrument plays is rather bland. Like always, anytime you play them together there are new melodies and harmonies created. Did they sit down and just come up with random parts and throw them together? Of course not. Is there anything spectacular going on? Of course not. If you like it, it is because you have similar taste to those guys. If you don't then it's cause you don't.
Unfortunately no one has been able to beat Bach in his polyphony and he still is up there in some of the most complex harmonies(and virtually all of it was intentional). Just imagine what he could do today! This is not to knock everyone else. Bach, overall, just seems to have been light years above anyone else. It doesn't mean everyone else sucks or that they didn't do cool things. Even simple things can sound very cool and you can't compare different styles of music. Obviously Bach didn't rap so just about any rapper will be better than Bach. What we can say is that if Bach was a live and rapped he probably would be the best... and would still suck as a mechanic, or anything else non-musical.
Comment: Btw, apropos of nothing in particular, Bach would have been an *awesome* mechanic.  He was constantly tinkering with instruments, trying to improve their sound and playability.  He had a thorough and complete understanding of the inner workings of the church organ, which was at the time the most complex mechanical device of any kind in the entire world.  If Bach were alive today, I would absolutely trust him to repair my transmission.  Just sayin'.
Comment: @AbstractDissonance: In retaliation for my comment, you have downvoted *eight* of my other posts (apparently selected randomly). This is, of course, your right to do, and I support that right. But the etiquette around here is as follows: when we downvote a post, we also leave a comment explaining our vote and how the post could be improved.  I would appreciate it if you would go back and leave those comments, so that I may improve them and serve the guitars.SE community better in the future.  Thank you.
Comment: -1 Dude. Huh? You lost me in that last paragraph. Just imagine what Bach could do today?  You mean, given all the advances in sheet music technology and violin bowing?  Bach as a rapper?  Bach as a mechanic?  What are you talking about?
Comment: In all honesty dude, I don't care if you like the track or not, I just wanted to know exactly what was going on--irregardless of how simple it is. Note that I *never* asked you to critique the track, but instead to explain to me what's happening musically. It seems you know something about music theory, and you could have easily explained to me what was happening **without** being condescending. I'm self taught--so I know absolutely nothing about the academic construction of a musical work.
Comment: I don't quite understand how what they are doing is uninteresting. I mean it's not as complex as a symphony, but the syncopation between instruments is phenomenal.
Comment: @Alex: You obviously don't know much about Bach or his music. You also seem to have an issues understanding what musicality is.
Comment: @Jduv: I didn't say it was uninteresting.  What I said it was that it wasn't complex(i.e., complicated). There is no non-diatonic harmonies, non-diatonic melodies, complicated rhythms except what happens by the combination of the individuals(and it seems this is what you are finding as interesting or complex). Why you like it and not some other band that has similar levels of complexity has almost everything to do with your taste. My point is that there are bands/songs/composers that do things these guys do on a much larger level but you may not like them because of taste.
Comment: @AbstractDissonance you have never come across a complex diatonic harmony?
Comment: By definition diatonic harmony is simple harmony. Now if you consider alterations of the diatonic harmony as diatonic then you can have complex diatonic harmony but this isn't generally how diatonic harmony is defined. Your aug6's, altered dominants, substitutions, etc... are all non-diatonic and create a more rich and complex harmony. It's neither good or bad but just the way it is. My point is, is that the OP asked about what was going on and my reply states that nothing much. It's basic pop music. Nothing advanced. No jazz, no advanced anything. The compound rhythms are the most complex.
Comment: Just because it gives you a boner doesn't mean there is something great about it. There are many factors involved. Jazz has a lot of advanced harmony but I don't it(most of it). Doesn't mean jazz sucks... just not my style. Just because you like this style of music doesn't mean it's special or complex or anything. It's all about taste. But as far as complexity goes this is pretty low on the list. BUT AGAIN, that doesn't mean it's bad music. You might find it to be complex, you might not understand the harmonic content or the syncopation's, so I guess it could be complex to you...


$_POST Array is empty

Question: I am working with XAMPP and PHPStorm v9, running locally, a simple application that does an AJAX callback.
My server handler for the AJAX request is showing an empty $_POST array and I have no idea why. Before I take all of this code and run on a different server, to eliminate the platform as the issue, does anyone see why the $_POST array would be empty? Any suggestions? Thanks
The XHR pane, shows the post executed.

The JS
if (valid) {

    var queryStr = 'fName=' + firstName.val() + '&lName=' + lastName.val() + '&email=' + email.val() + '&phone=' + phone.val();

    var f = firstName.val();
    var l = lastName.val();
    var e = email.val();
    var p = phone.val();

    $.ajax({
        type: "POST",
        url: '/ACS567-Projects/addContact.php',
        data: {
            fName: f,
            lName: l,
            email: e,
            phone: p
        },
        dataType: 'html',
        success: OnAddSuccess,
        error: OnAddFailure,
        timeout: 60000
    });
}

The PHP handler
<?php

if(isset($_POST['fName'])) {

    $firstName = $_POST['fName'];
    $lastName = $_POST['lName'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $addressBook->addContact($firstName,$lastName,$email,$phone);

    echo "success";
    exit();
}

echo "failure";
exit();

Comment: Try setting `processData` to `false` and/or do a `var_dump` on the `$_POST` array to see what you are getting instead. Your data is probably converted into a query string before sending.
Comment: how you know so POST is empty? Open your browser web tools and check network XHR what you're sending
Comment: I logged the $_POST check from inside the handler and POST is empty:foreach ($_POST as $key => $value) {

    $str.=$key." =>".$val;

}
Comment: @Slinky handler? from script what you posted ... how you can be sure the POST data is populated and exist in method addContact? .. pls what you are got from response? succes or failure html? If you don't see any of both you have problem upper.
Comment: hmm your POST is empty because you don't send nothing :D ... is if (valid) { really VALID ?
Comment: Yes, the data is valid and the PHP handler is getting called but $_POST is empty. The AJAX response is the "failure" message as well
Comment: Is request being made to different localhost port than page is on? use arguments in error handler to trace down issues
Answer: Data will not automatically turn into an array ready for use in your PHP script. Read the jQuery documentation:

It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

Also, you should use 'method' instead of 'type' if you don't have an old jQuery version.
More info on the .ajax function found here:
http://api.jquery.com/jquery.ajax/
Have you inspected your client/browser to see what is posted and dumped the $_POST variable to see that it's really empty?

$_POST Array is empty


undefined method `respond_to' for Api::V1::LocationsController:Class

Question: I am new to rails and decided to make make an application that shows the weather. I followed this tutorial and GoRails Rails API video course. When I run server (path: http://127.0.0.1:3000/api/v1/locations), I see undefined method respond_to for Api::V1::LocationsController:Class error. The same is with http://127.0.0.1:3000/api/v1/locations/1. I googled a lot, but didn't see an appropriate answer. I am leaving code here. Locations is for the city and Recordings is for temperature. I am also leaving schema here if this is the case. A screen of directories tree is attached.
I'VE NEVER BEEN SO STUCK
routes.rb
Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :locations
    end
  end

  resources :locations
  root "locations#index"
end

locations_controller:
module Api
  module V1
    class LocationsController < ApplicationController
      respond_to :json

    def index
      respond_with LocationsController.all
    end

    def show
      respond_with find_location
    end

    private
    def find_location
      @location = LocationsController.find(params[:id])
    end
  end
  end
end

recordings_controller
class RecordingsController < ApplicationController
end

application_controller
class ApplicationController < ActionController::Base
end

Models:
location.rb
It is also not able to find these fields in db for some reason...
class Location < ApplicationRecord
  belongs_to :recording

  validates_uniqueness_of :name
end

recording.rb
class Recording < ApplicationRecord
  has_many :locations
end

schema:
ActiveRecord::Schema[7.0].define(version: 2022_10_20_135036) do
  create_table "locations", force: :cascade do |t|
    t.integer "recording_id", null: false
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["recording_id"], name: "index_locations_on_recording_id"
  end

  create_table "recordings", force: :cascade do |t|
    t.integer "temp"
    t.string "status"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_foreign_key "locations", "recordings"
end

I thought to use here one-to-many association. As I thought, one city has one temperature and one temperature has loads of cities.
Answer: The tutorial you are following is quite old and partly outdated. The respond_to method which is in the first line of the Api::V1:: LocationsController was removed in Ruby on Rails 5.0 about six years ago.
But the good news it that its functionality has been extracted to the responders gem. That means when you add that gem to your application's Gemfile then it might work after running bundle install and restarting the server.
Note. I wrote it might work because it is possible that there are other incompatibilities between the tutorial and your current, up-to-date Ruby on Rails version 7.0.
Comment: Thank you! I refactored the code to `render json: ...`. The problem was that I was stupid and created instances in locations_controller from LocationsController class, not Location. :)


Apache alias works in browser, but does not work while trying to access via svn client

Question: I am encountering an issue that drives me mad. I installed from scratch an ubuntu 14.04 machine, installed a LAMP stack and subversion. I created a new folder /var/www/svn and imported my various SVN dumps. Made sure they all were set in the svnserve.conf file to be accessible via svn:// and made as well sure that there's a user in the passwd file for me to access it. I added myself and the www-data user to that directory to make sure it is available in the internet. To not bother with too much attributes I started the svnserve with the following command svnserve -d.
I then went on to add to my 000-default.conf an alias Alias /svn /var/www/svn, restarted the apache2 service and it worked like a charm in the browser.
Now to my actual problem when I am trying to access the repo with tortoisesvn I get the error message that there's no svn at that location. After spending quite a while researching I see somebody mention that he was able to access it when using the 'full' path. So I tried the following svn://mydomain.com/var/www/svnand it works...
As the alias works in a browser, but doesn't in a SVN client I am totally flabbergasted.
Any ideas?

To summarize:
I am using www.example.com/svn/myrepo when it doesn't work, and when I am using www.example.com/var/www/svn/myrepo then it works.
Full 000-default.conf:
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com

    ServerAdmin email@example.com
    DocumentRoot /var/www/html

    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>

    <Directory /var/www/html/>
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    Alias /svn /var/www/svn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Output of apachectl -S

   VirtualHost configuration:*:80
    www.example.com (/etc/apache2/sites-enabled/000-default.conf:1)
    ServerRoot: "/etc/apache2"
    Main DocumentRoot: "/var/www"
    Main ErrorLog: "/var/log/apache2/error.log"
    Mutex default: dir="/var/lock/apache2" mechanism=fcntl
    Mutex mpm-accept: using_defaults
    Mutex watchdog-callback: using_defaults
    Mutex rewrite-map: using_defaults
    PidFile: "/var/run/apache2/apache2.pid"
    Define: DUMP_VHOSTS
    Define: DUMP_RUN_CFG
    User: name="www-data" id=33 not_used
    Group: name="www-data" id=33 not_used

Comment: What URL are you using to access the repo from the SVN client when it's not working?
Comment: I am using www.example.com/svn/myrepo when it doesn't work, and I am using www.example.com/var/www/svn/myrepo when it works.
Comment: `www.example.com/var/www/svn/myrepo` works?  Your docroot is `/var/www/html` not `/`, and that doesn't match an alias, so it shouldn't work - that would be looking for a file at `/var/www/html/var/www/svn/myrepo`. Is there other config involved?  What's the output of `apachectl -S`?
Comment: Added `apachectl -S` output to original question. Thanks for helping!
Comment: So, any other config involved?  `/var/www/html/var/www/svn/myrepo` shouldn't work, so unless that path exists or you have more aliases somewhere (...`.htaccess`?), something doesn't add up.
Comment: I just remembered I edited the apache2.conf... I think I edited one Options Indexes FollowSymLinks AllowOverride None Require all granted` is what it is now and I think it was /var/www/html... can THAT be it?
Answer: The apache config file is only used when you access the repository using http or https. When you're using svn, the connection is handled by svnserve which is an entirely separate program.
The documentation for svnserve is available at the SVN book or the man page man svnserve and man svnserve.conf. You can set the root path when you invoke it, like so:
svnserve -r /var/www

to make it start looking for files and repos under /var/www instead of immediately under /.
Comment: absolutely correct... I am a flaming moron to mix that up. Thanks!
Comment: heh, bonus point for noticing the flames and putting them out though :-)


Attach a submit handler on an ajax-y form (hook_media_format_form_prepare_alter)

Question: I'm working with media 7.x-2.0-unstable7.
I am attempting to adjust the behavior of the media module's wysiwyg embedded image attribute editor modal dialog (c.f. http://drupal.org/node/835516).  It was pretty easy to adjust the contents of this dialog with hook_media_format_form_prepare_alter (see: http://drupal.org/node/835516#comment-7075374), and I expected that it would be easy to add a submit handler, and Drupal would jump through the hoops for me to insure that it was called at the right time. If this service is offered, I can't seem to figure out how to make it work.
The only other place I can find that uses hook_media_format_form_prepare_alter is media_crop, and it includes its own ajax POST to send its data back to the server.  It's not clear to me how the standard media_format_form saves its data.  It looks like ctools handles calling the submit handler for similar form, media_file_edit_modal (called for editing image metadata fields for media image files that are entity fields).  Is there something similar for hook_media_format_form_prepare_alter, or do I have to write my own Javascript and my own data-receive menu, like media_crop does?
media.api.php did not help clarify.
Answer: It always pays to test your assumptions.  The media_format_form only saves metadata edits into the embedded media tag in the edit text contents; the alt and title information attached to the file object are not adjusted.  There is an advantage to this, in that different instances of the same picture embedded in different locations can also have different alt and title text.  Unfortunately, though, it also means that if an image is uploaded via the embedded media image tool in a wysiwyg editor, then the alt and title fields will be empty the next time that image is used, whether it is used as an embedded image or attached to a media image file field.
It would be helpful if media_format_form would save metadata changes back to the file object, just as media_file_edit_modal does.  However, it appears that at the moment, that capability is not present in the code.


Verify my answer on induction definition for the set

Question: Write an induction definition for the set A={<a>, <b,a,b>,<a,b,a,b,a>,
<b,a,b,a,b,a,b>,….}
basic: < a > ∈A
induction:if bxb∈A then a::bxb::a ∈A
if a::x then b::x::b ∈A
Comment: Sorry, but I don't understand your notation.  What is $x$?  What does :: mean?
Comment: IT means cons()
Answer: Your definition seems to work, roughly. Your use of $x$ and $::$ seems a bit inconsistent though. Here's another way of writing it that is a bit more precise.
Basis:
$\langle a \rangle \in A$
Inductive step:
$\langle a::x \rangle \in A \implies \langle b::a::x::b \rangle \in A$
$\langle b::x \rangle \in A \implies \langle a::b::x::a \rangle \in A$
Comment: Thanks so much!
Comment: Feel free to explain the tree induction!thx !
Comment: @toby I'll give it a try.


The set of ordinals $< \alpha$ of a given cofinality $\kappa< \text{cf}(\alpha)$ is stationary

Question: I don't understand the last line of the following proof :

I understand that we climbed up to $g(\kappa)$ in $\kappa$ steps (i.e. cf$\big(g(\kappa)\big) \leq \kappa$) but can we be sure that we did in as quickly as one possibly can ? Put differently how can we but sure that $g(\kappa) \in S$ ?
Source : http://euclid.colorado.edu/~monkd/m6730/gradsets09.pdf
Comment: Perhaps you could identify the source of this proof.
Answer: Note that $g$ is a strictly increasing continuous function, and $\kappa$ is regular. So this is reduced to showing that $g(\kappa)$ has cofinality $\kappa$.
One direction is trivial, it is certainly at most $\kappa$, but on the other hand, if the cofinality was $\mu<\kappa$, by considering the preimages of that $\mu$-sequence we would obtain a $\mu$-cofinal sequence in $\kappa$.
Comment: Where do we use the continuity of the function ?
Comment: When you claim that $f(\kappa)$ is the limit of $f(\gamma)$ for $\gamma<\kappa$.


Postfix sendmail sets original recipient

Question: I have a postfix + dovecot with a spamassassin doing some content filtering on the postfix side. The problem is that with a recent update the originally available sendmail binary was replaced with the sendmail.postfix binary. Which seems to work differently with recipient information.
Here are some information about the configuration:
master.cf
<external ip>:submission         inet  n      -      -      -      -   smtpd
    -o content_filter=spamassassin
    -o cleanup_service_name=pre-cleanup
127.0.0.1:smtp                   inet  n      -      -      -      -   smtpd
[...]
spamassassin    unix        -       n       n       -       -       pipe
    flags=Rq user=spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}

And the slightly anonymized log output which shows the actual problem:
Feb  7 02:47:04 comu postfix/smtpd[25393]: connect from unknown[<my ip>]
Feb  7 02:47:04 comu postfix/cleanup[25398]: C0A192C5816B: message-id=<email@example.com>
Feb  7 02:47:04 comu postfix/qmgr[25384]: C0A192C5816B: from=<postmaster@domain>, size=259, nrcpt=1 (queue active)
Feb  7 02:47:04 comu dovecot: lmtp(25400): Connect from local
Feb  7 02:47:04 comu dovecot: auth: mysql: Connected to 127.0.0.1 (postfix)
Feb  7 02:47:04 comu dovecot: lmtp(25400): Disconnect from local: Client quit
Feb  7 02:47:04 comu postfix/lmtp[25399]: C0A192C5816B: to=<postmaster@domain>, orig_to=<admin@domain>, relay=smtp.domain[private/dovecot-lmtp], delay=0.04, delays=0.01/0.01/0/0.02, dsn=2.1.5, status=deliverable (250 2.1.5 OK)
Feb  7 02:47:04 comu postfix/qmgr[25384]: C0A192C5816B: removed
Feb  7 02:47:07 comu postfix/smtpd[25393]: C6E932C5816B: client=unknown[<my ip>]
Feb  7 02:47:07 comu postfix/cleanup[25403]: C6E932C5816B: message-id=<firstname.lastname@example.com>
Feb  7 02:47:07 comu postfix/qmgr[25384]: C6E932C5816B: from=<email@example.com>, size=697, nrcpt=1 (queue active)
Feb  7 02:47:07 comu postfix/smtpd[25393]: disconnect from unknown[<my ip>]
Feb  7 02:47:08 comu postfix/pipe[25404]: C6E932C5816B: to=<admin@domain>, relay=spamassassin, delay=3.5, delays=3.2/0.02/0/0.34, dsn=2.0.0, status=sent (delivered via spamassassin service)
Feb  7 02:47:08 comu postfix/pickup[25383]: 3F49C2C58395: uid=505 from=<firstname.lastname@example.com>
Feb  7 02:47:08 comu postfix/qmgr[25384]: C6E932C5816B: removed
Feb  7 02:47:08 comu postfix/cleanup[25403]: 3F49C2C58395: message-id=<firstname.lastname@example.com>
Feb  7 02:47:08 comu postfix/qmgr[25384]: 3F49C2C58395: from=<email@example.com>, size=1340, nrcpt=1 (queue active)
Feb  7 02:47:08 comu dovecot: lmtp(25400): Connect from local
Feb  7 02:47:08 comu postfix/lmtp[25399]: 3F49C2C58395: to=<admin@domain>, relay=smtp.domain[private/dovecot-lmtp], delay=0.08, delays=0.06/0/0/0.01, dsn=5.1.1, status=bounced (host smtp.domain[private/dovecot-lmtp] said: 550 5.1.1 <admin@domain> User doesn't exist: admin@domain (in reply to RCPT TO command))
Feb  7 02:47:08 comu dovecot: lmtp(25400): Disconnect from local: Client quit
Feb  7 02:47:08 comu postfix/cleanup[25398]: 45B2F2C5816C: message-id=<firstname.lastname@example.com>
Feb  7 02:47:08 comu postfix/qmgr[25384]: 45B2F2C5816C: from=<>, size=3192, nrcpt=1 (queue active)
Feb  7 02:47:08 comu postfix/bounce[25408]: 3F49C2C58395: sender non-delivery notification: 45B2F2C5816C
Feb  7 02:47:08 comu postfix/qmgr[25384]: 3F49C2C58395: removed
Feb  7 02:47:08 comu postfix/smtp[25390]: 45B2F2C5816C: to=<firstname.lastname@example.com>, relay=none, delay=0.13, delays=0.01/0/0.12/0, dsn=5.4.4, status=bounced (Host or domain name not found. Name service error for name=silverline.local type=AAAA: Host not found)
Feb  7 02:47:08 comu postfix/qmgr[25384]: 45B2F2C5816C: removed

When the E-Mail is first received the original recipient(postmaster@domain) is resolved to the actual recipient(admin@domain) and the existence of that user is checked with dovecot.
Which is fine and returns a success. The E-Mail is then send through the content-filter which requeues the E-Mail with postfix via the local port. But instead of using the actual recipient it's now the original recipient again which of course is not found in the dovecot database.
This error did not occur with the original sendmail binary which probably was from the sendmail project. I tried various flags with the pipe in master.cf without any positive results.
I would greatly appreciate your help.
Answer: I think the problem is that normal cleanup daemon does not run after mail is injected back by your filter. pre-cleanup does not usually make address rewriting and virtual aliasing.
Check if you have -o cleanup_service_name=pre-cleanup on SMTP listener that receives filtered messages from the content filter (usually 10026:) and if so delete it.


how to send image in messaging xmpp framework?

Question: I'm sending only text, but I don't know how to send image/url, videos and integrate that in the chat application in iOS using XMPP.
I have refer so many questions but I want to send image using XEP-0363
I refer so many demo like monal app but any demo can't clear anything.
so
Please help me.
Comment: I am uploading image to S3 and then I am using S3 Url for image in Xmpp.
Comment: what is s3....?
Comment: can you share a code with me?
Comment: S3 is basically a storage server, where you can upload image directly to server, and you will get the image url in response,
Comment: https://github.com/maximbilan/Swift-Amazon-S3-Uploading-Tutorial
Answer: There are a few ways to send images, one way is to create an API, and create a function for uploading images. So when you want to send an image, you can first call your API function, which will upload the image and then return the URL of the image. You can then send the URL in the <message> stanza, possibly in your own custom tags.
For example,
<message to=""...>
    <image>http://example.com/myimg.jpg</image>
</message>

Of course it will then be up to the client to download the image.
Another way to do it is to convert the image to a base64 string, and send the base64 string in the message stanza. However I actually do not recommend doing so, as the base64 string can be extremely large, and sending large packets through xmpp isn't a good idea. Particularly if you are in a group chat with a lot of users, in which case it will have to send the large packet to many users, wasting up valuable bandwidth, as well as server space for any offline-stored messages.
You could of course use XEP-0363 as mentioned, but you just need to make sure your XMPP server supports it.


excel vba to return cell address using a string

Question: i have make a table in excel from A1 to C6  where in column A i have string and in column B and C ihave number. Now i want to write a function code in vba in which when i pass a string from a column A i get the  range or cell address of column C corresponding to A. For eg if in A5 i have "apple" an when i pass apple as an argument to a function it should return cell address of C5 . I tried to search on net but not able to fin the code.
So guys please help me on this . this is very important.
Comment: What have you tried so far? Please add some code examples, possible errors etc.
Answer: The cell formula shown below will return the index in the array $A$1:$A$5 at which the value "peach" is found:
<code>=MATCH("peach",$A$1:$A$5,0)
</code>
if the values in the array $A$1:$A$5 are:

apple
  pear
  banana
  peach
  lemon

then the formula will return 4, the row-index in the array at which "peach" occurs. From this you should be able to complete your requirement.
Comment: thanks for your input an can pu please tell me how to store this in the form of  range.   i know
Comment: An EXCEL *Range* is simply the object created by referring to a contiguous block of cells by its upper-left and lower-right corners.
Comment: thanks for your input an can pu please tell me how to store this in the form of  range.   lets say i have a function call "returnString$(input As String)" when i call this function then C5 corresponing to A5 should be return by function and i can store that in a variable.


basic HTTP authentication preventing user adding bookmark

Question: I have a resource for coffeeshops where I allow the user to both favorite and bookmark individual coffee shops.
I also have http_basic_authenticate_withon the coffeeshop controller to prevent anyone but me from writing to my db.
It seems my current setup then doesn't allow users to actually favorite or bookmark unless they sign in.
How can I get around this? I am also using Devise for user management, can I take advantage of that to restrict write access to the database allowing me to remove http_basic_authenticate_with?
coffeeshop_controller.rb
class CoffeeshopsController < ApplicationController
http_basic_authenticate_with name: "*******, password: "*******", except: [:index, :show]

I tried updating this to [:index, :show, :put] but that has not made a difference.
Comment: If you have a user account system in place, e.g. with Devise, then you probably don't need any http_basic_authentication at all. [Read the README](https://github.com/plataformatec/devise#controller-filters-and-helpers), and authenticate with a `before_filter`.
Comment: Yeah, I need to put aside some time and read about setting up roles I think.
Answer: in the except you should list the controller actions and not http methods, so something like the following:
class CoffeeshopsController < ApplicationController
  http_basic_authenticate_with name: "*******", password: "*******", except: [:index, :favorite, :bookmark]
  def index
    # list of coffeeshops without authentication
  end

  def new
    # requires authentication
  end

  def create
    # requires authentication
  end

  def favorite
    # endpoint to mark coffeeshop as favourite without authentication
  end

  def bookmark
    # endpoint to bookmark a coffeeshop without authentication
  end
  ...
end


Gtest returns SegFault when accessing variable in TEST_F

Question: I am a beginner for Gtest and facing segmentation fault when accessing a class variable inside TEST_F. Below is the snippet of my code, kindly help in pointing the reason behind this behavior.
main.cpp
#include <Foo.h>
#include "gtest/gtest.h"

int main(int argc, char* argv[])
{
  InitalRegister();
  ::testing::InitGoogleTest(&argc, argv);
  int rc = RUN_ALL_TESTS();
  return rc;
}

Foo.h
void InitalRegister();
class TestFoo // Required for registration
{
  //Do nothing
};

Foo.cpp
#include "gtest/gtest.h"
#include <Foo.h>
#include <Bar.h>

void InitalRegister()
{
  //Doing few registration
}

Bar* newBar;
void Bar_called_init(void *inValue) // will be called as part of InitialRegsiter and inValue will be holding a valid value
{
  newBar = (Bar)*inValue;
}

class UnitTestFoo : public::testing::Test
{
  public:
    Bar* inValue;
    Bar* GetValue();
  protected:
  virtual void SetUp() override
  {
    inValue = GetValue();//able to access inValue here
  }
};

Bar* UnitTestFoo::GetValue()
{
  inValue = newBar;
}

TEST_F(UnitTestFoo, Foo1)
{
 if (inValue != NULL) // Getting segfault when accessing inValue here
 {
 }
}

Answer: There are at least 2 major issues with the code you presented (and I don't see Bar.h):

GetValue doesn't return any value while it should return Bar*, please update your code to sth like:
  Bar* UnitTestFoo::GetValue()
  {
    inValue = newBar;
    return inValue;
  }

Bar_called_init tries to dereference void* pointer which should yield a compilation error, please update your code to sth like:
  void Bar_called_init(void *inValue)
  {
    newBar = (Bar*)inValue;
  }

Does you code compile on your machine? With these two fixes I was able to see the test passing:
[ RUN      ] UnitTestFoo.Foo1
[       OK ] UnitTestFoo.Foo1 (0 ms)


C# How to modularly fill a list with floating point values via user input, calculate sum and average

Question: Mind you, I come from a C++ background and the instructor I have should be called an assignment proctor AT MOST. No instruction or guidance whatsoever. Now, is it possible that some kind person could assist me and help me figure out what I'm doing wrong and then explain(In durr durr language)how to fix it so that it compiles??? Here is the code and the errors. Got it down from 22 but these last 9 are killing me and it's now 3 a.m.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P1_Wilson
{
 class P1_Wilson
  {

    float sum;
    float aver;
    int counter;
    static float FillNumber()//Declaration of method utilized to fill an array/list of                              floating point numbers.
     {
       int counter = 0;
       List<float> floatlist = new List<float>();
       char sentinel;
       Console.WriteLine("I would like you to now input a few floating point numbers.\n                           Enter q to quit.");
       Console.WriteLine("You have the option to quit now.\nWould you like to continue? \nEnter q to quit.");
       sentinel = char.Parse(Console.ReadLine());
        while (sentinel != 'q')
         {
          Console.WriteLine("You have the option to quit now.\nWould you like to  continue?\nEnter q to quit.");
          sentinel = char.Parse(Console.ReadLine());
          Console.WriteLine("Then please input a floating point number.");
          floatlist[counter] = float.Parse(Console.ReadLine(floatlist[counter]));
          counter++;
          return floatlist;
          return counter;
         }

     }
    static float CalcSum(List<float> floatlist, int counter)//Declaration of method  used to add all entered numbers together and calculate the total sum.
     {
      for (; counter >= 0; counter--)
       {
        float sum = sum + floatlist[counter];
       }
       return sum;
     }
    static float CalcAver(float sum, float aver, int counter)//Declaration of method used to calculate the average of numbers entered.
     {
      aver = sum / counter;
      return aver;
     }

    static void Main()//Where execution of program begins. Introduces user to program. Prompts for user input and calls all subservient methods.
     {
      FillNumber();
      CalcSum();
      CalcAver();
      Console.WriteLine("The total number of floating point numbers entered is:" +  counter);
      Console.WriteLine("The total sum is:" + sum);
      Console.WriteLine("The average of the numbers entered is:" + aver);
      Console.ReadLine();
     }
  }
}

These are my errors: 9
Error 1 No overload for method 'ReadLine' takes 1 arguments
Error 5 No overload for method 'CalcSum' takes 0 arguments
Error 6 No overload for method 'CalcAver' takes 0 arguments
Error 2 Cannot implicitly convert type 'System.Collections.Generic.List' to 'float'
Error 3 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.sum'
Error 8 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.sum'
Error 7 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.counter'
Error 9 An object reference is required for the non-static field, method, or property 'P1_Wilson.P1_Wilson.aver'
Error 4 'sum' conflicts with the declaration 'P1_Wilson.P1_Wilson.sum'
I apologize if my one lame attempt at humor served more to anger instead of to kindly engender chuckles.
Comment: First off all, you defined CalcSum and CalcAver to take in parameters, but didnt pass any.
Answer: Read your error messages one by one and fix them, for example :

Error 1 No overload for method 'ReadLine' takes 1 arguments
This error message is not ambiguous, specifically when Visual Studio should point you to the exact point in code where it occurs.
In that case it is :
Console.ReadLine(floatlist[counter]);

Please try to fix your errors one by one by carefully reading the error messages (and googling them if needs be) and come back if you struggle with a specific error or if you would like a code review when the code is running.


Please help me to understand the solution of this problem

Question: Could anybody help me to understand the solution?
$\textbf{Problem:}$Proof that $\sup(A) = \sqrt{2}$,$~~$where $A = \lbrace x \in \mathbb{Q}: x > 0, x^2 < 2 \rbrace$
For proving the right-hand side of the inequality, it says that $s$ is rational or irrational. In the irrational case, how does he find $w$?
Answer: If $s$ is irrational (in fact, also if $s$ is rational - so there is not really a need to distinguzish the cases), we can certainly find a rational number $w$ with $s<w<s+\frac 1n$. Indeed, if we only consider numbers of the form $\frac k{n+1}$, at least one of these will be in the desired interval (simply because the distance between consecutive candidates is shorter than the interval length). More formally, we wnat to find an integer $k$ with $s<\frac k{n+1}<s+\frac 1n$ or equivalently with $$(n+1)s<k<(n+1)s+\frac{n+1}n=(n+1)s+1+\frac1n.$$ One can simply let $k=\lfloor (n+1)s+1\rfloor =\lfloor (n+1)s\rfloor +1 $ because that makes $k$ an integer with, by definition,
$$ (n+1)s<k\le  (n+1)s+1.$$
Comment: Well done. I have another question: When we construct $w$, how do we make a contradiction? I mean why $(s + 1/n)^2 < 2$? because $s$ is an irrational number.


Does the double integrative of d^{2}x make sense from a mathematical point of view?

Question: $\mathbf{SHORT}$: what is the result of $\iint{d^2x}$? Does it make sense from a mathematical point of view? Please note that I am not refering to $\iint{dx^2}$.
$\mathbf{LONG}$
I came to this doubt while solving the differential equation of a LC circuit (voltage source, inductor, and capacitor in series).
$$V_{in}(t)=V_C(t) + V_L(t)=\frac{1}{C}\int{i(t)dt}+L\frac{di(t)}{dt}\tag{1}$$
Where $L$ and $C$ are the constants of the inductor and capacitor respectively. Assuming $V_{in}(t) = 0$, and differentiating respect to $t$ both sides we obtain:
$$L\frac{d^2i(t)}{dt^2}+\frac{1}{C}i(t)=0$$
Or in standard differential equation form:
$$\frac{d^2i(t)}{dt^2}+\frac{1}{LC}i(t)=0$$
Now, I DO know how to solve this as a differential equation, that is not my doubt. However, alternatively, if I rearrange the terms:
$$\frac{d^2i(t)}{i(t)}=-\frac{1}{LC}dt^2\tag{2}$$
$$\iint{\frac{d^2i(t)}{i(t)}}=-\frac{1}{LC}\iint{dt^2}=-\frac{1}{LC}\int{(t+C_1)dt}=-\frac{1}{LC}\left({\frac{t^2}{2}+C_1t+C_2}\right)\tag{3}$$
As you can see, the right part of $(3)$ can be easily solved since $\int{dx}=x$ and $\iint{dx^2}=\int{\left(\int{dx}\right)dx}$. However, when it comes to the left side of the equation, I don't know how to proceed. I have read somewhere that the term $d^2x$ does not make sense by itself, and that $\frac{d^2x}{dt^2}$ is just some form of notation to refer to $x''(t)$. But I don't buy it, because in the following case:
$$\frac{dx}{dt}=x$$
Solving this is as simple as multiplying both sides by $\frac{dt}{x}$ and integrating:
$$\int{\frac{dx}{x}}=\int{dt} \Rightarrow ln|x|=t+C_1 \Rightarrow x=x(t)=e^{t+C_1}$$
In this case, we did operate with the two terms $dx$ and $dt$ by considering them as differentials. Then, there must be a way I believe there might be a way of solving $\iint{d^2x}$, and consequently also $\iint{\frac{d^2x}{x}}$ as in equation $(3)$.
By the way, feedback on my question is happily accepted, since is my first question on math stackexchange.
Comment: Your claim "there must be a way" is simply not true. See https://math.stackexchange.com/questions/27425/what-am-i-doing-when-i-separate-the-variables-of-a-differential-equation for what the manipulations for first-order separable PDEs really mean. Separating $d^2 i$ and $dt^2$ makes no sense at all.
Comment: Yeah, with "there must be a way" I didn't mean "the previous example implies that this is also possible", but rather "my intuition tells me there must be a way". Thanks for the advice and the link.
Comment: Well the definition of derivative is the limit of a fraction, which can be expressed as the fraction of two limits, where each limit corresponds to each differential (numerator and denominator), right?
Answer: The derivative $\frac{dy}{dx}$ looks like it's a fraction, and in many cases behaves like it was a fraction, but it's important to remember that...
$~~~~~~~~~~~~~~$
The trick you have been thought for solving first order ODEs simply does not extend to higher order ODEs. This is a common misconception and it's important to learn the limitations of this trick.
To give you an answer beyond "this simply does not work" let's go through the reason why it works to "multiply by ${\rm d}t$" for first order ODEs and then show what happens for a second order ODE.
Given $$\frac{dy}{dt} = y$$
we divide by $y$, multiply by $dt$ and integrate to get
$$\int \frac{{\rm d}y}{y} = \int {\rm d}t \implies \log(y) = t + c\implies y = C e^t$$
The rigorous way of doing this is to divide the ODE by $y$ (assuming $y\not=0$) and integrate the ODE using the fundamental theorem of calculus and the chain rule on the left hand side which allows us to write
$$\int \frac{1}{y}\frac{dy}{dt}{\rm d}t = \int \frac{d\log y}{dt}{\rm d}t = \log(y) + C$$
which is the same we would get if treated $\frac{dy}{dt}$ as it was a fraction. Now if we try to do the same procedure (the rigorous one) on the second order ODE $\frac{d^2y}{dt^2} = y$ then we get
$$\int \frac{1}{y}\frac{d^2y}{dt^2}{\rm d}t = \int {\rm d}t \implies \int \frac{d(y')}{y} = t + c$$
Now we see the problem here. In order to solve the integral $\int \frac{dy'}{y}$ we would need to know $y$ as a function of $y' \equiv \frac{dy}{dt}$. But this is not known to us unless we already know the solution we are trying to find. There is simply not enough information about $y$ available to us at this stage to be able to solve this integral which shows that this way of solving the ODE does not work like it did in the first order case.
There are many other examples of where treating the derivative as a fraction fails. One that comes to mind comes from the implicit function theorem where we have an equation $F(x,y(x)) = 0$ and can deduce $\frac{dy}{dx} = -\frac{\partial F/\partial x}{\partial F/\partial y}$ (notice the minus sign which is not there is we treat the right hand side derivatives as fractions). For more information see for example When not to treat $dy/dx$ as a fraction in single-variable calculus? and Is $\frac{\textrm{d}y}{\textrm{d}x}$ not a ratio?
Comment: I still think that the notation dy/dt may lead to a lot of mistakes when you're not familiar with what it really means, and on the other hand y' only makes sense when you know that y=y(t). In more complex problems it would not be possible to use the y' notation since each variable might be differentiated over a different variable.
Comment: Your answer clarified a lot to me. I see now that the (rigorous, as you call it) operation even for 1st order ODEs is actually integrating over the same variable both sides, hence same differential appears (dt), and by undoing the chain rule it's why we have the ln(y) as a result. I actually thought it was about "moving things around" and WHEN having all differentials in place, THEN just integrating both sides (and by this I thought just add the integration operator). Your answer gave me a lot of insight, thanks.
Answer: From the point of view of differential forms it does makes sense.
The theory of differential forms gives meaning to what the expression $dxdydz$ could mean. In the language of this theory $d^2x=ddx=0$. So the result of $\int\int d^2x=0$ whereas $\int\int dx^2=\int \int 2xdx$.
In attempt to explain things in a very narrow way, in the study of differential forms, you the operator $d$ which differentiates expresions like $ω=xdx+e^zdy$ which are called differential forms. From the aximatic properties of this operator one gets that for every form $ω$ we have $ddω=0$.
If you would like a really approachable introdction to the subject try David Bachman's book: A geometric approach to differential forms.
Comment: It still doesn't make any sense when it comes to solving the ODE in the question (as in equation (2)).
Comment: Thanks, I will definitely check that one out.
Answer: Personally it depends by what you mean by $d^2x$ I have two way of seing this
I you are talking about one-dimensional integral then I think double integral is not appropriate .
My guess will be the following conjecture. let start with elementary case
assume $f$ is twice differentiable thereof I guess by double integral you meant (which will an appropriate conjecture to your question in my opinion)
$$\iint_a^b f''(x)d^2x = f(b)-f(a)$$
as for one integral we have $$\int_a^b f'(x)dx = f(b)-f(a)$$
I personally never came across such notation in mathematics. But you really need to define your object $$\iint_a^b [..]d^2x = ?$$
the second meaning of $d^2x$ could be $dx\cdots dx$ seen as a double integral. therefore this mathematically is senseless
Indeed, the notation $dxdxy$ is the surface element notation of the exterior product $dx \hat{}dy $ (this is very closed to differential geometric ). However, the known properties of this is that it is antisymmetric that
  $dx \hat{}dx= 0 $ and hence we would have $d^2x= dxdx= 0$ a
and this make your formulation trivial .
So a good guess could be the aforementioned formula with second derivative namely,
$$\iint_a^b f''(x)d^2x = f(b)-f(a)+ $$
Nevertheless this formulation  has some well-postness issue namely, we have
$$\iint_a^b f(x)d^2x = F(b)-F(a)$$ where $F''=f$
in fact one could take $F_1(x) =F(x) + kx+d$ we still have
$F_1''(x) =F''(x) =f(x) $ but
$$F(b)-F(a) +k(b-a)= F_1(b)-F_1(a)= \iint_a^b f(x)d^2x= F(b)-F(a). $$
this brings $k(b-a) =0$ which not necessary true.


Biased random walk away from cliff

Question: A drunken probabilist stands $n$ steps from a cliff's edge. He takes random steps, either towards or away from the cliff, each step independent of the past. At any point, the probability of taking a step away is $2/3$, or a step toward, $1/3$. What are his chances of eventually falling off the cliff?
The textbook has no answer. This is how I did it:
Let $p(i)$ represent the probability of death if you start $i$ steps from the cliff. I first start with the case where $i=1$. Clearly, $$p(1)=\frac{1}{3} + \frac{2}{3}p(2)$$ and $p(2)=(p(1))^2$ so we have the equation $$2(p(1))^2 + 1 - 3(p(1))=0$$ which we can easily solve.
Then to get the case where $i=n$ simply raise $p(1)$ to the $n^\text{th}$ power.
Is this correct? It seems a bit counterintuitive, since it seems as if no matter how far away the drunkard gets, sooner or later some fluke of chance will send him walking straight and steady down the cliff, with probability $1$.
Comment: That too is an old problem, not with cliffs, but stated as a gambling problem. You can google *Gambler's Ruin*. Two gamblers start out with fortunes $A$ and $B$, and play repeatedly a game in which the one who starts with $A$ has probability $p$ of winning a dollar. When one of them is broke, the game enda. We want the probability $A$ ultimately goes broke. The problem was already studied (and solved) in the $17$th century, when real probability theory started.
Comment: It's not that bad. In fact the probability is not $1$ as long as the probability of a step away is $\gt 1/2$. It is $1$ at $1/2$, no matter what $n$ is.
Comment: Hmm. So if the probability is exactly 1/2, then the drunkard is bound to eventually run off the cliff, no matter how ridiculously far he starts?

An interesting question might be having two cliffs with, say, 100km between, and placing the drunkard at a position in between, and betting on which side the drunkard falls down first.
Comment: Note the quadratic equation has two solutions, so $p(1)$ is either $1/2$ or $1$. How do you decide?
Answer: A start. Let $p_1,p_2,p_3,\dots$ be the probabilities of (ultimate) disaster if we start $1,2,3,\dots$ paces from the cliff edge. Then, as you wrote, $p(1)=\frac{1}{3}+\frac{2}{3}p_2$.
Similarly, if $k\ge 2$, then
$$p_k=\frac{1}{3}p_{k-1}+\frac{2}{3}p_{k+1}.\tag{$1$}$$
You can also fit the first equation into this pattern, by defining $p_0$ to be $1$.
Equation $(1)$ is a linear second-order recurrence. You can solve it by general techniques for such recurrences, either generating functions or by working with the characteristic equation. You can also solve the recurrence by ad-hoc techniques. For Equation $(1)$ can be rewritten as
$$\frac{2}{3}(p_{k+1}-p_k)=\frac{1}{3}(p_k-p_{k-1}).$$
So if $a_k=p_{k+1}-p_k$, then $a_k$ satisfies a very simple recurrence, for which you can find an explicit solution.
Answer: I am not quite sure what you are doing above, but here's how I did it.
The person will fall off if he takes n+1 steps forward. Let's start with looking at the cases by which the man can take n+1 steps forward.

Takes all n+1 steps forward. Probability = (1/3)^(n+1)
Takes n+2 steps forward and 1 step backward. Probability = (1/3)^(n+2)*(2/3)
Takes n+3 steps forward and 2 steps backward. Probability = (1/3)^(n+3)*(2/3)^2
Takes n+4 steps forward and 3 steps backward. Probability = (1/3)^(n+4)*(2/3)^3
...

So the probability that the man jumps off will be the sum of this infinite series.
Which comes out to (9/7)*(1/3)^(n+1)

Biased random walk away from cliff


Find which program is replacing my resolv.conf file

Question: I use network-manager on Debian 8. My config contains some custom DNS servers, so my /etc/resolv.conf file generated by network-manager looks like this:
# Generated by NetworkManager
search rudloff.pro
nameserver 188.8.131.52
nameserver 126.96.36.199
nameserver 2a00:5881:8100:1000::3

This is perfectly fine but after a few minutes, the resolv.conf file is replaced by this:
nameserver 2a01:e00::1
nameserver 2a01:e00::2

(Those are my ISP DNS servers, which are sent by the DHCP server.)
I have no idea what is replacing this file.
Do you have any idea what could do that? Is there a way to see which process edited the file?
Answer: Both network(mis)manager and resolvconf (only dns) can change network settings and/or dns settings (for example change the /etc/resolv.conf file as you noticed).
Though handy on a laptop which sees a lot of different (wireless) networks it is of limited practical use on servers and can even bite you, rendering the server without connectivity (say if someone accidentally or purposely adds a dhcp server on the network, suddenly network(mis)manager may decide to grab an IP address from there). If you run a server you have little use for these packages and it may be best to remove them and configure networking by hand. That way you will be sure the configuration remains consistent and unchanged.
To fix:
apt-get --purge remove resolvconf network-manager

This will not remove files such as /etc/resolv.conf and /etc/network/interfaces which you can edit by hand to create your own stable network configuration.
I did this as a rule when setting up a new server, or when I took over administration of a server and removal was appropriate (in 99% of cases).
Comment: I think that this is good advice in most cases, but here I like to use nmcli in order to easily manage VPN connections.
The really strange thing is the resolvconf package is not installed on this system so I really don't see what program is editing the file...
Comment: You should install auditd and set it to watch the /etc/resolv.conf file. You can add a watch on the file by simply running auditctl -w /etc/resolv.conf -k resolv-conf -p rwxa and once it's been modified by running ausearch -f /etc/resolv.conf to see what modified the file. Logs should be available under /var/log/audit/
Answer: Here is the solution I found:

Install and enable resolvconf
Edit /etc/resolvconf/interface-order and give NetworkManager a high priority

I still don't know what was messing with my resolv.conf file but at least now the one generated by network-manager is used.


Next.js _app and _document use?

Question: I'm totally new with next.js and I need your help for something I guess really basic but I cannot find my mistake or an explanation, I found nothing on the internet about it, so here I am :
Everything works when I create a file in the pages folder(I mean every file in pages folder is ok except _app.js or _document.js), I can reach the URL, but I would like to use context, layout or authentification in the future and I need to use the _app and _document override cool things but I can write anything I want in it, it seems my _app.js or _document.js are just useless, never called or I don't know but they just never work.
I tried on 2 projects, here is what I do according to the next documentation :
first, npx create-next-app to create the project, and then add an _app.js for example in pages folder and add :
import React from 'react'
import App from 'next/app'
import Nav from '../components/nav'

class MyApp extends App {
  // Only uncomment this method if you have blocking data requirements for
  // every single page in your application. This disables the ability to
  // perform automatic static optimization, causing every page in your app to
  // be server-side rendered.
  //
  // static async getInitialProps(appContext) {
  //   // calls page's `getInitialProps` and fills `appProps.pageProps`
  //   const appProps = await App.getInitialProps(appContext);
  //
  //   return { ...appProps }
  // }

  render() {
    const { Component, pageProps } = this.props
    return (
      <>

        <Component {...pageProps} />
      </>
      );
  }
}

export default MyApp

Anybody could tell me what I am doing wrong?
Comment: Hi again @SamiAhmedSiddiqui thank you for answering, I don't really know why but today everything work... even when I undo every last changes and retry what I sent here, and I had the same issue on 2 different computers, so I really don't get it... Thank you very much for your help and if I finally find out why it didnt work and why now it is working I will post the reason here. Thank you !
Comment: What is the issue you are facing? As per your code, you are adding `` in the render. Does it not working?
Comment: Hi Sami, thank  you for your  answer. Indeed, it  does  not  work  and  I still  dont  know  why. Same  on an  other  project, nothing  appearing. Would  you  have  any  idea  ?
Comment: Hi @AnaiO Have you tried this in `_document.js`. If yes, then what you have tried there. Also, please share your `../components/nav` code.
Answer: Well, if anybody is going through the same issue, I found what was going on, in fact, after creating for the first time _app.js, I have to restart my docker container, or restart my app with yarn next dev if I want to see the changes or they never appear. I am going to look for more explanations on how SSR and next.js more globaly exactly work to understand their behaviour on this point. Good luck all !
Comment: Yes. In fact you have to rebuild the codes with next so that it takes `_app.js` changes into consideration.

Next.js _app and _document use?