Convexity and integrands. Simple proof desired

The following result is well-known:

Suppose that $ H(x,y)$ is a log-concave distribution for $ (x,y) \in \mathbb R^{m \times n}$ so that by definition we have

$ $ H \left( (1 – \lambda)(x_1,y_1) + \lambda (x_2,y_2) \right) \geq H(x_1,y_1)^{1 – \lambda} H(x_2,y_2)^{\lambda},$ $

and let $ M(y)$ denote the marginal distribution obtained by integrating over $ x$

$ $ M(y) = \int_{\mathbb{R}^m} H(x,y) \, dx.$ $

Let $ y_1$ $ y_2 \in \mathbb R^n$ and $ \lambda \in (0,1)$ be given. Then the Prékopa–Leindler inequality applies. It can be written in terms of $ M$ as

$ $ M((1-\lambda) y_1 + \lambda y_2) \geq M(y_1)^{1-\lambda} M(y_2)^\lambda$ $ which is the log-concavity for $ M$ .

Now, I wanted to understand this for a very simple example where $ f: \mathbb R^2 \rightarrow \mathbb R:$

$ $ e^{-g(y)} = \int_{\mathbb R} e^{-f(y,z)} \ dz.$ $

Then, I want to prove that $ g”\ge 0$ if $ f$ satisfies $ D^2f > 0$ globally as a matrix. We assume for simplicity that $ f$ is such that the above integral is well-defined.

It is easy to see that

$ $ g”(y) = \langle D_{yy}f \rangle_z – \operatorname{ Var}_z (D_{y}f)$ $

where is the expectatio $ \langle F \rangle_z(y) := \int_{\mathbb R} F(y,z) e^{-f(y,z)} \ dz / \int_{\mathbb R} e^{-f(y,z)} \ dz$

and $ \operatorname{ Var}_z$ is the variance with respect to the above probability measure.

However, it is not at all clear to me from this representation why $ g”\ge 0$ holds.

Is there a pedestrian way to see this from the above expression for the second derivative.

Simple ring/circular buffer c++ class V3

The Original Post (v2)

As stated in the previous post, i’m looking for feedback on the updated version of the code posted.

A few things specifically I’m looking for feedback on, are:

  • I switched to using the std::aligned_storage as suggested in the previous post, but on the cppreference.com – std::aligned_storage page, in the examples it says // note: needs std::launder as of C++17 above the reinterpret_cast‘s. Would that mean, that the launder function should just wrap the cast, and if so, it states that its needed for c++17, which is what I’m using, but I’d also like the code to be compatible back to c++11. What would be the recommended approach in this situation?

  • I was considering making a private function, something like:

    #include <new> // ... [[nodiscard]] constexpr const T* ptr_to(std::size_t pos) const {     return std::launder(reinterpret_cast<const T*>(&data[pos])); } 

    to remove some of the code duplication, I’m still trying to gain a better understanding of const correctness, would I need a const version and a non-const version of this function, similar to the peek function?

  • Is there any reason to reinterpret_cast to T* rather then const T* within this class?

  • Like I mentioned in a previous point, I’m wanting to target c++17 primarily, but also be backward compatible down to c++11. Language features such as [[nodiscard]] and std::launder are c++17 only, is there a standard way(using macros or otherwise) to accommodate for this?

  • The function void push(const T& item) noexcept takes a const ref and uses std::move internally on it, is that reasonable? or should that only be done to params such as T&& item? Should I just delete the std::move in that function?

CircularBuffer.h

#pragma once  #include <cassert> #include <type_traits>  namespace datastructures {      template<class T, std::size_t N>     class CircularBuffer {          typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N];         std::size_t head = 0;         std::size_t tail = 0;         bool isFull = false;       public:         template<typename ...Args>         void emplace_push(Args&&... args) noexcept {             assert(!isFull && "Attempting to push item into full buffer!");              new (&data[head]) T(std::forward<Args>(args)...);              head = ++head % N;             isFull = head == tail;         }          void push(const T& item) noexcept {             assert(!isFull && "Attempting to push item into full buffer!");              new (&data[head]) T(std::move(item));              head = ++head % N;             isFull = head == tail;         }          T pop() noexcept {             assert(!is_empty() && "Attempting to pop item from empty buffer!");              auto ptr = reinterpret_cast<T*>(&data[tail]);             auto result = std::move(*ptr);             ptr->~T();              tail = ++tail % N;             isFull = false;              return result;         }          [[nodiscard]] constexpr T& peek() noexcept {             assert(!is_empty() && "Attempting to peek in empty buffer!");              return *reinterpret_cast<T*>(&data[tail]);         }          [[nodiscard]] constexpr const T& peek() const noexcept {             assert(!is_empty() && "Attempting to peek in empty buffer!");              return *reinterpret_cast<const T*>(&data[tail]);         }          [[nodiscard]] constexpr bool is_empty() const noexcept {             return !isFull && tail == head;         }          [[nodiscard]] constexpr std::size_t get_capacity() const noexcept {             return N;         }          [[nodiscard]] constexpr std::size_t get_size() const noexcept {             if (isFull)                 return N;              if (head >= tail)                 return head - tail;              return N + head - tail;         }     }; } 

Python program for a simple calculator

I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.

Here is my code:

# This function adds two numbers  def add(x, y):    return x + y  # This function subtracts two numbers  def subtract(x, y):    return x - y  # This function multiplies two numbers def multiply(x, y):    return x * y  # This function divides two numbers def divide(x, y):    return x / y  print ("Select operation.") print ("1. Add") print ("2. Subtract") print ("3. Multiply") print ("4. Divide")  choice = input("Enter choice (1/2/3/4): ")  num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: "))  if choice == '1':    print(num1, "+", num2, "=", add(num1,num2))  elif choice == '2':    print(num1, "-", num2, "=", subtract(num1,num2))  elif choice == '3':    print(num1, "*", num2, "=", multiply(num1,num2))  elif choice == '4':    print(num1, "/", num2, "=", divide(num1,num2)) else:    print("Invalid input") 

So, I would like to know whether I could make this code shorter and more efficient.

Also, any alternatives are greatly welcome.

Any help would be highly appreciated.

Simple ring/circular buffer c++ class V2

The Original Post (v1)

I’m looking for feedback on the updated version of the code posted at the link above.

#pragma once  #include <memory> #include <cassert> #include <type_traits>  namespace datastructures {      template<class _Ty, size_t _Size>     class CircularBufferv2 {          // uses char as type to prevent default _Ty initialization.         alignas(alignof(_Ty)) char buffer[_Size * sizeof(_Ty)];         size_t head;         size_t tail;         bool isFull;      public:         constexpr CircularBufferv2() noexcept :             buffer{0},             head{0},             tail{0},             isFull{false} {         }          void push(const _Ty& item) noexcept {             assert(!isFull && "Attempting to push item into full buffer!");              new (&buffer[head * sizeof(_Ty)]) _Ty(std::move(item));              head = ++head % _Size;             isFull = head == tail;         }          _Ty pop() noexcept {             assert(!is_empty() && "Attempting to pop item from empty buffer!");              auto location = reinterpret_cast<_Ty*>(&buffer[tail * sizeof(_Ty)]);             auto result = std::move(*location);             std::destroy_at(location);              tail = ++tail % _Size;             isFull = false;              return result;         }          _NODISCARD constexpr _Ty& peek() noexcept {             assert(!is_empty() && "Attempting to peek in empty buffer!");              return *reinterpret_cast<_Ty*>(&buffer[tail * sizeof(_Ty)]);         }          _NODISCARD constexpr const _Ty& peek() const noexcept {             assert(!is_empty() && "Attempting to peek in empty buffer!");              return *reinterpret_cast<_Ty*>(&buffer[tail * sizeof(_Ty)]);         }          _NODISCARD constexpr bool is_empty() const noexcept {             return !isFull && tail == head;         }          _NODISCARD constexpr size_t get_capacity() const noexcept {             return _Size;         }          _NODISCARD constexpr size_t get_size() const noexcept {             if (isFull)                 return _Size;              if (head >= tail)                 return head - tail;              return _Size + head - tail;         }          _NODISCARD _CONSTEXPR17 _Ty* data() noexcept {             return buffer;         }          _NODISCARD _CONSTEXPR17 const _Ty* data() const noexcept {             return buffer;         }     }; } 

I want to take advantage of all of the new features(c++17) while also supporting older compilers(preferably all older compilers but c++11 is probably as old as i’ll actually be compiling for). Any suggestions welcome. (I’m attempting to use this class as an example class to follow when constructing other classes.)

Also, the use of _CONSTEXPR17 on the data functions I was wondering why use the macro vs just a constexpr? (I based the use of macros around the std::array struct, its data function uses _CONSTEXPR17 rather than just constexpr.)

Simple REST Base Web Server with Unit Tests

I am building out a simple web server in Go. My goal is to expand on this framework in a different application I am building.

Here is my github repo https://github.com/jmacnc/gowebserver

Is what I have here using best practices?

I am specifically looking for feedback on the tests, and how I am connecting to different databases (testing and main application). As seen below…

//Handler for posting a new user func (d *MongoDB) PostUser(w http.ResponseWriter, r *http.Request) {     w.Header().Set("Content-Type", "application/json")     //Retrieving request body     var user User     _ = json.NewDecoder(r.Body).Decode(&user)     //Posting Company     err := d.PostUserToDB(user)     //Error Handling     if err != nil {         fmt.Println(err)         w.WriteHeader(500)     } }  //Populating a new user in the database func (d *MongoDB) PostUserToDB(user User) error {     _, err := d.db.Collection("users").InsertOne(context.Background(), user)     if err != nil {         return err     }     return nil }  func main() {     //Connects to the database     d , _ := ConnectToDB()     //Creates mux router/multiplexer     r := mux.NewRouter()     //Handle Functions     r.HandleFunc("/user", d.PostUser).Methods("POST")     //Starts web server     //Prints a string saying that the app is running...     fmt.Println("Application Running...")     log.Fatal(http.ListenAndServe(LOCALHOST, r)) } 

How to apply INAR model to a simple time series model in Python

As a course project for Time Series Analysis, I used ARIMA for a very simple model – (Analyzing number of deaths in each episode of game of thrones and forecasting the number of deaths in the final episode), thus there wasn’t as much data for this. I have been asked to redo it using INAR model. I was wondering if that could be achieved using ARIMA and applying zero for the MA and lag part, which would just give it AR. But I’m confused as to how to make it Integer valued. I need this done in Python and was wondering if there is a model out there for this.

This is the code I used for forecasting but I’m sure INAR is more than this.

#Prediction     model = ARIMA(df, order=(15, 0, 0))     model_fit = model.fit(disp=False)     prediction = model_fit.forecast()[0]     print(prediction) 

How to create a simple improvement version of “hover and change” in JavaScript?

I’m doing a JavaScript function which is to hover anyone of the <a> elements and change the <img> src and <p> accordingly.

I am practicing and learning JavaScript. So I have create a super simple JavaScript function code.

function onHover() {      var pistiProducts = [         "https://temp1.asign.pro/wp-content/uploads/2019/05/test-1.jpg",         "https://temp1.asign.pro/wp-content/uploads/2019/05/test-2.jpg"     ];      var replace = document.getElementById("replacement");         var itemdec = document.getElementById("text-replacement");      replace.src = pistiProducts[1];         itemdec.innerHTML = "Test 1";  } 

In my HTML:

<div class="dropdown-menu-wrapper d-flex">                                                  <div class="dropdown-item-wrapper flex-grow-1">                                                     <a id="pisti-products" onmouseover="onHover();" class="pisti-products" href="#">Action</a>                                                        <a class="" href="#">Another action</a>                                                           <a class="" href="#">Something else here</a>                                                              <a class="" href="#">Something else here</a>                                                              <a class="" href="#">Something else here</a>                                                              <a class="" href="#">Something else here</a>                                                              <a class="" href="#">Something else here</a>                                                          <a class="" href="#">Something else here</a>                                                              <a class="" href="#">Something else here</a>                                                          <a class="" href="#">Something else here</a>                                                          <a class="" href="#">Something else here</a>                                                          <a class="" href="#">Something else here</a>                                                          <a class="" href="#">Something else here</a>                                                    </div>    <div class="dropdown-display-wrapper">                                                          <div class="display-img replacement">                                                                  <img id="replacement" class="w-100 img-fluid" src="https://temp1.asign.pro/wp-content/uploads/2019/05/test-1.jpg" alt="">                                                            </div>                                                            <p class="mb-0 w-100 pisti-title" id="text-replacement">Another action</p>                                                      </div>                                                  </div> 

Currently what I will do is I will write 13 function and set the onmouseover="" to the relevant one. But I don’t think this is a best solution because I have more to do something like this.

As you can see my JavaScript code included Array. But I have no idea what can be done with array. 🙁

I need help to suggest me the best and easy solution. Please suggest me in JavaScript code instead of jQuey. I’m not good with basic JavaScript syntax and structure.

Simple explanation for the iterative version of extended Euclidean algorithm?

pair<int, pair<int, int> > extendedEuclid(int a, int b) {     int x = 1, y = 0;     int xLast = 0, yLast = 1;     int q, r, m, n;     while(a != 0) {         q = b / a;         r = b % a;         m = xLast - q * x;         n = yLast - q * y;         xLast = x, yLast = y;         x = m, y = n;         b = a, a = r;     }     return make_pair(b, make_pair(xLast, yLast)); }  int modInverse(int a, int m) {     return (extendedEuclid(a,m).second.first + m) % m; } 

I don’t understand what’s happening inside the while loop, especially lines 8-12.

simple one variable probability question

A Lego shop is open between 10-18.00.

question ‘a’: At the 15.th of December last year, 16 Star Wars lego was sold. What’s the probability that between 10.00 and 12.00 more than five legos were sold(on that day)?

question b: Supposed, that this was an average day before Christmas, what’s the probability that between 10.00 and 12.00 more than five legos were sold at any given day?

For question ‘a’, I tried to use Poisson distribution, with an expected value of E=2, based on the opening time and our two hour long time interval. I get 0.964 as a result, which I don’t find realistic.

For question ‘b’, I think think that this is a conditional probability, but what is the condition?

Thank you