innodb – Nullable integer as part of composite primary key

I want to store phone numbers as integers and I’ve created this SQL:

DROP TABLE `user_id_phone`;
CREATE TABLE `user_id_phone`
(
    `user_id`      int     unsigned  NOT NULL,
    `country_code` smallint unsigned NOT NULL,
    `number`       bigint unsigned   NOT NULL,
    `ext`          smallint unsigned NULL,
    PRIMARY KEY (`country_code`, `number`, `ext`)    
) ENGINE = InnoDB

But my server (10.4.14-MariaDB) creates field ext as ‘NOT NULL’:

`ext` smallint(5) unsigned NOT NULL,

if ext is a part of the composite primary key:

PRIMARY KEY (`country_code`, `number`, `ext`) 

In case of ext is not a part of the primary key:

PRIMARY KEY (`country_code`, `number`),

the field DDL is right after creation:

  `ext` smallint(5) unsigned DEFAULT NULL,

Why?

command line – Creating a Function That Sets a Variable to a Random Integer

I am writing a shell script on my Linux machine, and I’m trying to figure out a good way to write a function that I could call that would set a variable, let’s call it $variable, to a random number between 1 and 466,550. Of course I could write;

shuf -i 1-466550 -n 1

And it’ll do the trick, but how could I write this in a function to have it set my variable, $variable, to that random number (until the function is called again, at which case it picks another random integer from 1-466,550)?

performance – Efficient loop over a integer range in Python

I want to search for positions inside a range of integers. How to improve the code in terms of efficiency, since both my search list and the ranges are very big:

#Range list with ids
range_lst = ((121000, 122000, 'foo'), (123456, 124557, 'bar'), (156789, 163659, 'egg'))
# Positions which we want to scan
pos = (123456, 369369)
# Neighbouring windows size
window_size = 10000

for p in pos:
    for r in range_lst:
        range_area = range(r(0), r(1))
        range_area_window = range(r(0)-window_size, r(1)+window_size)
        id = r(2)
        if p in range_area:
            print (p, id, 'exact hit!')
        else:
            # If we don't find an exact hit, we check the neighbouring region +- 10000
            if p in range_area_window:
                print (p, id, 'neighbour hit!')

scala – get sum of integer from array of objects in mongodb

I want to filter my documents by sum of decimal field in array of objects, but didn’t find anything good enough. for example I have documents like below:

(
    {
        "id": 1,
        "limit": NumberDecimal("100000"),
        "requests": (
            {
                "money": NumberDecimal("50000"),
                "user": "user1"
            }
        )
    },
    {
        "id": 2,
        "limit": NumberDecimal("100000"),
        "requests": (
            {
                "money": NumberDecimal("100000"),
                "user": "user2"
            }
        )
    },
    {
        "id": 1,
        "limit": null,
        "requests": (
            {
                "money": NumberDecimal("50000"),
                "user": "user1"
            },
            {
                "money": NumberDecimal("50000"),
                "user": "user3"
            }
        )
    },
)

description by documents fields:

  1. limit – maximum amount of money, that I have
  2. requests – array of objects, where money it’s how much money user get from limit (if user1 get 50000 money there remainder it’s 50000, limit – sum(requests.money))

I am making query in mongodb from scala projects:

  1. get all documents where limit equal to null
  2. get all documents where I have x remainder money (x like input value)

first case it’s more easy than second one, I know how I can get sum of requests.money: I am doing it by this query:

db.campaign.aggregate((
    {$project: {
        total: {$sum: ("$requests.money")}
    }}
))

scala filter part

Filters.or(
    Filters.equal("limit", null),
    Filters.expr(Document(s""" {$$project: {total: {$$sum: ("$$requests.money")}}}"""))
)

But I don’t want to store it and get as result, I want to filter by this condition x (money which I want to get by some user) limit >= sum(requests.money) + x. And by this filter I want to get all filtered documents.

Example:
x = 50000
and output must be like this:

(
    {
        "id": 1,
        "limit": NumberDecimal("100000"),
        "requests": (
            {
                "money": NumberDecimal("50000"),
                "user": "user1"
            }
        )
    },
    {
        "id": 1,
        "limit": null,
        "requests": (
            {
                "money": NumberDecimal("50000"),
                "user": "user1"
            },
            {
                "money": NumberDecimal("50000"),
                "user": "user3"
            }
        )
    },
)

c – Check if integer is a palindrome in base 10

Here is the solution->

//Write a program to check the number whether it is palindrome or not
#include <stdio.h>
int
main(void){

//Put variables for the further proceed
int number, quotient=1, remainder,i=0;

//To declare a character array
char text(100);

//To show the message to the user
printf("Enter an integer number :");

//Taking input from the user
scanf("%d",&number);

//For finding escape the integer number in the reverse order specifically
int number_update=number;

//To find out the integer number in the reverse order
  while(quotient!=0){
  quotient=number_update/10;
  remainder=number_update%10;
  number_update=quotient;
  text(i) = remainder + '0';//Converts integer to character and store to the array
  i++;
  }
 //Converts the string to a whole integer
  int result_of_reverse=atoi(text);

  //Check the result of reverse order with the given integer number
  if(result_of_reverse==number){

    //To display the result
    printf("This is a palindrome number");
  }
  else{

    //To display the result
    printf("This is not a palindrome number");
  }

  }

I want to achieve: How can I simplify my solution? Is there any better strategy should I follow to solve these types of problems?

immutability – Immutable String and Integer in Java: What is the point if assignment in effect changes the value?

First there is a difference between a Variable, and a referenced Object.

A variable is a slot in a scope for a piece of information. If that slot can never be changed you would have a constant, useful but limiting if everything were constant.

What makes that slot interesting is that the specific information in the slot can be changed. Which allows a function/program to change its behaviour.

Now the problem with slots is that they have to have a predetermined size when the scope they are in is created. That might be determined at compile time, or when the scope is created. But once created the size cannot be made bigger.

This is an issue for interesting types like strings, because we don’t want to allocate 2GB of space for a single character string. We would like to make an 80-character string longer say 85 characters, but if we weren’t prescient enough to allocate extra space we can not store it.

The heap to the rescue. The heap allows us to create slots at runtime of any size we desire. We can allocate exactly the space needed for an 8-character string or even an 80-character string. The new problem is where in the heap this string lives?

References to the rescue. The interesting thing about the heap is that every address is the same length. That means we can create a slot of known length in a known location (a variable) and assign an address to it (a reference).


Data comes in many flavours:

  • Data that is part of the compiled code instructions
  • Data in a register
  • Data in a global segment
  • Data on the stack
  • Data on the heap

Each of these types is subtly different and yet the same, they are after all – all data.

The problem though is that some of these data sources have more unknowns and unpredictable behaviour than other sources.

  • Data in instructions is fully known. The program literally was compiled with it in mind.
  • Data in a register is mostly known, the specific value might not be but where it is is exactly known. With the exception of some special registers, they cannot be changed by external influence, only by the code being run.
  • Data in a global static segment is kind of like a register in that where, and what type it is is known. The problem though is that it’s value might suddenly change due to external influence. This is similar for thread local segments in the presence of strands.
  • Data on the stack is like a register in that only your own code is changing it. The problem though is the exact where has to be calculated on the fly.
  • The heap is just the worst. You have to keep track of what, where, and to top it off that can change suddenly due to external influence.

The strength of immutability is that it takes some of the unknowns found in the heap, and reduces them down to constants. Given that it is known that it won’t change the code when compiled can cache the data with certainty, some operations can be faster because the answer doesn’t change between runs, and it is also more memory efficient one copy/many readers.

Without immutability we could not guarantee tat an answer is still current.

  • How long is the string? When last checked it was 5, but now well it could be anything. Need to check again.
  • Need to copy the string, great start by copying each character. Now done, right? Well what if someone changed the first character before you finished copying the last character. Did you in fact copy the string?

time complexity – Determining the number of iterations needed to find the number of bits in an integer

I’m trying to understand the complexity/number of iterations needed to determine the number of bits in an integer.

4 = 100  =  3 bits
3 = 011  =  2 bits
8 = 1000 =  4 bits

I skimmed through this article and it says: A positive integer n has b bits when 2^b-1 ≤ n ≤ 2^b – 1

But when you do the math for an integer 4, you get 2.32 ~= 2. What am I doing wrong?

reference request – Counting special paths on a certain rectangle integer grid (binary matrix)

Crossposting from MSE after getting no answers. The bounty on the MSE question is still open, but not for long. Be advised that the comments of the MSE question regard an obsolete version, and that the issues which had arose from those comments were answered in subsequent edits.

This question arose in the context of studying reflections.

Matrix

Let $n$ be a positive integer.

Denote by $B_n$ the matrix of dimensions $ 2^n times left( n+1 right) $ with entries from $ {0,1} $ such that it satisfies the recursive block relation
$$B_n =
left(
begin{array}{c|c}
underline{0}_{left(2^{n-1} times 1right)} & B_{n-1}\
hline
underline{1}_{left(2^{n-1} times 1right)} & B_{n-1}
end{array}
right)
$$

with the condition

$$
B_1 equiv
begin{bmatrix}
0 & 0 \
1 & 0 \
end{bmatrix}
$$

Matrix examples

For $ n in {2,3,4} $ obtain
$$
B_2 =
begin{bmatrix}
0 & 0 & 0 \
0 & 1 & 0 \
1 & 0 & 0 \
1 & 1 & 0 \
end{bmatrix},
,
B_3 =
begin{bmatrix}
0 & 0 & 0 & 0 \
0 & 0 & 1 & 0 \
0 & 1 & 0 & 0 \
0 & 1 & 1 & 0 \
1 & 0 & 0 & 0 \
1 & 0 & 1 & 0 \
1 & 1 & 0 & 0 \
1 & 1 & 1 & 0 \
end{bmatrix},
,
B_4 =
begin{bmatrix}
0 & 0 & 0 & 0 & 0 \
0 & 0 & 0 & 1 & 0 \
0 & 0 & 1 & 0 & 0 \
0 & 0 & 1 & 1 & 0 \
0 & 1 & 0 & 0 & 0 \
0 & 1 & 0 & 1 & 0 \
0 & 1 & 1 & 0 & 0 \
0 & 1 & 1 & 1 & 0 \
1 & 0 & 0 & 0 & 0 \
1 & 0 & 0 & 1 & 0 \
1 & 0 & 1 & 0 & 0 \
1 & 0 & 1 & 1 & 0 \
1 & 1 & 0 & 0 & 0 \
1 & 1 & 0 & 1 & 0 \
1 & 1 & 1 & 0 & 0 \
1 & 1 & 1 & 1 & 0 \
end{bmatrix}
$$

Explicit formula for the matrix elements

It’s not hard to show that
$$
left(B_nright)_{i,j} =
begin{cases}
lfloor {i-1 over 2^{n-j}} rfloor pmod{2}, & text{if $1 le j le n$}
\
0, & text{if $j=n+1$}
end{cases}
$$

Path

A $B_n$-path $P$ is a set of size $2^n$ where each element is an ordered pair, where the first element is a row index of $B_n$, and the second element is a column index of $B_n$, so that each row index of $B_n$ appears exactly once in the elements of $P$.

Notice that $P$ has the form
$$
{
left(i_1,j_1right),left(i_2,j_2right), ldots , left(i_{2^n},j_{2^n}right)
}
$$

where the row indices from all the pairs are pairwise distinct.

In other words, a $B_n$-path is equivalent to choosing exactly one element from each and every row of $B_n$ in some order.

Obviously $left(B_n right)_{i_{1},j_{1}} = left(B_n right)_{i_{2},j_{2}}$ does not imply that $left(i_1,j_1 right) = left(i_2,j_2 right)$.

Weighted path

A $B_n$-weight $w$ is an $left(n+1right)$-tuple with non-negative integer entries, such that the sum of its entries is equal to $2^n$.

Fix a $B_n$-weight $w equiv left(mu_1, mu_2, ldots , mu_{n+1} right) $, so $mu_j in mathbb{Z}_{ge 0}, , j in {1,2, ldots, n+1 }$ and $sum_{j=1}^{n+1}{mu_j} = 2^n$.

A $B_n$-path with $B_n$-weight $w$, denoted by $P_w$, is a $B_n$-path such that $mu_1$ of its pair elements have column indices which are equal to $1$, $mu_2$ of the remaining pair elements have column indices which are equal to $2$, and so on, until finally the remaining $mu_{n+1}$ pair elements have column indices which are equal to $n+1$.

Notice that if $mu_k = 0$ for some $ k in {1,2,ldots,n+1} $ then $P_w$ does not have an element pair with $k$ as a column index.

Notice that the number of distinct $B_n$-paths with a fixed weight $w$ is given by the multinomial coefficient
$$
binom{mu_1+cdots+mu_{n+1}}{mu_1,ldots,mu_{n+1}}=binom{2^n}{mu_1,ldots,mu_{n+1}}
$$

Weighted path examples

Consider the matrix $B_2$ and the $B_2$-weight $w equiv left(1,2,1 right)$. A $B_2$-path with $B_n$-weight $w$, denoted by $P_w$, can be, for instance, the set
$$
{
left( 1,1right),left( 2,2right),left( 3,2right),left( 4,3right)
}
$$

Graphically, this $B_2$-path looks like the following (in red):
$$
begin{bmatrix}
color{red}{0} & 0 & 0 \
0 & color{red}{1} & 0 \
1 & color{red}{0} & 0 \
1 & 1 & color{red}{0} \
end{bmatrix}
$$

Another possiblity for $P_w$ is the set
$$
{
left( 1,2right),left( 2,3right),left( 3,2right),left( 4,1right)
}
$$

which looks like the following:
$$
begin{bmatrix}
0 & color{red}{0} & 0 \
0 & 1 & color{red}{0} \
1 & color{red}{0} & 0 \
color{red}{1} & 1 & 0 \
end{bmatrix}
$$

Consider the matrix $B_3$ and the $B_3$-weight $w equiv left(2,0,5,1 right)$. A $B_3$-path with $B_n$-weight $w$, denoted by $P_w$ can be, for instance, the set
$$
{
left( 1,1right),left( 2,1right),left( 3,3right),left( 4,3right),left( 5,3right),left( 6,3right),left( 7,3right),left( 8,4right)
}
$$

Graphically, this $B_3$-path looks like the following (in red):
$$
begin{bmatrix}
color{red}{0} & 0 & 0 & 0 \
color{red}{0} & 0 & 1 & 0 \
0 & 1 & color{red}{0} & 0 \
0 & 1 & color{red}{1} & 0 \
1 & 0 & color{red}{0} & 0 \
1 & 0 & color{red}{1} & 0 \
1 & 1 & color{red}{0} & 0 \
1 & 1 & 1 & color{red}{0} \
end{bmatrix}
$$

Another possiblity for $p_w$ is the set
$$
left(
left( 1,4right),left( 2,3right),left( 3,1right),left( 4,3right),left( 5,3right),left( 6,3right),left( 7,3right),left( 8,1right)
right)
$$

which looks like the following:
$$
begin{bmatrix}
0 & 0 & 0 & color{red}{0} \
0 & 0 & color{red}{1} & 0 \
color{red}{0} & 1 & 0 & 0 \
0 & 1 & color{red}{1} & 0 \
1 & 0 & color{red}{0} & 0 \
1 & 0 & color{red}{1} & 0 \
1 & 1 & color{red}{0} & 0 \
color{red}{1} & 1 & 1 & 0 \
end{bmatrix}
$$

Parity of a path

The parity of a $B_n$-path $P$ is the sum modulo $2$ of the elements of $B_n$ with row-column indices which correspond to the elements of $P$.

Summation modulo 2 is commutative, so the parity of a $B_n$-path $P$ is given by
$$
sum_{i=1}^{2^n}{left( B_nright)_{i,j_i}} pmod 2
$$

where $j_i$ is the column index in the element pair of $P$ with row index $i$.

Notice that when calculatiing this sum we may ignore the elements of $P$ with column index $j_i=n+1$, because the corresponding elements of $B_n$ are all equal to $0$.

Parity of a path examples

Consider the following $B_2$-path and $B_3$-path and just take the sum of the red colored $0$‘s and $1$‘s modulo 2.

The $B_2$-path described graphically by
$$
begin{bmatrix}
0 & color{red}{0} & 0 \
0 & 1 & color{red}{0} \
color{red}{1} & 0 & 0 \
1 & 1 & color{red}{0} \
end{bmatrix}
$$

has parity equal to $1$.

The $B_3$-path described graphically by
$$
begin{bmatrix}
0 & color{red}{0} & 0 & 0 \
0 & color{red}{0} & 1 & 0 \
0 & 1 & color{red}{0} & 0 \
0 & 1 & color{red}{1} & 0 \
1 & 0 & color{red}{0} & 0 \
1 & 0 & color{red}{1} & 0 \
1 & 1 & color{red}{0} & 0 \
1 & 1 & 1 & color{red}{0} \
end{bmatrix}
$$

has parity equal to $0$.

Consider the matrix $B_n$.

Fix a $B_n$-weight $w equiv left(mu_1, mu_2, ldots,mu_{n+1} right)$, so $mu_j in mathbb{Z}_{ge 0}, , j in {1,2, ldots, n+1}$ and $sum_{j=1}^{n+1}{mu_j} = 2^n$.

  1. Show that the number of all distinct $B_n$-paths with weight $w$ and parity equal to $0$ is equal to the number of all distinct $B_n$-paths with weight $w$ and parity equal to $1$, if and only if at least one of the entries of the weight $w$ is an odd integer.

Now consider a weight with only even entries.

Fix a weight $varpi equiv left(2phi_1, 2phi_2, ldots , 2phi_{n+1} right) $, so $phi_j in mathbb{Z}_{ge 0}, , j in {1,2, ldots, n+1 }$ and $sum_{j=1}^{n+1}{phi_j} = 2^{n-1}$.

  1. Count the number all distinct $B_n$-paths with weight $varpi$ and parity equal to $0$. Count the same for when the parity is equal to $1$.
  2. Show that the difference between the number of all distinct $B_n$-paths with weight $varpi$ and parity equal to $0$, and the number of all distinct $B_n$-paths with weight $varpi$ and parity equal to $1$, is invariant under any permutation of the entries of $varpi$.

I am looking for references to this kind of problems. I’d appreciate to know about equivalent problems which require less setup, perhaps stated as a problem in graph theory. I am also hoping for some input or hints for these problems. Problem 2 seems to be the most difficult.

recursion – Take an Integer and print it in a Different Base Recursively (c++)

1. Names/Magic numbers

What is the magic number 55 in your base converter function?

I suggest giving it a name.

2. Bounds / Magic numbers / validation

Also, what are the upper and lower bounds on which bases are allowed? Only 2-9 since you are comparing with 9? That should also be specified and checked when reading the input.

3. Code formatting / style

Your code has a lot of space (empty lines and unnecessarily many newlines).
Unless your school requires you to follow that particular style, I suggest reformatting it into a more readable style. You can for example paste it into this formatter to get a more concise and readable code.

https://codebeautify.org/cpp-formatter-beautifier

For example, this is the output of reformatting part of your code.

void BaseConverter(int num, int base) {
  if (num == 0) {
    cout << "";
  }

  if (num >= base) {
    BaseConverter(num / base, base);

    if (num % base > 9) {
      cout << char(num % base + 55);
    } else {
      cout << num % base;
    }
  } else {
    cout << num % base;
  }
}

4. cout multiple inputs

You can chain inputs to cout so you don’t need to do this

cout << endl;
cout << endl;

But rather
cout << endl << endl;

5. File reading

It doesn’t seem that the requirements for the assignment are to read from a file. If that is correct, I think you should skip the file reading and read from cin or a similar terminal input instead.