real analysis – Doubt to an exercise from Terry Tao’s blog

I’ve been reading Tao’s An introduction to measure theory,a draft can be found here.An exercise from it is

Exercise 30 (Rising sun inequality) Let ${f: {bf R} rightarrow {bf R}}$ be an absolutely integrable function, and let ${f^*: {bf R} rightarrow {bf R}}$ be the one-sided signed Hardy-Littlewood maximal function

$displaystyle f^*(x) := sup_{h>0} frac{1}{h} int_{(x,x+h)} f(t) dt$.

Establish the rising sun inequality

$displaystyle lambda m( { f^*(x) > lambda } ) leq int_{x: f^*(x) > lambda} f(x) dx$

for all real ${lambda}$ (note here that we permit ${lambda}$ to be zero or negative).

I’ve prove it. But there it’s another exercise after it

Exercise 31 Show that the left and right-hand sides in Exercise 30 are in fact equal when ${lambda>0}$.

I tried to solve it and failed.
And I found that if we take $f=1_{(0,1)}$, and $lambda=frac{1}{2}$ then the left-hand side is $frac{1}{2}$ but the right-hand side is $1$, which are not equal.

Am I make any mistake?Please tell me.

Thanks in advance.

The solution for the exercise 1-22 from the book “The C programming language” K&R2

The exercise

My solution : https://github.com/AhmedAlaa-10/The-C-programming-language.-k-R-2-solutions-by-me/blob/main/Chap.%201/ex22.c

The key idea is that I process whitespace character by character while processing a sequence of non-blank characters block by block, i.e. I read a block then decide whether to print it in the current line or next line.


#include <stdio.h> 

#define LINE_MAX_SIZE 21        /* The maximum number of columns allowed in a single line */
#define IN_NON_BLANK_SEQ 1      /* Indicate that a sequence of non-blank character are being processed */ 
#define TAP_STOP_DIST 5

#define NON_BLANK(ch)   (ch != 't' && ch != 'n' && ch != ' ') 

int get_next_tap_pos(int current_column) {
    // columns numbered 0, 1, 2... there is a tap stop at 0, 5, 10, 15, 20
    return current_column / TAP_STOP_DIST * TAP_STOP_DIST + TAP_STOP_DIST; 
}

int main(void) 
{
    char block(LINE_MAX_SIZE+1);
    int column_pos = 0;                 /* Indicate the current column in the output where the next character will be printed*/
    int index_non_blank = 0;            /* Indicate the number of the non-blank char in the next non-blank char sequence */ 
    int state = !IN_NON_BLANK_SEQ;      /* Indicate whether a non-blank character is being processed */ 

    int ch; 
    while ( (ch = getchar()) != EOF) {
        if (NON_BLANK(ch)) {

            state = IN_NON_BLANK_SEQ; 
            if (index_non_blank == LINE_MAX_SIZE) {
                // There is a word bigger than the size of the line
                block(LINE_MAX_SIZE) = ''; 
                // Should I print it in the current line or in the next line ?
                // Our word is as big as our line. so if current line is not empty, we can't print it here
                if (column_pos != 0) 
                    putchar('n');
                printf("%sn", block); 
                column_pos = 0; 
                index_non_blank = 0;
                block(index_non_blank) = ch;  
            }
            else {
                block(index_non_blank) = ch; 
                ++index_non_blank; 
            }
        }
        else {
            // Is there a non-blank sequence that just finished ?
            if (state == IN_NON_BLANK_SEQ) {
                // Should the current word be printed in the current line or next line ?
                block(index_non_blank) = ''; 
                int expected_column_num = column_pos + index_non_blank; 
                if (expected_column_num <= LINE_MAX_SIZE) {
                    printf("%s", block); 
                    column_pos = expected_column_num; 
                }
                else {
                    putchar('n'); 
                    printf("%s", block); 
                    column_pos = index_non_blank; 
                }

                state = !IN_NON_BLANK_SEQ;  
                index_non_blank = 0; 
            }
            // now print the whitespace character and update column position 
            if (ch == 'n') {
                putchar(ch); 
                column_pos = 0; 
            }
            else if (ch == ' ' && column_pos < LINE_MAX_SIZE) {
                putchar(ch); 
                ++column_pos; 
            }
            else if (ch == 't' && column_pos < LINE_MAX_SIZE) {
                putchar(ch); 
                column_pos = get_next_tap_pos(column_pos); 
            }
            else {
                putchar('n');
                column_pos = 0;  
            }
        }
    }
}
```

Measure preserving transformation exercise – Mathematics Stack Exchange

im trying to solve this exercise but I need some hints because my teacher didn’t give me the theory necessary to solve it.

Let (X, M, µ) be a measurement space such that µ (X) = 1. Suppose
that T: X → X is measurable and µ (T^−1 (E)) = µ (E) for all E ∈ M. Prove that
(1) For all E ∈ M such that µ (E)> 0 there exists a natural n such that µ (E ∩
T^n (E))> 0. Here T^0 is the identity map in X and T^n = T ◦T^(n − 1) for
n ≥ 1.
(2) For every E the set of points for which there is a
natural n0 such that T^n(x) doesnt belong to E for all n ≥ n0 has measure 0.

Exercise 11.29 TOM M APOSTOL MATHEMATICAL ANALYSIS

Consider the following problem:

Prove that $int_{0}^{infty} frac{ cos ax}{ b^2 +x^2} dx= frac{ pi}{2b} e^{-|a| b}$.

I am not able to solve it but it seems that 11.27 (a) will be used which I have proved.

11.27 (a) If f satisfies the hypothesis of Fourier integral theorem then show that: (a) If f is even , ie f(-t)= f(t) for every t , then show that $frac{ f(x+) + f(x-) } {2} = (2/ pi ) lim alpha to infty int_{0}^{alpha} cos vx (int_{0}^{infty} f(u) sin (vu) du ) dv $.

Can you please help me using tthis result in the given question?

Thanks!

c – K&R 1-22 Folding Lines Exercise

I am currently reading and doing exercises from K&R. For exercise 1-22, I have the following solution. When I check my answer with other solutions online, I find that mine is generally shorter. Am I missing something? Any corrections are appreciated!

  1. Very long solution
  2. Very long solution 2
  3. Shorter solutions (some of the solutions at the top are around the same length as mine, but not generalized).

Exercise 1-22 Specifications: Write a program to “fold” long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.

#include <stdio.h>

#define LEN 20
#define TABSTOP 8
#define MAXLINE 1000

int get_line(char s(), int lim);

int main() {
    int len, nc;
    char line(MAXLINE);
    while ((len = get_line(line, MAXLINE)) > 0) {
        nc = 0;
        for (int i = 0; i < len; i++) {
            if (nc >= LEN) {
                putchar('n');
                nc = 0;
                if (line(i) != 't') putchar(line(i));
            } else putchar(line(i));
            if (line(i) == 't') nc += (nc + 1) % TABSTOP;
            else ++nc;
        } 
    }
}

int get_line(char s(), int lim) {
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != 'n'; ++i)
        s(i) = c;
    if (c == 'n') s(i++) = c;
    s(i) = '';
    return i;
}

Domain Driven Design Exercise – Software Engineering Stack Exchange

I recently found out about Domain Driven Design and I liked it. However, it is quite overwhelming and requires quite of expertise to get it right. For this reason, I wanted to try to model a simple domain using DDD and event storming.
The domain is the following:

The application allows publishers to publish small articles or books. Both publishers and users can browse, read, “pin” articles and “follow” more than one publisher to get notification about their new articles. Lets say that publishers are the same as users, with the additional functionality that they can publish.
Users have free access. Publishers have only a subscription based access. Users have an hard limit on the number of articles they can pin. However, this limit can be increased by buying a subscription. Publishers have an hard limit on the number of articles they can publish. However, this limit can be increased by buying an advanced subscription.

This is what I modelled till now and it is only a small part of it:

enter image description here

The Article Bounded Context contains a single aggregate Portfolio. The Portfolio holds the owner of the Portfolio, the created Articles entities and the ArticleQuotas ValueObject. To create an Article the Publisher has to go to the Portfolio, so that we can regulate the creation of new Articles. The Publisher can publish an Article of its Portfolio and the published Article will be visible in the PublishedArticle ReadModel. Finally, the PortfolioQuotas are regulated via events generated by the Subscription BoundedContext, by incrementing the PortfolioQuotas.
At first I was tempted to separate the concept of Article and Quotas, but then there is the problem of the eventual consistency between the creation of an Article and the Exceed of Quotas.

What I’m asking here is whether I’m going in the right direction and, otherwise, if you have some suggestions in modeling using Domain Driven Design.

Thank you very much

beginner – 2 Weeks into Go: Golang Tour WebCrawler Exercise

I’m on week 2 of learning go. I just completed the golang.org exercise on creating web crawler (https://tour.golang.org/concurrency/10) and I would please like feedback on my code. It feels overly complicated but I’m a noob so I don’t know.

I came across this post on the same exercies a few minutes ago while writing up this question. The only posted feedback there is one that I already implemented, so I’m hoping to get something different.

I also am not a fan of that implementation because it relies on knowing exactly how many urls will need to be fetched, which works with the fake data but wouldn’t work with real data.

type Fetcher interface {
    // Fetch returns the body of URL and
    // a slice of URLs found on that page.
    Fetch(url string) (body string, urls ()string, err error)
}

type FetchState struct {
    sync.Mutex
    fetchedUrls map(string)bool
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, state *FetchState) {
    if depth <= 0 {
        return
    }

    state.Lock()

    if _, ok := state.fetchedUrls(url); ok {
        state.Unlock()
        return
    }

    state.Unlock()
    body, urls, err := fetcher.Fetch(url)

    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Printf("found: %s %qn", url, body)
    state.Lock()
    state.fetchedUrls(url) = true
    state.Unlock()

    var wg sync.WaitGroup

    for _, u := range urls {
        wg.Add(1)
        go func(urlToCrawl string, group *sync.WaitGroup) {
            Crawl(urlToCrawl, depth-1, fetcher, state)
            group.Done()
        }(u, &wg)
    }

    wg.Wait()

    return
}

func main() {
    state := &FetchState{
        fetchedUrls: make(map(string)bool),
    }

    Crawl("https://golang.org/", 4, fetcher, state)
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map(string)*fakeResult

type fakeResult struct {
    body string
    urls ()string
}

func (f fakeFetcher) Fetch(url string) (string, ()string, error) {
    time.Sleep(1000 * time.Millisecond)

    if res, ok := f(url); ok {
        return res.body, res.urls, nil
    }
    return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
    "https://golang.org/": &fakeResult{
        "The Go Programming Language",
        ()string{
            "https://golang.org/pkg/",
            "https://golang.org/cmd/",
        },
    },
    "https://golang.org/pkg/": &fakeResult{
        "Packages",
        ()string{
            "https://golang.org/",
            "https://golang.org/cmd/",
            "https://golang.org/pkg/fmt/",
            "https://golang.org/pkg/os/",
        },
    },
    "https://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt",
        ()string{
            "https://golang.org/",
            "https://golang.org/pkg/",
        },
    },
    "https://golang.org/cmd/": &fakeResult{
        "Package cmd",
        ()string{
        },
    },
    "https://golang.org/pkg/os/": &fakeResult{
        "Package os",
        ()string{
            "https://golang.org/",
            "https://golang.org/pkg/",
        },
    },
}

algorithm – C++ Coding Exercise – Maximum unit to load into a truck given it size

You are assigned to put some amount of boxes onto one truck. You are given a 2D vector of box_types where box_type(0) is the number of a type of box and box_type(1) is the units per box for that type. You are also given an integer value for the truck size, this the maximum boxes you can put in the truck. Return the maximum unit that can be put in a given truck.

Example

input : box_types = {{1, 3}, {2, 2}, {3, 1}}
truck_size = 4

output: 8

Explanation:

There are

  • 1 box of type 0
  • 2 box of type 1
  • 3 box of type 2

where 0, 1, 2 is the index of the vector

You can take all the boxes of the first type, second type and one box from the third type

max_unit = (1 * 3) + (2 * 2) + (1 * 1) = 8

Here is my implementation

#include <iostream>
#include <algorithm>
#include <vector>

void sort_boxtypes(std::vector<std::vector<int>> &box_types)
{
    std::sort(
        box_types.begin(), box_types.end(), 
        ()(const std::vector<int>& a, const std::vector<int> &b)
        {return a(1) > b(1); }
    );
}
int maximum_units(std::vector<std::vector<int>> box_types, int truck_size)
{
    sort_boxtypes(box_types);
    int max_unit = 0;
    for(const auto& box_type : box_types)
    {
        truck_size -= box_type(0);
        if(truck_size >= 0)
            max_unit += box_type(0) * box_type(1);
        else
        {
            max_unit += (box_type(0) + truck_size) * box_type(1);
            return max_unit;
        } 
    }
    return max_unit;
}

int main()
{
    std::vector<std::vector<int>> box_types = {{5, 10}, {2, 5}, {4, 7}, {3, 9}};
    int max = maximum_units(box_types, 10);
    std::cout << max << 'n';
    
}


probability theory – Conditional Variance Exercise

This is a simple exercise on Conditional Variance that I’m trying to understand the proof of.

Let $X$ and $Y$ be two real-valued random variables such that $Y$ is square-integrable. We call the random variable $mathbf{E}left((Y-mathbf{E}(Y mid X))^{2} mid Xright)$ the conditional variance of $Y$ given $X$, denoted by $operatorname{Var}(Y mid X)$. Show that for all Borel measurable $f: mathbf{R} rightarrow mathbf{R}$ such that $f(X)$ is square-integrable,
$$
mathbf{E}left((Y-f(X))^{2}right)=mathbf{E}(operatorname{Var}(Y mid X))+mathbf{E}left((mathbf{E}(Y mid X)-f(X))^{2}right).
$$

Here is the solution, where I seem to be missing something simple.

We have
$$
begin{aligned}
mathbf{E}left((Y-f(X))^{2}right) &=mathbf{E}left(((Y-mathbf{E}(Y mid X))+(mathbf{E}(Y mid X)-f(X)))^{2}right) \
&=mathbf{E}left((Y-mathbf{E}(Y mid X))^{2}right)+2 mathbf{E}((Y-mathbf{E}(Y mid X))(mathbf{E}(Y mid X)-f(X))) \
&+mathbf{E}left((mathbf{E}(Y mid X)-f(X))^{2}right)
end{aligned}
$$

The first term in the last line equals $mathbf{E}(operatorname{Var}(Y mid X)),$ while the second term vanishes since $mathbf{E}(Y mid X)-f(X)$ is $sigma(X)$-measurable. The proof is complete.

Okay, but what does $mathbf{E}(Y mid X)-f(X)$ being $sigma(X)$-measurable have to do with anything? Why does it imply that $2 mathbf{E}((Y-mathbf{E}(Y mid X))(mathbf{E}(Y mid X)-f(X))) = 0$?

The Rust Programming Language Pig Latin Exercise

This is my implementation of the Pig Latin recommended exercise in The Rust Programming Language book. I am using the unicode segmentation crate to split the string into words while also keeping the delimiters. Any pointers on making this code more idiomatic or run more optimal?

use unicode_segmentation::UnicodeSegmentation;

#(allow(overlapping_patterns))
fn translate_word(s: &str) -> String {
  let mut it = s.chars();
  let first = it.next().unwrap();
  match first.to_ascii_lowercase() {
    'a' | 'e' | 'i' | 'o' | 'u' => format!("{}-hay", s),
    'a'..='z' => format!("{}-{}ay", it.collect::<String>(), first),
    _ => s.to_string(),
  }
}

pub fn translate(s: &str) -> String {
  s.split_word_bounds()
    .map(translate_word)
    .collect::<Vec<_>>()
    .join("")
}

The code is inside a module named pig_latin.