R is a PID , M a free R module, R-basis

Question: We are a group of Finnish second semester undergrad students who are trying to solve old exercises from this linear algebra class for the benefit of our whole semester and even all prospective students (aka TeXing the solutions for future generations and putting them on our Dropbox). So far so good, this one exercise really leaves us clueless (probably due to non of us quite understanding how to handle modules) and we hope somebody who knows "non linear" Algebra can teach us by solving this with explainations so we don't lose more time just on this one exercise ( we spent heartfelt 2-3 hours already trying to figure something, but we haven't got anything substantial which isn't just a mere guess) :
This is the "evil" exercise:
7
a) Let $R$  be a PID, $M$ a free $R$ module and let $S$ be a $R$-submodule with $\{0\} \ne S \subset M$. Let $(x_{1},\dots,x_{n})$ be a $R$-basis of $M$ and let $t_{1},\ldots,t_{m}\in R$, with $t_{1}|\cdots|t_{m} \ne 0$ so that $(t_{1}x_{1},\cdots,t_{m}x_{m})$ is a $R$-basis of $S$. If we now let
$$F=\bigl\{f_{1}(y_{1})+\cdots+f_{k}(y_{k});k\ge 1, f_{1},...,f_{k}\in \mathrm{Hom}(M,R), \ y_{1},\ldots,y_{k}\in S\bigr\}.$$
Then we can show that $F=t_{1}R$
b) Let more concretely be $R=\mathbf{Z}$, $M= \mathbf{Z}^{3}$, $S= \mathbf{Z}a_{1}+\mathbf{Z}a_{2}+\mathbf{Z}a_{3}$.  Putting $a_{1}=(1,2,3)$, $a_{2}=(4,5,6)$, $a_{3}=(7,8,9)$. Compute $t_{1}>0, \ldots , t_{m} > 0$ in (a)
c) Show that $M/S$ is isomorphic to $(\mathbf{Z}/3\mathbf{Z}) \times \mathbf{Z}$
When we asked our prof where he takes the exercises from, he told us he takes them from a book called "Algebra" by Artin. We couldn't find it in the book itself, so excuse us for not giving a direct reference. Our professor puts $30$% of pure Algebra stuff in the exercises and it is obvious that they are his favourite exercises (so if you want a good grade you need to know this material). We sincerely hope that a seasoned algebraist takes pity/empathy on us and excuse ourselves for the English mistakes and our mathematical incapability.
Comment: Is there supposed to be a question in a)?
Comment: Yes. You were 30 seconds too fast for us :-).
Comment: (a) Doesn't make sense as written. If $f_1(y_1)+\cdots+f_k(y_k)$ is an element of the set of homomorphisms from $M$ to $R$, then what are $f_i$? What does that mean? I suspect that you mean that $F$ consists of all elements of $R$ of the form $f_1(y_1)+\cdots+f_k(y_k)$ with $f_i\in\mathrm{Hom}(M,R)$ and $y_1,\ldots,y_k\in S$. Is that correct?
Comment: Yes, the exercise says exactly what you thought. Thanks also for cleaning up our thread.
Answer: (a) I'm assuming that $F$ is supposed to be:
$$F=\Bigl\{ f_1(y_1)+\cdots + f_k(y_k)\mid f_i\in \mathrm{Hom}(M,R),y_j\in S\Bigr\}.$$
I claim that if $f\in\mathrm{Hom}(M,R)$ and $y\in S$, then $f(y)\in t_1R$.
Indeed, if $y\in Y$, then there exist $a_1,\ldots,a_m\in R$ such that $y = a_1(t_1x_1)+\cdots+a_m(t_mx_m)$. Therefore,
$$f(y) = f\bigl( a_1(t_1x_1)+\cdots + a_m(t_mx_m)\bigr) = t_1 f(a_1x_1)+\cdots + t_mf(a_mx_m).$$
Since $t_1|t_k$ for all $k\geq 1$, $t_jf(a_mx_m)\in t_1R$ for all $j$.  Thus, $F\subseteq t_1R$.
Conversely, let $t_1a\in t_1R$. Since $M$ is free, there is a homomorphism $f\colon M\to R$ such that $f(x_1)=a$, $f(x_j)=0$ for $j\gt 1$. Then $r(t_1x_1) = t_1a\in F$, so $t_1R\subseteq F$. This proves the equality.
(b) Is an exercise in Smith Normal Form, or on something like Theorem II.1.6 in Hungerford's Algebra. I'm going to do it that way, though one can simplify things in this case (see below).
Let $F$ be the set corresponding to $S$ from part (a); in our case, we consider all maps $f\colon\mathbb{Z}^3\to\mathbb{Z}$, evaluated at all linear combinations of $(1,2,3)$, $(4,5,6)$, and $(7,8,9)$. It is not hard to check that $F$ is always a subgroup of $R$, and so is a subgroup of $\mathbb{Z}$, hence is of the form $m\mathbb{Z}$ for some $m\geq 0$. In this case, $F$ will be $\mathbb{Z}$, since we can show $1\in F$ by a suitable choice of morphisms and elements of $S$: take $f_1\colon\mathbb{Z}^3\to\mathbb{Z}$ be given by $f_1(x,y,z) = x$, and consider $f_1(1,2,3)\in F$. So $x_1 = (1,2,3)$, $t_1=1$.
(In fact, in a situation such as these, where $M$ is given as $R^n$ and $S$ is given by generators in terms of the basis of $M$, it is not hard to verify that $F$ is the ideal of $R$ generated by the coordinates of the generators of $S$; in this case, we would want the ideal generated by $1,2,3,4,5,6,7,8,9$, which is nothing more than $\mathbb{Z}$ itself).
So $F=1\mathbb{Z}$, and $t_1$ will be $1$. Now find an element of $S$ that has a coordinate equal to $t_1$: $(1,2,3)$ will do. Here, $t_1=1$ so there is nothing to do, but if $t_i\gt 0$, then we will want to show that every coordinate of the vector must in fact be divisible by $t_1$ (consider the projection on the $i$th coordinate, which must be an element of $F$ as well).
Now let $S'=\{(x,y,z)\in S\mid x=0\}$ ($x$ because it was the first coordinate that was equal to $t_1$ in our choice above). Then $\langle(1,2,3)\rangle\cap S' = \{(0,0,0)\}$, and $\langle(1,2,3)\rangle+S' = S$. Indeed, if $(x,y,z)\in S$, then $(x,y,z)=x(1,2,3) + \bigl((x,y,z)-x(1,2,3)\bigr)$, and $(x,y,z)-x(1,2,3)\in S'$. So $S=\langle(1,2,3)\rangle\oplus S'$.
Our first basis element will then be $t_1(1,2,3)$, and now we proceed to work recursively on $S'$.
Note that since $S$ is generated by $(1,2,3)$, $(4,5,6)$, and $(7,8,9)$, it is also generated by $(1,2,3)$, $(4,5,6)-4(1,2,3) = (0,-3,-6)$, and $(7,8,9)-7(1,2,3)=(0,-6,-12)$. So $S'$ is generated by $(0,3,6)$ and $(0,6,12)$; in fact, $S'$ is generated by $(0,3,6)$.
Consider now $F(S')$. It is easy to check that $F(S') = 3\mathbb{Z}$ (again, $F(S')$ is the ideal generated by the coordinates of the generators of $S'$, in this case $0$, $3$, $6$, and $12$, so $F(S') = (3)=3\mathbb{Z}$); find an element of $S'$ that has some coordinate equal to $3$: $(0,3,6)$ will do. Note that both coordinates are divisible by $3$, so write $(0,3,6) = 3(0,1,2)$. Then $t_2=3$, and $x_2=(0,1,2)$.
Now let $S'' = \{(0,y,z)\in S'\mid y=0\}$. As above, $\langle (0,3,6)\rangle\cap S''=\{(0,0,0)\}$, $\langle (0,3,6)\rangle+S''=S'$. So we can now work in $S''$.
In fact, $S''=\{(0,0,0)\}$ so we are done. We have $t_1=1$, $t_2=3$, $m=2$, $x_1=(1,2,3)$, $x_2=(0,1,2)$. Now we just need to complete the list of $x_i$ to a basis for $M$; take $x_3 = (0,0,1)$, for example.
(c) Now it is easy:
$$\begin{align*}
\frac{M}{S} &\cong \frac{(1,2,3)\mathbb{Z} \oplus (0,1,2)\mathbb{Z}\oplus (0,0,1)\mathbb{Z}}{(1,2,3)\mathbb{Z}\oplus 3(0,1,2)\mathbb{Z}\oplus 0(0,0,1)\mathbb{Z}}\\
&\cong \frac{(1,2,3)\mathbb{Z}}{(1,2,3)\mathbb{Z}} \oplus \frac{(0,1,2)\mathbb{Z}}{3(0,1,2)\mathbb{Z}} \oplus \frac{(0,0,1)\mathbb{Z}}{0(0,0,1)\mathbb{Z}}\\
&\cong \frac{\mathbb{Z}}{\mathbb{Z}} \oplus \frac{\mathbb{Z}}{3\mathbb{Z}} \oplus \frac{\mathbb{Z}}{0\mathbb{Z}}\\
&\cong \frac{\mathbb{Z}}{3\mathbb{Z}} \oplus \mathbb{Z}\cong \frac{\mathbb{Z}}{3\mathbb{Z}}\times\mathbb{Z}.
\end{align*}$$

Now, I did (b) using the algorithmic proof that appears, for example, in Hungerford, and using part (a). In fact, we can do it simpler in this instance by doing some preliminary considerations:
First, simplify the generating set by doing row-reduction on the matrix whose rows are the generators of $S$:
$$
\left(\begin{array}{ccc}
1 & 2& 3\\
4 & 5 & 6\\
7 & 8 & 9
\end{array}\right) \to \left(\begin{array}{rrr}
1 & 2 & 3\\
0 & -3 & -6\\
0 & -6 & -12
\end{array}\right) \to \left(\begin{array}{rrr}
1 & 2 & 3\\
0 & 3 & 6\\
0 & 0 & 0
\end{array}\right).$$
So $S$ is generated by $(1,2,3)$ and $(0,3,6) = 3(0,1,2)$.
Then notice that we have $(1,2,3)$, $(0,1,2)$, and $(0,0,1)$, which are a basis for $\mathbb{Z}^3$; that $(1,2,3)$ and $3(0,1,2)$ are a basis for $S$; and that setting $t_1=1$ and $t_2=3$ will solve the problem.

R is a PID , M a free R module, R-basis


Redirect sites without certificate to non-ssl instead of serving a default certificate

Question: I am hosting several websites from our customers. Some of them have ssl certificates and thus use port 443 for https and some do not have a certificate.
The sites that have such a certificate are configured to automatically redirect http to https. If I access one of the sites that don't have their own certificate, the one from the vhost file that was loaded first is served, which is in my case my own homepage.
I now want to know if it is possible to have apache redirecting ssl requests to sites that do not have their own certificate to non-ssl so it does not give the "untrusted certificate" warning.
Example:

domain1.com - SSL enabled (loaded first)
domain2.com - SSL enabled
domain3.com - SSL not enabled

When I request https://domain3.com I get the untrusted warning because the certificate of domain1.com is served, which does of course not contain domain3.com as the primary or alternative name.
Instead of that, I want to have a redirect to http://domain3.com
What I already tried was the following configuration, which gives me an SSL error when accessing domain3.com
<code><VirtualHost MyIp:443>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>
</code>
I am not sure if my approach is going in the right direction or if my goal is even achievable. So I am open to all kinds of help. Thanks.
Comment: I would go for "https everywhere", and get certs for all the domains you're hosting. It's quite easy now with [Let's Encrypt](https://letsencrypt.org/).
Comment: This is of course our long-term goal but we wanted a short-term solution until we are done implementing Let's Encrypt in our Hosting infrastructure.
Answer: This is not possible without valid certificates.
With https the TLS/SSL negotiation happens first, before any content (including redirects) happens. So you need to establish a secure connection (using a certificate) before you can redirect back to http.
If there was any way around this, then that would be a major security hole in https as attackers could just downgrade any request to http.


how to replace cell values in a column of a data frame at a specified frequency with the previous cell value?

Question: There is one column
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Output should be:
1
1
1
1
5
5
5
5
9
9
9
9
13
13
13
13
17
17
17
17
Unable to solve the same
how to replace every 3 cell values in a column with its previous cell value in a data frame in python. I am trying to replace the cell values in a specified frequency with its previous cell value.
Please help to resolve the same.
Comment: What do you imagine are the logical steps necessary to solve the problem? Where did you get stuck when trying to implement it?
Comment: As i am new in the field, didn't able to find any right solutions as of now
Comment: I didn't ask you to find solutions. I asked you to think about the problem and what is involved in solving it. This is a basic skill that everyone should develop, whether they write code or not.
Answer: Instead of column let's call it a List or an Array of values.
When looking up for solving any problem, we must break it into small steps, in order to make it easier.
First of all, you'll need to create a cycle that reads the full list, one element at a time. Like this:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

# Using for loop
for position in list:
    print(position)

While we are reading the list, our application will have 2 tasks.

Read the current position of the list and temporarily store the value
Replace the current position with the previous value read, until we have done it 3 times.

input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
output_list = []

# We will store the position value here
saved_value = 0

# We use this variable to loop to count up to 4 within the list range
counter = 0

# Using for loop
for position in input_list:
  #print(counter)

  # when the counter is zero,
  if counter == 0:
    # we store the current position in the temporary variable
    saved_value = position

    # we add the current value of the inputlist into the output list
    output_list.append(position)
  else:
    # For every other situation we save the temporary value
    output_list.append(saved_value)

  # increase the counter at the end of the cycle
  counter+=1

  #  every 4 reads we reset the counter
  if counter == 4:
    counter = 0

print("\nOutput List")
print(output_list)
# [1, 1, 1, 1, 5, 5, 5, 5, 9, 9, 9, 9, 13, 13, 13, 13, 17, 17, 17, 17]

Comment: Thank you for your response but not getting the desired output
Comment: I explained the exercise correctly, you probably didn't even bothered to copy the full solved exercise, and that is why you think the solution is wrong...
Check again, and this time, copy everything... :S


How to detect if a user is in a specific directory/accessing a specific path?

Question: For example I need to know if a user is in this directory http://example.com/directory; the value should return true if the use is on any of the following pages:

http://example.com/directory/cars
http://example.com/directory/homes
http://example.com/directory/homes/howtosell
http://example.com/directory/food/seafood
http://example.com/directory/food/seafood/fish
Answer:
For example I need to know if a user is in this directory http://example.com/directory

If "directory" is a filesystem directory, then it's not possible for a Drupal function to know when a user is visiting that directory, for the simple fact Drupal is not invoked to serve the content of a directory. One of the Rewrite directives present in the .htaccess file that comes with Drupal is the following one:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

If "directory" is the path for which a module defines a menu callback, and there isn't a directory with that name, then it is possible for a function to return TRUE when the user is visiting a specific path.
function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if ($dir == $path) {
      return TRUE;
    }
  }

  return FALSE;
}

This function doesn't consider the path aliases. If http://example.com/path-alias is the path alias for http://example.com/real-path, $_GET['q'] will contain real-path when the user visits http://example.com/path-alias; the same is true for arg(), which will return an array containing real-path.
If the function needs to consider also the path aliases, then it needs to be rewritten as:
function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if (drupal_get_normal_path($dir) == $path) {
      return TRUE;
    }
  }

  return FALSE;
}

Answer: Are you looking for http://api.drupal.org/api/drupal/includes--path.inc/function/arg ?
arg(0); // should be 'directory'

That's if you're referring to path components (eg "node" and "1" in "node/1") rather than actual directories, which are a filesystem component as kiamlaluno says. But if those were actual directories, then this wouldn't be a Drupal question :)


Convert dictionary to multiple arrays

Question: How can I convert a dictionary like this :
var myDictionary: Dictionary = ["Data1":"Value1", "Data2":"Value2", "Data3":"Value3"]

Into two arrays like that :
var myArray1 = ["Data1", "Data2", "Data3"]
var myArray2 = ["Value1", "Value2", "Value3"]

I tried to do it with :
myDictionary.values

and :
myDictionary.keys

But didn't worked...
Any help is greatly appreciated
Comment: For future reference "*But didn't worked*" is never a sufficient description of a problem – did it give you a compile time error? A runtime exception? An unexpected output? Set your house on fire?
Comment: Also duplicate of [Swift Dictionary: Get values as array](http://stackoverflow.com/questions/26988167/swift-dictionary-get-values-as-array/26988168#26988168)
Answer: let someKeys = [String](myDictionary.keys)
//It is only [String] because the keys are Strings

let someValue = [String](myDictionary.values)
//It is only [String] because the values are String

If I had a [Int:String]() then it would be
let someKeys = [Int](someKeys.keys)

because key:Value
Edit
I totally forgot, nice job @originaluser2
You can also do
let array = Array(myDictionary.keys)
let array2 = Array(myDictionary.values)

and it will do the hard work for you.
Comment: Or even better, use the `Array(...)` initialiser and let Swift infer the type

Convert dictionary to multiple arrays


Invalid `prisma.dayEvent.create()` invocation: Null constraint violation on the fields: (`id`)

Question: When I'm trying to create event in calendar this error throws:
Invalid `prisma.dayEvent.create()` invocation:

Null constraint violation on the fields: (`id`)

Which is weird cause id have default() in prisma schema
Prisma schema:
model Calendar {
  id           String      @id @default(cuid())
  calendarName String
  dayEvents    dayEvent[]
  hostId       String

  host User @relation(fields: [hostId], references: [id])
}

model dayEvent {
  id         String   @id @default(cuid())
  name       String
  date       DateTime
  calendarId String

  calendar   Calendar @relation(fields: [calendarId], references: [id])
}

TRPC code where is prisma.create() triggering error:
create: protectedProcedure
    .input(
      z.object({ name: z.string(), date: z.date(), calendarId: z.string() })
    )
    .mutation(async ({ ctx, input }) => {
      return ctx.prisma.dayEvent.create({ //Error here
        data: {
          name: input.name,
          date: input.date,
          calendarId: input.calendarId,
        },
      })
    }),

In Calendar @id @default(cuid()) is working, I can create calendars.
But for some reason in dayEvent it wants id.
When I give it id, like that:
create: protectedProcedure
    .input(
      z.object({ name: z.string(), date: z.date(), calendarId: z.string() })
    )
    .mutation(async ({ ctx, input }) => {
      return ctx.prisma.dayEvent.create({
        data: {
          id: '1',
          name: input.name,
          date: input.date,
          calendarId: input.calendarId,
        },
      })
    }),

Everything is working as expected. Despite this, I don't think it will be right to generate ids like that with trpc.
Using full t3 stack
I searched on the web, but didn't find anything helpful.
Did npx prisma db push to make sure database is in sync with the Prisma schema.
Comment: Is this mongoDb?
Comment: This is supabase
Answer: I think that the problem is on the schema.
This is the docs example in the one to many relation:
model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int
}

If you have a one to many relation: The problem in your code is here:
calendar   Calendar @relation(fields: [id], references: [id])

You should change fields [id] to fields [calendarId].
In the Calendar you should change the day DayEvent to days DayEvent[]
But if you have one to one relation this field should be @unique in the schema.
I hope it helps you!
Comment: Thanks for responding, but sadly It's not working as expected. I edited question for better understanding of situation. Right now I'm generating ids with uuid().
Comment: Seeing your edit two considerations:

`
create: protectedProcedure
    .input(
      z.object({ name: z.string(), date: z.date(), calendarId: z.string() })
    )
    .mutation(async ({ ctx, input }) => {
      return ctx.prisma.dayEvent.create({
        data: {
          id: '1',
          name: input.name,
          date: input.date,
          calendarId: input.calendarId,
        },
      })
    }),
`

1.  The id is marked as default, you dont need to send it.

1. The calendarId corresponds with one already created in the other table?


Dovecot corrupted transaction log file is delaying email

Question: We're running dovecot as an IMAP server and postfix to deliver mail. One of our users is complaining that email is gettin delayed (no we're not using grey listing or anything like that). /var/log/mail.info is showing these log messages around when the user should be getting this email. The mail dirs (eg /mail) is mounted over NFS (if that helps)
Jul 26 18:31:08 mail1 deliver(email@example.com): Corrupted transaction log file /mail/example.com/user/dovecot.index.log: start_offset (5160) > file size (5140)
Jul 26 18:31:08 mail1 deliver(firstname.lastname@example.com): fscking index file /mail/example.com/user/dovecot.index
Jul 26 18:31:08 mail1 deliver(email@example.com): msgid=<firstname.lastname@example.com>: save failed to INBOX: Internal error occurred. Refer to server log for more information. [2009-07-26 18:31:08]

Answer: D'oh!  The cause of the delay is that dovecot is trying to process a corrupted index.
Just have the user log out of mail, delete the index file, and it will automatically be recreated when they log in.  Thus, just do this:
rm /mail/example.com/user/dovecot.*

Dovecot creates temporary index files of every message; when the user logs in for the first time, the indexes are created from scratch if they are not present, so this is a simple, effective fix, and it works every time.  I've had this happen with earlier versions of Dovecot, and deleting the index is 100% effective in all cases.
You are storing mail on that NFS mount in maildir format, right?
By the way, pre-1.0 or beta releases of Dovecot had this issue on a regular basis.  The newer versions have fixed this.


How do Bayesians deal with the fact that the treatment of fixed parameters as random variables can lead to inappropriate subjective probabilities?

Question: Let's assume the tossing of an unfair coin is modeled by a random variable X taking the values head and tail. You know that the objective probability of the coin showing up head is either $p=0.4$ or $p=0.6$ and that no other value is possible. Further, you have reason to believe that $p=0.6$ is very likely to be true.
Following the Bayesian methodology, you could express your belief by the (subjective) prior distribution
$$\begin{align}
P(p=0.6)&=0.9 \\
P(p=0.4)&=0.1\text{,}
\end{align}$$
hence treating $p$ as a random variable. Once you do this, marginalization in combination with Lewis's principle implies that your subjective probability for the coin showing up head should be
$$P(X=\text{head})=0.6 \times 0.9+0.4 \times 0.1=0.58\text{,}$$
which is rather inappropriate even as subjective probability, because after all you know that $p$ can either take the value $0.4$ or $0.6$ and hence your subjective probability should either be $0.4$ or $0.6$.
I would like to know how Bayesians respond to that issue. Has this issue been discussed theoretically, and what is the Baysian position towards it?

@Arya McCarthy: Thank you for your answer. I think you are right that Baysians interpret P(X=head)=0.58 as degree of belief, that heads will show up. My question is why does this makes sense, and according to which criterion? I feel this boils down to the justification of the prior. Imagine a Bayesian also has the same prior distribution for other coins as well and that the objective probability of getting a coin with p=0.6 is actually 0.9 and the objective probability of getting a coin with p=0.4 is actually 0.1. If in an experiment, the Baysian selects a series of coins at random and tosses them, $P(X=\text{heads})=0.58$ would be justified, because in this two stage random experiment (first select a coin and then toss it) the overall relative frequency of head will roughly speaking converge to the expected value, which is $0.58$. Hence, roughly speaking, a long run strategy based on $P(X=\text{head})=0.58$ would actually be successful in the real world and this seems to me as a good criterion for P(X=head)=0.58 to make sense, - actual long run success considering similar situations. So how do you arrive at a prior, that roughly reflects these two objective probabilities? You could collect a sample and calculate frequentist estimates. If this is not possible, you should somehow try to guess what these two objective probabilities in a two stage experiment really are. Only then can you interpret $P(X=\text{head})=0.58$ as your subjective believe about the long run frequency in a two stage experiment and can argue that you believe this leads to the best long run strategy. That being said, in my initial example, if I had to make a single bet, I personally would base my action on $p=0.6$, because I am not interested in the long run here. This does not mean $P(X=\text{head})=0.58$, which reflects the long run relative frequency if my prior also does.
Comment: I see no problem with 0.58 as a subjective probability, it is simply taking into account uncertainty over the two possible choices
Comment: It might be less confusing to use a less loaded letter than $p$ for the coin's parameter. I'll call it $f$. The asker seems concerned that the true $f$ cannot be 0.58. But the Bayesian never claims that the coin's parameter $f$ is 0.58. They're saying that this is their belief about $p(\text{heads})$.
Comment: Editing questions is not meant for discussion with other users. Please do not use it like this. Few edits to improve questions are fine, but not frequent edits.
Comment: Could you explain what you're trying to ask by "what sense does this make?"
Comment: You'd base it on the first one. (A lot of Bayesian reasoning actually was first described in the context of betting odds.)
Comment: It may also be useful to consider more extreme values for $f$ than 0.4 and 0.6. Consider $P(f=0.99) = 0.9$ and $P(f=0.01) = 0.1$. Behaving as if the probability of heads is 0.99 ignores the 10% chance that it's the much smaller 0.01, but the Bayesian estimate of $P(X=\text{head}) = 0.892$ considers both possibilities in proportion to their prior probability.
Comment: I updated the question. It is a valid theoretical issue and I hope I made that clear.
Comment: If you were in a casino, would you base your next action on P(X=head)=0.58 or on p=0.6 (maximum of the prior) given that you know that p can either be 0.4 or 0.6? If the answer is p=0.6, then what practical meaning has P(X=head)=0.58?
Comment: Don't forget—you're not betting on the value of $p$. You're betting on the outcome of the sampled coin flip.
Comment: [Here](https://stats.stackexchange.com/questions/539351/how-do-bayesians-interpret-px-x-theta-c) is a thread addressing a related question about coin tosses and Bayesian predictive probability.  [Here](https://stats.stackexchange.com/a/538616/307000) is a thread comparing a Bayesian predictive probability to a frequentist predictive p-value using a coin toss example.
Comment: @ AryaMcCarthy could you please elaborate on that?
Comment: @Jan I would drop your edit and ask the question again.  The reason is that in your edit, you drop marginalization in the second part when you discuss what you would do and instead impose a loss function.  Implicitly, you have imposed the "all or nothing" loss function.  Although you are not aware of it, that decision has vast mathematical implications for gambling. Arya's answer is correct for your first question.  You cannot get from Arya's answer to the first half, to your question in the second half. Also, as you have told us what you would do, it isn't really a question anymore.
Answer:
What you refer to as $P(X=\text{head})$ is in fact an expected value $E(p)$ of a prior distribution that you've chosen for $p$. You noticed correctly that the distribution can take only two values $0.4$ and $0.6$, so $0.58$ is an impossible result for such distribution. There is nothing wrong with this. Bernoulli distribution can take only two values $0$ and $1$, and its expected value is a real number in the unit interval. The expected value of a discrete distribution, like binomial, or Poisson can be a real number, no matter that those are distributions for integer-valued things. This has nothing to do with Bayesian statistics, it's how random variables and expected values work.

It's worth pointing out that the expected value of the prior distribution for $p$ is not the "subjective probability", it's just a numerical summary of the prior distribution that you assumed for the parameter $p$. This summary may, or may not make sense to describe the distribution. Your prior is the whole distribution, not its expected value.
If your prior probability distribution is
$$
\begin{align}
P(p=0.6)&=0.9 \\
P(p=0.4)&=0.1\text{,}
\end{align}
$$
and based on this you need to make a single bet, then you could simply bet on $0.6$ as it has a higher probability. There is no reason why you would bet for the impossible $0.58$ average. Expected value just tells you what is $p$ on average, nothing more than this.

This choice of the prior for $p$ is rather strange, but I understand that this is a made-up example. As you noticed, the distribution can take only two values. If you plug in the prior into the Bayes theorem
$$
P(A|B) = \frac{P(B|A)\,P(A)}{P(B)}
$$
the result would also need to be defined in terms of those two values. The more usual choice of a prior for probability $p$ would be a distribution over the whole range of possible values for probabilities, e.g. uniform over $(0, 1)$, or beta distribution. Such distributions assign non-zero probabilities to all the possible values of $p$, so you could update the prior with the data (through the likelihood), and come up with an estimate. Usually, you have no way of knowing for certain that the parameter is a particular real number, so both such prior makes more sense, and problems, as described by you, don't arise.

If you collect the data, the more data you have, the closer the result would be to what you observed in the data. Given that you used a reasonable prior (that assigns non-zero probabilities to the possible values of the parameter), this methodology enables you to estimate the distribution of possible values of the parameters given the data and the prior.

What is probability? Bruno de Finetti once said that "probability does not exist". Probability is an abstract, mathematical concept. There are no "probabilities" in the wild. If you toss a coin, an unlimited number of different factors make it hard to predict. Each of those factors alone can be described in terms of laws of physics, but together they form a chaotic system. We assign a probability to simplify all those factors to a single number, but there is no "probability" that is responsible for the result of the coin toss.
Bayesians reason in terms of subjective probabilities, the probability is a number between zero and one that measures how much I believe in something. If I needed to make a bet, the number would help me quantify the amount of the bet that would be reasonable based on my assumptions.
Comment: "Your choice of a prior is rather bad"—the asker indicates that 0.4 and 0.6 are the only possible values.
Comment: @AryaMcCarthy good point. I corrected the wording.
Answer: Expanding my comment into an answer: I don't see this as inappropriate at all. To call it inappropriate is analogous to saying that the the expected value of a die being 3.5 is inappropriate—after all, a 3.5 can never come up!
It might be less confusing to use a less loaded letter than $p$ for the coin's parameter. I'll call it $f$.
You seem concerned that the true $f$ cannot be 0.58. But the Bayesian never claims that the coin's parameter $f$ is 0.58. They're saying that this is their belief about $p(\text{heads})$. The belief incorporates uncertainty about $f$.
Don't forget—you're not betting on the value of $f$. You're betting on the outcome of the sampled coin flip. Believing that $p(\text{heads})$ is 0.58 lets you hedge your bets. In fact, de Finetti explained the concept of subjective probabilities in the context of betting odds. It's exactly what you're considering here: rather than treating $p(\text{heads})$ as 0.6 or 0.4, you use your uncertainty about $f$ to alter how confidently you'd bet on heads.
Comment: Thank you for your answer. I think you are right that Baysians interpret P(X=head)=0.58 as degree of believe, that head will show up. See my longer post below.
Answer: This is not really an objection to Bayesian analysis at all --- it is an objection to the rules of probability theory.  If you have an event $\mathcal{E}$ (e.g., a head occurring on a coin) and a discrete parameter $p$ giving the conditional probability of the event, then the law of total probability states that:
$$\mathbb{P}(\mathcal{E}) = \sum \mathbb{P}(\mathcal{E}|p) \pi(p) = \sum p \cdot \pi(p).$$
As can be seen from this equation, the marginal probabilty of the event is a convex combination of the conditional probabilities given by the possible values of the parameter $p$.  Your question asserts that the marginal probability of the event should be equal to one of the possible parameter values, but that is not always true.  In your example, there is nothing wrong with the conclusion that the marginal probability of a head is $0.58$ --- that is the value that follows from the stipulated prior for $p$ and the likelihood function for the outcome of the coin.
As to a response, Bayesians would have the same response as any other practitioners who use probabilty theory as the basis for statistics.  If you are unwilling to accept the law of total probability theory then you are rejecting one or more of the axioms of probability, and the onus would then be on you to stipulate an alternative theory of probability to take its place.
Comment: @Jan this example has *nothing* to do with Bayesian statistics, it does not even involve Bayes theorem. It uses basic laws of probability. This is how probability theory works. Average human has between one and two legs, this is how expected values work nonetheless that the results does not have much to do with human biology.
Comment: @Jan: As Tim notes, this is something that also happens in non-Bayesian applications.  Many statistical paradigms use the law of total probability, so if you are unwilling to accept values computed from this rule, that is something that will affect more than just Bayesian analysis.
Comment: Thank you for your answer. It is only Bayesians, who treat the fixed constant p as a random variable (frequentists do not). It is only this treatment, which makes it possible to apply the law of total probability to the situation. A frequentist would not agree with the equation you presented. I am not questioning the axioms of probability here, only the treatment of fixed constants as random variables.
Comment: @Jan but, as noticed correctly by Ben, there is nothing "Bayesian" about your example. It is just a probability distribution and you are calculating the expected value of it, that appears outside the possible values of the random variable. Same thing applies to Bernoulli distribution, so you could argue that if Frequentist estimates the mean of the coin tosses to be 0.513, the number does not make sense.
Comment: As I said, it is only Bayesians, who treat the fixed constant $p$ as a random variable, i.e. as a function $p: \Omega \rightarrow [0,1]$, and only then does $p=0.6$ represents an event, i.e. a subset of $\Omega=\{head,tail\}$, i.e. $\{p=0.6\}=p^{-1}(0.6)=\{\omega \in \Omega : p(\omega)=0.6\}$. The law of total probability applies only to events or subsets of $\Omega$ in this case and not to constants. In the described single stage experiment, no frequentists would agree with the application of the law of total probability.
Comment: @Tim: It might help you to consider a *two*-stage experiment were we first choose from two *different* types of coins with objective probabilities $p_1=0.4$, $p_2=0.6$ and then toss: $\Omega:=\{p_1,p_2\}\times\{head,tail\}$, $X:\Omega\rightarrow\{head,tail\}$,  $p:\Omega\rightarrow [0,1], \omega \mapsto \pi_1(\omega)$, $i=1,2$ ($\pi_1$ is the projection to the first component), $\mathbb{P}(X=head|p=p_i):=p_i$, $i=1,2$, $\mathbb{P}(p=p_1):=0.1$, $\mathbb{P}(p=p_2):=0.9$. Here $p$ models the selection of the coin. Then $\mathbb{P}(X=head)=\sum_i\mathbb{P}(X=head|p=p_i)\mathbb{P}(p=p_i)=0.58$.
Comment: @Tim: We disagree.
Comment: @Tim: I am not questioning the interpretation of the expected value as "middel". It is OK that the average human has 1.99 legs. However, the interpretation as "middel" does not justify the *exact* identification of the probability of heads with the expected value. Bayesians say P(X=head)=0.58 (exactly). Frequentists say that the mean of given data is an *approximation* of P(X=head).
Comment: @Jan I made edits in my answer to comment on that.


Java: Graphics2D

Question: import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class SimpleGui3C implements ActionListener {

JFrame frame;

public static void main(String[] args) {

    SimpleGui3C gui = new SimpleGui3C();
    gui.go();
}

public void go() {

    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton button = new JButton("Change Colors");
    button.addActionListener(this);

    MyDrawPanel drawPanel = new MyDrawPanel();

    frame.getContentPane().add(BorderLayout.SOUTH, button);
    frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
    frame.setSize(300, 300);
    frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
    frame.repaint();
}
}

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class MyDrawPanel extends JPanel {

public void paintComponet(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;

    int red = (int) (Math.random() * 256);
    int green = (int) (Math.random() * 256);
    int blue = (int) (Math.random() * 256);
    Color startColor = new Color(red, green, blue);

    red = (int) (Math.random() * 256);
    green = (int) (Math.random() * 256);
    blue = (int) (Math.random() * 256);
    Color endColor = new Color(red, green, blue);

    GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
    g2d.setPaint(gradient);
    g2d.fillOval(70, 70, 100, 100);

}
}

So I have been trying to solve this problem for 2 hours straight and do not seem to be able to problem solve. This "program" is supposed to have an oval and a button come up at the bottom of the screen that allows me to randomize the color of the oval.I am using netbeans and whenever I click run I get this:
Does anyone have any solutions to fix my problems? Sorry for wasting your time if it is a stupid question.
Comment: What problem are you having?
Comment: The circle doesn't appear, as shown in the photo. The bottom appears, though.
Comment: Please perhaps post a link better image. The link should be to an image, not to a web page.
Comment: Sorry sir, I fixed it.
Answer: Spelling matters: paintComponet != paintComponent
Always preface your overridden methods with @Override. If you'd have done this, you the compiler would warned you about your error.
So change this:
public void paintComponet(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;

    int red = (int) (Math.random() * 256);
    int green = (int) (Math.random() * 256);
    int blue = (int) (Math.random() * 256);
    Color startColor = new Color(red, green, blue);

    red = (int) (Math.random() * 256);
    green = (int) (Math.random() * 256);
    blue = (int) (Math.random() * 256);
    Color endColor = new Color(red, green, blue);

    GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
    g2d.setPaint(gradient);
    g2d.fillOval(70, 70, 100, 100);
}

to this:
@Override // don't forget this
protected void paintComponent(Graphics g) { // spelling matters. Also make it protected

    // !!!! don't forget this!
    super.paintComponent(g); // to have the JPanel do housekeeping painting

    Graphics2D g2d = (Graphics2D) g;

    int red = (int) (Math.random() * 256);
    int green = (int) (Math.random() * 256);
    int blue = (int) (Math.random() * 256);
    Color startColor = new Color(red, green, blue);

    red = (int) (Math.random() * 256);
    green = (int) (Math.random() * 256);
    blue = (int) (Math.random() * 256);
    Color endColor = new Color(red, green, blue);

    GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
    g2d.setPaint(gradient);
    g2d.fillOval(70, 70, 100, 100);
}

Comment: Wow! I literally looked over this code forever! And I could not find what is wrong! Thank you so much! I hope I will get as good at code as you one day!

Java: Graphics2D


Query abbreviation TSQL

Question: SELECT COUNT(id) FROM [user] WHERE [rank] = 1
SELECT COUNT(id) FROM [user] WHERE [rank] = 2
SELECT COUNT(id) FROM [user] WHERE [rank] = 3
SELECT COUNT(id) FROM [user] WHERE [rank] = 4

How can I shorten the question?
Comment: FWIW, I didn't downvote this. Hopefully you will realize that you need to provide some details about what you are trying to do. Even as simple as "Is it possible to retrieve all 4 values in a single query?" would have been a huge leap in making this question better.
Comment: @SeanLange if you are able to shorten that *question* as requested, not the *script* i'd be utterly impressed :)
Comment: So, do you want to put that into one select statement? Is that what you mean?
Comment: I am not sure what the question so I couldn't begin to help you shorten it. Can you try to explain what you are trying to do?
Comment: @scsimon - "shorten question"? or maybe "question shorter"? LOL
Comment: Immediately press the negatives :) WEI_DBA solved!
Comment: I apologize, I will be more careful.
Comment: One of the best things about Stackoverflow is that it not only allows people to answer your questions, but your questions and their answers also act as documentation and references for many people in the future who will have similar questions to you. It is always good to have a very structured, easy-to-understand question, and often times it's not a very hard thing to do. I would suggest you update the question, especially now that it's solved.
Answer: Try this. From what you explained.
SELECT [rank], COUNT(id)
FROM [user]
WHERE [rank] BETWEEN 1 AND 4
GROUP BY [rank]

Comment: Given the extremely vague "question" this is about the only thing that makes sense. Well guessed!!!

Query abbreviation TSQL


Can c++ mutex cross method/variable? If so, why does it not work here?

Question: I am writing a provider-consumer program. There are many message queues, and I want to make sure that every message enqueued in each message queue has a sequential, increasing index, for example, <0, "msga">, <1, "msgb">, .... The order remains inside each queue, and different queues are irrelevant.
I use 2 hash maps and 2 mutex locks to do this(I want to use only one lock, but failed).
(i) The first hash map maps queue name to a pair <int, mutex *>, in which int means the counter of each queue, mutex protects the queue in concurrent requests. The definition is
using umap_cnt = unordered_map<string, pair<int, mutex* > >;
umap_cnt counters;

(ii) The second hash map maps queue name to actual message <int, MSG>(MSG is actually string), the definition is
using umap_msg = unordered_map<string, vector<pair<int, msg> > >;
umap_msg messages`;

My logic is

find the mutex of a queue in counters, lock() it
use counter_iter->first as the index of a message, put() it in messages
increase the index
unlock() the mutex lock

The sample code is as follows
/* File A.cpp */
using umap_msg = unordered_map<string, vector<pair<int, msg> > >;
mutex mtx;
umap_msg messages;
void put(string kname, MSG msg, int index) {
    // If not using mtx here, the message would be out of order.
    // lock_guard<mutex> mtx;
    messages[kname].push_back(make_pair<index, msg>);
}

// Many threads runs producer()
/* File B.cpp*/
using umap_cnt = unordered_map<string, pair<int, mutex* > >
void producer(string kname, MSG msg) {
    umap_cnt::iterator iter = counters.find(kname);
    if (iter == counters.end())
        return;
    // lock the queue
    iter->second.second->lock();
    put(kname, msg, iter->second.first);
    ++iter->second.first; // increase the counter
    iter->second.second->unlock();
}

The problem is that I find a single lock does not work. I have to use 2 mutex locks, one in producer and the other in put, otherwise I get either out of order message or segmentation fault(no idea why).
My original purpose is to use only one lock in producer. Each queue has its own mutex, and no two threads can get the lock of a queue at the same time, so every message in each queue should be ordered. However, the result is not what I expected.
Why is the extra lock in line 7 necessary? If I do have to use 2 locks, is there anyway that I can optimize it because 2 locks seems a little heavy?
Comment: The tangled description is difficult to follow. You need to edit your question and make it meet all requirements for a [mcve] as explained in stackoverflow.com's [help], so that anyone can reproduce your problem, themselves. Random code fragments, that may or may not have anything to do with the issue at hand, are insufficient.
Comment: And remove all those line numbers - they make it impossible for us tio compile your code.
Comment: You really ought to use a `lock_guard` in `producer()` instead of directly calling `lock()` and `unlock()`
Comment: @BenVoigt Thanks for the tip, but could you elaborate? I just did a quick search and found lock_guard is a local variable and gets unlocked when it is deconstructed. What if I have more lines after unlock in producer, will lock_guard lock those lines too?
Comment: Yes, it unlocks the synchronization object when the guard's destructor runs.  Remember that the lifetime of a local variable is not necessarily the entire function, but the containing scope.  In your example, the guard would be destroyed at the closing brace of the function, but you can always introduce a new block in order to force it earlier.  The advantage is that the guard will free the lock during abnormal control transfers as well as normal exit.
Comment: @BenVoigt Now I see their differences, thanks!
Answer: I'm assuming that the unordered_map named messages starts empty (btw, am I assuming right or is the code not showing this part?), then at line 8:
messages[kname].push_back(make_pair<index, msg>);

we write to messages using the [] operator  which performs an insertion if the key doesn't already exist.
And writing concurrently to an unordered_map is not supported (see this question), therefore a mutex is needed to make these writes sequential.
Comment: You are right, I forgot about the implicit insertion by `[]`. Maybe I should have pre-insert some empty vectors to get a fixed keyset. Thanks!


Proof that $|\sin(nx)| \le n|\sin(x)|$

Question: I have to show that for every $x \in \mathbb{R}$ and every $n \in \mathbb{N}$
$$|\sin(nx)| \le n|\sin(x)|  $$
In the previous exercise, I have showed that $|\sin(x)|≤|x|$ with the use of the mean value theorem. I think that I cannot use this approach this time. I also tried to write $\sin(nx)$ as a series expansion but that doesn't work either.

Does anyone know how I can solve this?
Answer: You can use what you have already proved.
Apply it for "$x=nu$", then you get
$$\vert \sin(nu)\vert\leqslant \vert nu\vert=n\vert u\vert$$
since $n\geqslant 0$.

Edit.
For your new question, you should prove it by induction using the fact that
$$\vert a+b\vert \leqslant \vert a\vert+\vert b\vert.$$
Answer: It is easy to see by induction. Keep the fact that, $|\cos x|\leq 1$. For $n=2$
 $$|\sin(2x)| = |2\sin x \cos x|\leq 2|\sin x |$$
Assuming $|\sin(nx)| \leq n|\sin x|$ and using the addition formula we have
$$|\sin((n+1)x)|  = |\sin nx ~\cos x +\sin x~ \cos nx|\\\overset{|\cos(\cdot)|\leq 1}{\leq}|\sin nx| + |\sin x| \overset{\text{by assumption}}{\leq}(n+1) |\sin x| .$$
For your worry
$$ |\sin(nx)| = |\int_0^{nx} \cos t\, dt\leq |nx|.$$
Answer: $$ |\sin(nx)| = |\int_0^{nx} \cos t\, dt\leq |nx|$$

Proof that $|\sin(nx)| \le n|\sin(x)|$


Need help solving these limits

Question: $$1. \lim_{n \to \infty} \left(\frac{2n^2 + 5}{1 + 5 + ... + (4n - 3)} + \frac{5}{n}\right)$$
$$2. \lim_{x \to -1} \left(\frac{x^4 + 2x^3 + 4x^2 + 6x + 3}{x^3 - 3x^2 - 9x - 5}\right)$$
$$3. \lim_{x \to \infty} \left(\frac{x-1}{14x+5}\right)^{1-3x}$$
$$4. \lim_{x \to 0} (1+\sin{(7x)})^{(\sqrt[\leftroot{-2}\uproot{2}5]{1-9x+x^2}-1)^{-2}}$$
$$5. \lim_{x \to 0} \frac{x \cdot \ln(1+4x^2)}{(1-2x^3)^8-1}$$
Comment: Please show what you have done to solve the problem!
Answer: HINT: for 1) prove by induction that $$\sum_{i=1}^n 4i-3=2n(n+3)$$
for 2) show that $$\frac{x^4+2x^3+4x^2+6x+3}{x^3-3x^2-9x-5}={\frac {{x}^{2}+3}{-5+x}}$$
for 3) the limit doesn't exist
for 4) the limit doesn't exist
for 5) prove by L'Hospital that the limit is given by $$-\frac{1}{4}$$
Comment: Thank you very much, but is there any solution for 5th without L'Hopital's rule? I shouldn't use it here by the task condition...
Answer: HINTS:

1)

$$\lim_{n\to\infty}\left(\frac{2n^2+5}{1+5+\dots+(4n-3)}+\frac{5}{n}\right)=$$
$$\lim_{n\to\infty}\left(\frac{2n^2+5}{\sum_{k=1}^{n}(4k-3)}+\frac{5}{n}\right)=$$
$$\lim_{n\to\infty}\left(\frac{2n^2+5}{2n^2-n}+\frac{5}{n}\right)=$$
$$\lim_{n\to\infty}\frac{2n^2+5}{2n^2-n}+\lim_{n\to\infty}\frac{5}{n}=$$
$$\lim_{n\to\infty}\frac{2n^2+5}{2n^2-n}+0=$$
$$\lim_{n\to\infty}\frac{2n^2+5}{2n^2-n}=$$
$$\lim_{n\to\infty}\frac{2+\frac{5}{n^2}}{2-\frac{1}{n}}=$$
$$\frac{2+0}{2-0}=\frac{2}{2}=1$$

2)
$$\lim_{x\to-1}\frac{x^4+2x^3+4x^2+6x+3}{x^3-3x^2-9x-5}=\lim_{x\to-1}\frac{x^2+3}{x-5}=\frac{(-1)^2+3}{(-1)-5}=-\frac{2}{3}$$
3)
$$\text{L}=\lim_{x\to\infty}\left(\frac{x-1}{14x+5}\right)^{1-3x}=\exp\left(\lim_{x\to\infty}(1-3x)\lim_{x\to\infty}\ln\left(\frac{x-1}{14x+5}\right)\right)$$

$$\text{so when}\space\space x\to\infty\space\space\text{then}\space\space\text{L}\to\infty$$

4) Notice: a two-sided limit does not exist!

$$\lim_{x\to0^-}\left(1+\sin(7x)\right)^{\frac{1}{\left(\sqrt[5]{x^2-9x+1}-1\right)^2}}=\exp\left(\lim_{x\to0^-}\frac{\ln(1+\sin(7x))}{\left(\sqrt[5]{x^2-9x+1}-1\right)^2}\right)=0$$
Comment: Can you explain how you get $$\frac{x^2+3}{x-5}$$ from the original expression? Are you dividing these polynomials?
Comment: $$\frac{x^4+2x^3+4x^2+6x+3}{x^3-3x^2-9x-5}=$$
$$\frac{(x^2+2x+1)(x^2+3)}{(x^2+2x+1)(x-5)}=$$
Cancel terms, assuming $x^2+2x+1\ne0$
$$\frac{x^2+2x+1}{x^2+2x+1}\cdot\frac{x^2+3}{x-5}=$$
$$1\cdot\frac{x^2+3}{x-5}=\frac{x^2+3}{x-5}$$

@Alex, you're welcome!
Comment: Thank you, but in fact, i understand that $$(x+1)^2$$ is a root, i don't understand, how to find these multipliers: $$(x^2+3), (x-5)$$
Comment: And, sorry for my stupidity, can you explain one more thing?
Is that correct? $$\exp(\lim_{x \to \infty} (1-3x) \lim_{x \to \infty} \ln(\frac{x-1}{14x+5})) = e^{\lim_{x \to \infty} (1-3x) \lim_{x \to \infty} \ln(\frac{x-1}{14x+5})}$$

Need help solving these limits


PersistenceController initialization container.loadPersistentStores Crashes Thread 0 unsafeMutableAddressor

Question: I've implemented CoreData in production identically to the suggestion by HackingWithSwift: https://www.hackingwithswift.com/quick-start/swiftui/how-to-configure-core-data-to-work-with-swiftui
This is by far the most common crash reason affecting almost 1% of all users. I was reviewing the organizer crash log in a TechTalk without any results. Therefore, respect if any of you knows the cause:

Here is the specific code used, but as I said, it's as described in the HackingWithSwift article:

I appreciate any help, I've been fighting with this for a while, and I assume others must have the same issue since HackingWithSwift is a popular site. Thank you so much!
class GroupedPersistentContainer: NSPersistentContainer {

    enum URLStrings: String {
        case group = "group.app"
    }

    override class func defaultDirectoryURL() -> URL {
        let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: URLStrings.group.rawValue)

        if !FileManager.default.fileExists(atPath: url!.path) {
            try? FileManager.default.createDirectory(at: url!, withIntermediateDirectories: true, attributes: nil)
        }
        return url!
    }
}

Here is an example of how I use core data in prod for background tasks. This function is only for demonstration but the coding style might be the cause of the issue:
func backgroundCoreDataExample(userinfo: UserInfoProperties) {
    Task {
        // some api call or something else
        PersistenceController.shared.container.performBackgroundTask({ context in
            guard let user = User.fetch(viewContext: context) else {
                completion(false)
                return
            }
            user.userid = Int64(userinfo.userid)
            context.saveIfPossible()
            DispatchQueue.main.async {
                let viewContext = PersistenceController.shared.container.viewContext
                if let user = User.fetch(viewContext: viewContext) {
                    print(user.userid)
                }
            }
        })
    }
}

Here is how I am initialising the singleton
@main
struct YourApp: App {
    let persistenceController = PersistenceController.shared
// …
}

Comment: Need more code & it's threading issue .
Comment: I've updated it with some demo code
Comment: Never mix Task and DispatchQueue. There is a whole WWDC video on CoreData and Concurrency. You should also not be going from async await to completion handlers. That function needs a complete restructure.
Comment: I know this is not optimal. I've used this as a transitionary way to rebuild more and more functions with completion handlers to the swift async await way. However, my rebuilds to (DispatchQueue with Task) here did not introduce or change how often the error occurs.
Comment: I also have this exact crash (stack trace is 1:1 the same). I'm not using any background tasks for accessing CoreData, but I have a widget extension. I guess the widget extension and iOS app simultaneously try to create the persistence store. Any recommendations on what to do?
Answer: It seems to me that this is a deadlock:
As shown in your stack trace, init(inMemory:) is executed on the main thread, but cannot continue (sqlite3LockAndPrepare), since another thread also runs the init, and locks the database.
Thus I suspect that you are using your singleton PersistenceController.shared also on some background thread that runs concurrently to your main thread.
Maybe you could check this.
EDIT:
It is difficult to make a suggestion without knowing the architecture of your app. Maybe you can do the following:
Initialize the singleton very early in your app, e.g.:
SwiftUI:
@main
struct YourApp: App {
    let persistenceController = PersistenceController.shared
// …
}

UIKit:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let persistenceController = PersistenceController.shared
// …
}

Start the background threads only after persistenceController has been initialized.
Comment: Thank you Reinhard, you seem to have good understanding of the problem. Yes, I am using PersistenceController.shared on background threads like in the example above. I assumed that this is the correct way to go here and I've also showed the code to Apple engineers in one-on-one meetings. How else can I access the persistence controller on background threads?
Comment: Please see my edit above. If you get a different suggestion from Apple, please share it.
Comment: This is exactly how I am currently doing it in SwiftUI.
Comment: Hmmm... Are you sure that you don't trigger another init of your singleton, probably on a background thread, before the 1st init succeeded?
Comment: That's hard to tell. However, wouldn't any background thread execute after the @main App is initialized including its persistenceController?
Comment: There are some potential risky spots like .onOpenURL where I use the controller. However, they are all in the body where I'd expect them to execute after the @main init. Do you know any good way to debug these kind of deadlocks? I pretty much agree that a deadlock is the most likely reason for this bug.
Comment: To check when `persistenceController` is used, I would insert log statements in the respective code. These can be displayed in the Xcode console, but are also stored when the app runs without Xcode. They can later be extracted and displayed by the console app. Please check [this blog](https://www.biteinteractive.com/the-joys-of-logging/)
Comment: It's not a good idea, to save the reference of the shared global `persistenceController ` in a _class member variable_. This again makes it susceptible to data races. In order to avoid this, the access to the property `persistenceController` in `MyApp` needs to be explicitly synchronised, either making MyApp and actor or using "old" DispatchQueues, or other means.
Comment: Hi [CouchDeveloper](https://stackoverflow.com/users/465677/couchdeveloper), thanks for your comment. I am sure you are right. I did not think about this. Could you make a suggestion how to do it right?
Answer: Your background function is mixing DispatchQueue and Task, the new "Concurrency" replaces the "old" GCD setup, they should never be mixed.
Concurrency deals directly in terms of "Actors" and GCD uses "Threads".
Apple talks about Core Data and Concurrency in Bring Core Data concurrency to Swift and SwiftUI what you are looking for is around minute 6:50.
It would look something like
func backgroundCoreDataExample(userinfo: UserInfoProperties) async throws -> User {
    let backgroundCtx = PersistenceController.shared.container.newBackgroundContext()

    try await backgroundCtx.perform {
        guard let user = User.fetch(viewContext: backgroundCtx) else {
            throw CustomErrors.unableToFetchUser
        }
        user.userid = Int64(userinfo.userid)
        try backCtx.saveIfPossible() // should throw if saving
    }

    let viewContext = PersistenceController.shared.container.viewContext
    guard let user = User.fetch(viewContext: viewContext) else {
        throw CustomErrors.unableToFetchUser
    }
    return user
}

Then you can call it on something that uses @MainActor such as a UIViewController or a SwiftUI View or a class or struct that has been marked and is dedicated to updating UI.
let task: Task<Void, Never> = Task { // or .task in a SwiftUI View
    do{
        let user = try await backgroundCoreDataExample(userinfo: userInfo)
    }catch{
        print(error) //Catch and display any errors
    }
}

Concurrency has the advantage that you can easily throw errors all the way to the UI so you can present a user friendly description using error.localizedDescription you can also use task.cancel() to stop the Task mid-operation if needed.
You can learn more with Meet async/await
The CustomError I use looks like this.
enum CustomErrors: LocalizedError {
    case unableToFetchUser

    var errorDescription: String?{
        "\(self)".localizedUppercase
    }
}

Comment: Thank you lorem ipsum. I will definitely look into that and I believe that will definitely help me to clean up the code and better identify issues like the one I'm facing right now.


MANUSEIO DO EXPLORER ATRAVÉS DE VBA

Question: Bom dia, estou começando a trabalhar com o VBA então minha dúvida pode ser bem básica, mas meu problema é o seguinte:
Quando eu executo o código (que está abaixo) a parece um alerta de erro na linha do 'For each'

"Erro em tempo de execução '438'.    Objeto não aceita esta
  propriedade ou método"

O código está análogo a outro que peguei de um amigo, apenas fazendo as mudanças pertinentes e o dele está funcionando.
Sub TesteBusca()

Dim ie As Object
Dim sWindows As Object
Dim sJanelas As Object
Dim sDados As String

Set ie = CreateObject("InternetExplorer.Application")

ie.navigate "http://sdro.ons.org.br/SDRO/DIARIO/index.htm"
ie.Visible = True

    Do Until (ie.readyState = 4 And Not ie.Busy)
        DoEvents
    Loop

i = 1
For Each link In ie.document.getElementByTagName("a")

    If Mid(link.href, 8, 22) = "EnergiaNaturalAfluente" Then
    i = i + 1

       With iefat
           .Visible = bMostrarNavegador
           .navigate link.href
       End With

       Do Until (iefat.readyState = 4 And Not iefat.Busy)
         DoEvents
       Loop
    link.Click
    If i = 2 Then Exit For
    End If

Next link

End Sub

Agradeço desde já,
Abs.
Comment: O do seu amigo está no mesmo site? Pois neste da ons, creio que possui um iframe... Então o código do DOM mudaria.
Comment: Não, o site que ele usou foi este "http://sys.sigetplus.com.br/cobranca/transmitter/1191/invoices?agent=5111". Como eu devo fazer para abrir o link, então?
Answer: Código
Você pode realizar isto com este código:
'Declara função Sleep
#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
#End If

Sub TesteBusca()

    Dim IE As Object
    Dim sWindows As Object
    Dim sJanelas As Object
    Dim sDados As String
    Dim doc As MSHTML.HTMLDocument

    Set IE = CreateObject("InternetExplorer.Application")

    IE.navigate "http://sdro.ons.org.br/SDRO/DIARIO/index.htm"
    IE.Visible = True

    EsperaIE IE, 2000

    'Debug.Print IE.document.getElementsByTagName("frame")(1).contentDocument.getElementsByTagName("a").innerText
    i = 1
    For Each link In IE.document.getElementsByTagName("frame")(1).contentDocument.getElementsByTagName("a")
    'Debug.Print EXTRAIRELEMENTO(link.href, 8, "/")
        If EXTRAIRELEMENTO(link.href, 8, "/") = "21_EnergiaNaturalAfluente.html" Then
            i = i + 1

            link.Click
             EsperaIE IE, 2000
            If i = 2 Then Exit For
        End If

    Next link
End Sub

Public Sub EsperaIE(IE As Object, Optional time As Long = 250)
'Código de: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
    Sleep time
    Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.READYSTATE = 4) & _
                vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
    i = i + 1
Loop Until IE.READYSTATE = 4 Or Not IE.Busy
End Sub

Function EXTRAIRELEMENTO(Txt As String, n, Separator As String) As String
    On Error GoTo ErrHandler:
    EXTRAIRELEMENTO = Split(Application.Trim(Mid(Txt, 1)), Separator)(n - 1)
    Exit Function
ErrHandler:
    ' error handling code
    MsgBox "Erro, veriique os dados de entrada."
    EXTRAIRELEMENTO = CVErr(xlErrNA)
    On Error GoTo 0
End Function

Explicação
Extrair Elemento
A Função Definida pelo Usuário (UDF - User Defined Function) de extrair elemento é declarada para extrair os elementos de uma string separados por um separador, neste exemplo "/", em que cada elemento possui um index.
Esta utiliza a função Split para dividir a string em vários elementos a partir de um separador.
E a função Trim é usada para evitar erros quando o espaço é utilizado como separador, pois esta função retira os espaços do início e fim da string.
Exemplo: EXTRAIRELEMENTO("http://sdro.ons.org.br/SDRO/DIARIO/2018_03_15/Html/DIARIO_15-03-2018.xlsx", 1, "/") retorna o valor http:
Outro Exemplo:
EXTRAIRELEMENTO("http://sdro.ons.org.br/SDRO/DIARIO/2018_03_15/Html/DIARIO_15-03-2018.xlsx", 2, "/") retorna o valor `` ou vazio
Outro:
EXTRAIRELEMENTO("http://sdro.ons.org.br/SDRO/DIARIO/2018_03_15/Html/DIARIO_15-03-2018.xlsx", 3, "/") retorna o valor sdro.ons.org.br
Uma função muito útil, que pode ser aplicada para extrair elementos de Strings com separadores, como links, diretórios, códigos de produto, datas,  entre outros.
Espera IE
Normalmente eu utilizo uma função do SOen para realizar a função de esperar um tempo para a página ser carregada completamente, somente While IE.Busy Or IE.ReadyState <> 4: Wend pode não ser suficiente.
Então ao invés de While IE.Busy Or IE.ReadyState <> 4: Wend Você chama a função EsperaIE e escolhe o tempo de espera em ms. Exemplo: EsperaIE IE, 5000
Código principal
Como o site da ONS possui uma hierarquia com iFrames e não somente o HTML "puro". Você precisa procurar pela tag "a" com: IE.document.getElementsByTagName("frame")(1).contentDocument.getElementsByTagName("a"), em que o index da frame é (1), pois o index (0) é do topo da página.

OBS.: Não esqueça de habilitar as referências: Microsoft HTML Object Library e Microsoft Internet Controls.

Em Ferramentas > Referências...
Comment: @LeandroLazari Editei a resposta, você precisa habilitar a referência MS HTML Object Library. E isto é uma função definida pelo usuário, ou seja, uma função customizada criada pelo usuário e não nativa do Excel. Ela foi criada para separar os elementos, onde os dados de entrada dela são Txt, Separator e n. Muitas funções podem ser encontradas na internet e muitas vezes você não precisa entendê-las por complexa (é bom saber o funcionamento), mas para economizar tempo, você pode somente saber os dados de entrada e quais valores/saídas a função retorna.
Comment: Muito bom! Parabéns pela resposta.
Comment: Daniel, muito obrigado pela ajuda!! Só não consegui entender direito a parte o Extrair Elemento o que quer dizar "Split(Application.Trim(Mid(Txt, 1)), Separator)(n - 1)".
E tentei executar o código e aparece "Erro de compilação: o tipo definido pelo usuário não foi definido" e destaca o "doc As MSHTML.HTMLDocument". O que devo fazer?
Comment: Entendi! Primeiramente obrigado! você está sendo de grande ajuda! Mas estou com outra dúvida, o meu próximo passo seria clicar no ícone que faz o download do arquivo xls. Tentei utilizar o mesmo argumento mas alterando o 'If' do 'For Each':

   For Each link In IE.document.getElementsByTagName("frame")(1).contentDocument.getElementsByTagName("a")
    'Debug.Print EXTRAIRELEMENTO(link.href, 8, "/")
        If link.getAttribute("scr") = "../img/exportxls.gif" Then
            i = i + 1

Mas não acontece nada. Se puder me ajudar mais uma vez...
Comment: @LeandroLazari Sugiro criar uma nova pergunta e quando algum usuário estiver livre irá respondê-lo.
Comment: Ok. Obrigado, Daniel!!

MANUSEIO DO EXPLORER ATRAVÉS DE VBA


DPM 2012 R2 Error 30231 - Exchange 2013 Protection Group

Question: Hi all I seem to have an issue with DPM since I have changed over to new local disk storage. I have looked on the TechNet wiki here and the error we are getting is not listed - 30231.
I have changed local storage before and used DPMSync to reallocate protection groups space and after a consistency check, backups resume. This time all backups are working as usual apart from the Exchange Backup. Agent on the DPM server and Exchange server are both version 4.2.1594.0.
I have tried stopping protection for the group, whilst retaining data to keep online data, and this has not helped. I have seen this as a solution elsewhere, but very little else on this error.
Here is some of the error log, its a large log so I've only taken a few snippets that have errors in.
<code>0EB4    2494    08/23   15:47:34.481    27  FindPrincipalServerBlock.cs(249)        5FD400E4-F8D7-46C3-8506-346275EAE85C    NORMAL  Found Principal server for DatasourceId = 15ac89e2-c5fa-49a6-9469-3b5a8b163113 Server= <SERVERNAME>
0EB4    1818    08/23   15:47:34.675    18  fsutils.cpp(4046)           WARNING Failed: Hr: = [0x80070002] : Encountered Failure: : lVal : HRESULT_FROM_WIN32(dwError)
0EB4    1C20    08/23   15:47:35.802    27  FsmBlock.cs(178)        5FD400E4-F8D7-46C3-8506-346275EAE85C    WARNING Backup.ReplicaPreBackupBlock : RAPreBackup, StatusReason = Error (StatusCode = -2137454109, ErrorCode = VSSDatasourceCaptionMismatch, workitem = 26865e42-efaa-4a43-8841-b44f2da04fd4)
0EB4    1C20    08/23   15:47:35.802    27  FsmBlock.cs(178)        5FD400E4-F8D7-46C3-8506-346275EAE85C    WARNING <Status xmlns="http://schemas.microsoft.com/2003/dls/StatusMessages.xsd" StatusCode="-2137454109" Reason="Error" CommandID="RAPreBackup" CommandInstanceID="b726ee56-e0ac-40a1-b23f-f134f6b747cc" GuidWorkItem="26865e42-efaa-4a43-8841-b44f2da04fd4" TETaskInstanceID="5fd400e4-f8d7-46c3-8506-346275eae85c"><ErrorInfo xmlns="http://schemas.microsoft.com/2003/dls/GenericAgentStatus.xsd" ErrorCode="30231" DetailedCode="-2137454109" DetailedSource="2"><Parameter Name="AgentTargetServer" Value="<SERVERNAME>"/></ErrorInfo><RAStatus><RAPreBackup xmlns="http://schemas.microsoft.com/2003/dls/ArchiveAgent/StatusMessages.xsd"><BackupTime>131479768557280000</BackupTime><RAPreBackupSubTaskStatus>Completed</RAPreBackupSubTaskStatus><DSStatus><ComponentName>29f315c6-0df0-4e08-ae1e-39b32614f3c5</ComponentName><LogicalPath>Microsoft Exchange Server\Microsoft Information Store\<SERVERNAME></LogicalPath><BackupStamp></BackupStamp><Metadata></Metadata></DSStatus></RAPreBackup></RAStatus></Status>
0EB4    1C20    08/23   15:47:35.819    27  FsmBlock.cs(130)        5FD400E4-F8D7-46C3-8506-346275EAE85C    WARNING Backup.ReplicaPreBackupBlock : <-- Exited FSM block with FAILURE (errorCode = VSSDatasourceCaptionMismatch) ErrorInfo = VSSDatasourceCaptionMismatch
0EB4    16D8    08/23   15:47:38.990    27  BackupMachine.cs(2185)      5FD400E4-F8D7-46C3-8506-346275EAE85C    WARNING BackupMachine : FAILURE - BACKUP, errorCode=VSSDatasourceCaptionMismatch
0EB4    16D8    08/23   15:47:38.991    01  TaskInstance.cs(803)        5FD400E4-F8D7-46C3-8506-346275EAE85C    WARNING <q1:ErrorInfo ErrorCode="30231" DetailedCode="-2137454109" DetailedSource="2" ExceptionDetails="" xmlns:q1="http://schemas.microsoft.com/2003/dls/GenericAgentStatus.xsd">
</code>
If anyone can help uncover this that would be great.
EDIT - Not sure what has changed but now its throwing 30127 errors, these too are not on any documentation I can find.
Answer: Turns out this is a bit of an ambiguous error code; however, in a certain section of the SCDPM interface it says the caption is incorrect. Someone our end has updated the Exchange database name so its easier to query - spaces removed and shortened - and DPM does not auto refresh server changes, even when recreating a protection group.
I stopped protection, created a new protection group and then refreshed the host details. This picked up the new name of the database and the backup consistency check is current still running whereas before it would fail after 5 seconds.
EDIT - I should have noticed this with the whole VSSDatasourceCaptionMismatch


configure docker network bridge IP for multiple IP alias

Question: I got a Ubuntu host with multiple IP address aliases and I want to expose the ports from docker containers connected to one docker network bridge to a specific IP address of the host and the ports from the other containers to the other IP address of the host.
Answer: I found out how to do this:
<code>docker network create -o "com.docker.network.bridge.host_binding_ipv4"="22.214.171.124" network1
</code>
this way exported ports are available at this IP but not on other IP addresses of the host.
Comment: It should be noted that this creates a bridge interface, and that you cannot create multiple host interfaces which are limited to just one of the IPs on the host, Which is discussed as an open issue here: https://github.com/docker/libnetwork/pull/976


Erro ao importar CSV para o phpMyAdmin

Question: Eu preciso de importar um ficheiro <code>.csv</code> para o phpMyAdmin, mas os caracteres especiais não aparecem, nem o texto que os segue. Qual pode ser o problema?
Comment: O seu arquivo está em UTF-8 ou em ANSI? Tente abrir no [**Notepad++**](http://notepad-plus-plus.org/) e conferir o formato do arquivo e se for o caso converter para UTF-8
Comment: Funcionou, obrigado.
Comment: Vou escrever esta solução como resposta
Answer: Explicação do problema
Normalmente arquivos de texto com caracteres especiais precisam ser salvos em utf-8, da mesma forma os bancos de dados que guardam textos que também possuem caracteres especiais devem ser salvos no mesmo formato.
Desta forma presumo que seu arquivo de texto está no formato ansi, onde o UTF-8 compreende perfeitamente todos os caracteres contemplados pelo ANSI, porém o contrário não acontece.
Portanto sempre que você tenta ler caracteres especiais e um arquivo de texto no formato ANSI usando UTF-8 ele dá erro exatamente no local onde estão os caracteres especiais e o arquivo para de ser lido.
Por este motivo o phpMyAdmin não executa a importação completamente.
Solução
Converta o tipo do arquivo para UTF-8 (recomendo usar o Notepad++) e em seguida realize a importação normalmente.
Answer: Para importar corretamente um arquivo CSV, os campos de auto increment (tipo id) devem estar vazios. Para isso, salve sua planilha do excel no formato csv, deixando o campo de os respectivos campos de ID vazios. Em seguida, abra o arquivo criado em excel pelo notepad.exe e salve novamente o arquivo só que agora com a codificação uft-8. Depois vá ao phpmyadmin e importe o arquivo criado no notepad.exe. Observe marcar a caixa para alterar a primeira linha (onde contém os títulos das colunas), também substitua as caixas com a vírgula (,) por (;) e exclua as aspas (") das respectivas opções.
Answer: Caso o problema persista mesmo após a conversão, pode tentar informar a ordem das colunas no campo com o respectivo nome. Conforme a imagem:

Erro ao importar CSV para o phpMyAdmin


sending image to another activity

Question: I am trying to send an image that in ListView from onItemClick to onCreate method in another activity .
This is my code :
Activity 1
product_imageView= findViewById(R.id.product_imageView);

byte[] image = savedInstanceState.getByteArray("Product image");

 Bitmap receivedImage = BitmapFactory.decodeByteArray(image,0,image.length);

//here it give me error
        product_imageView.setImageResource(receivedImage);

Activity 1
String productimage = productslist.get(position).getProductImage();

Bundle bundle = new Bundle();
                bundle.putByteArray("Product image", productimage.getBytes());
                intent.putExtras(bundle);
                startActivity(intent);

Comment: the amount of bytes one can put into a `Bundle` is limited. better pass the productId.
Comment: how can i do that ? can you provide code
Comment: `bundle.putInt("productId", productslist.get(position).getProductId());`
Comment: save your bitmap in a separate file on storage and pass path uri between activities.
Comment: You might get `TransactionTooLarge` exception if bitmap is large
Answer: Why are you sending images between activities?, why not just place your image in drawable folder and pass the name or path of the image to the next activity and then display or do whatever you want to do with it.
Comment: How can I do that ?
Answer: You do it like this

put your image in drawable folder for example image1.png.
then all you do is parse a string with the name for the image to the second activity example:

   Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                intent.putExtra("image", "image1.png");
                startActivity(intent);

On the second activity you display for instance:

  Intent intent = getIntent();
  String imageStr = intent.getStringExtra("image");
  ImageView imageView = (ImageView)findViewById(R.id.myimage);
  imageView.setImageResource(R.drawable.image1);

I hope code is correct, forgive my mistakes I wrote this in a hurry.
Answer: Please try this
First convert imageview to bitmap.
product_imageView.buildDrawingCache();
Bitmap bitmap = product_imageView.getDrawingCache();

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("BitmapImage", bitmap);

In second Activity please include this line:
  Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");

  imageview.setImageBitmap(bitmap);

sending image to another activity


How to programmatically set a checkbox value of an user account which field is not in /people/accounts/fields

Question: I need to set a checkbox which has an unknown field (machine) name in the user account. the checkboxes are in the user account /user/?/edit

but they doesn't appear as fields in people/accounts/fields and are provided by the
DANSE Content Moderation Module.
I need to update them through a twig template with a custom form controller which works fine, but i cannot find the right way to update the field. I've tried:
<code>$checkarticle = $values->get('checkmailarticle'); //--> field from custom form
$user_load = User::load($userID_current);
$user_load->danse_subscriptions_settings_content_node_article_0_update->value = $checkarticle;
</code>
but where to find the correct
<code>$user_load->"this field name?"->value
</code>
Or is there another way to update the settings?
Comment: I don't understand the question. You just want to alter a form and set a checkbox? If yes, have you tried with altering the form? If yes, have you tried to hook in the form after DANSE has done its work? If your module hook implementation is called before DANSE you can use hook_module_implements_alter to force your module to be called after DANSE.
Comment: The "problem" is the danse module doesn't store the user settings in 'fields', it stores it in the userObject, that i didnt know. After i found this information (which was not easy) i got it done.
Comment: anyone? --------
Answer: because the module stores the settings information in the userObject and not in fields you can use
<code>$userData = \Drupal::service('user.data');
$userData->set('danse', $userID_current, 'content-node-"your content type machine name"-0-publish', 1);
</code>
for set the checkbox on, or
<code>$userData->set('danse', $userID_current, 'content-node-"your content type machine name"-0-publish', 0);
</code>
for set it off
to find the right keys (third argument in the set function) you can log them in the service.php of the danse module


Usando Programação Funcional LISP, responda aos exercícios?

Question: Suponha que foram definidos:
(defun xxx (x) (+ 1 x)) (setf xxx 5)

Qual o valor das seguintes expressões?

(xxx 2)
(xxx (+ (xxx 5) 3))
(+ 4 xxx)
(xxx xxx)
Comment: Porque você não testa isso num interpretador de lisp e vê a resposta? Ou você quer uma explicação sobre a resposta dada?
Comment: Dica, ao testar, use `(print (xxx 2))`, por exemplo.
Comment: Estou aprendendo LISP por conta e não estou entendendo muito bem gostaria de entender nem que fosse com 1 exemplo só o resto me viro !
Comment: Veja esse site: http://rextester.com/l/common_lisp_online_compiler
Comment: Deu certo nesse exemplo do xxx 2 , deu 3 como resultado !. Gostaria de entender a resposta dada .
Answer: Isso daqui define xxx como uma função que soma 1 a xxx:
(defun xxx (x) (+ 1 x))

Isso daqui define xxx como tendo o valor 5:
(setf xxx 5)

O LISP mantém valores e funções separados. Ou seja, você tem uma variável xxx com o valor 5 e uma função xxx que soma mais um.

Quando você faz isso:
(print (xxx 2))

Você está chamando a função xxx e passando-lhe 2 como parâmetro. O resultado é 3.
Com isso:
(print (xxx (+ (xxx 5) 3)))

Você está chamando a função xxx e passando-lhe 5 como parâmetro, resultando em 6. Depois soma 3, que dá 9. Chama a função xxx de novo passando o 9, e dá 10.
Já nisso:
(print (+ 4 xxx))

O xxx é o número 5. Somando com 4 dá 9.
Finalmente, isso:
(print (xxx xxx))

Você chama a função xxx com o valor do xxx (que é 5). Logo, isso resulta em 6.

Veja aqui funcionando no rextester.
Comment: Até eu aprendi agora, @GustavoAryel marque como aceita a resposta.
Comment: Muito Obrigado. Deu para entender bem com sua resposta, ajudou bastante . Grato!


How can I use user fields in panels title

Question: This seems to be basic but I cannot get my head around it and I am rather stuck. I am trying to have a panel override in D7 on the user profile page and access a few fields that I have defined in a user profile type (first name and surname in profile2)
I have added a context of the profile type in the panel and set the title to use the content pane title. I add the profile field, how can I set this field to be the panel title?
Any help welcome please.
Answer: Click on the gear icon on the grey bar for your field you have added, and click set as panel title.
Comment: Thanks for your reply, I've been looking at this problem all day and I realised that the issue is larger than not showing up in title. Page manager and Profile2 don't play well together. Others that encounter same behaviour might find useful this thread http://drupal.org/node/1273026


How run a view in MySQL

Question: From a view, I get the following in the Auto preview Preview with contextual filters:
SELECT node.nid AS nid, node.created AS node_created, node_field_data_field_title.title AS node_field_data_field_title_title, field_data_field_it_ac.field_it_ac_value AS field_data_field_it_ac_field_it_ac_value, field_data_field_clon.field_clon_nid AS field_data_field_clon_field_clon_nid, field_data_field_ts_year.field_ts_year_value AS field_data_field_ts_year_field_ts_year_value, field_data_field_it_volume.field_it_volume_value AS field_data_field_it_volume_field_it_volume_value, field_data_field_it_cl.field_it_cl_value AS field_data_field_it_cl_field_it_cl_value, 'node' AS field_data_field_it_ac_node_entity_type, 'node' AS field_data_field_clon_node_entity_type, 'node' AS field_data_field_taksithetiko_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_title} field_data_field_title ON node.nid = field_data_field_title.entity_id AND field_data_field_title.entity_type = 'node'
LEFT JOIN {node} node_field_data_field_title ON field_data_field_title.field_title_nid = node_field_data_field_title.nid
LEFT JOIN {og_membership} og_membership_node ON node.nid = og_membership_node.etid AND og_membership_node.entity_type = 'node'
LEFT JOIN {field_data_field_deleted} field_data_field_deleted ON node.nid = field_data_field_deleted.entity_id AND field_data_field_deleted.field_deleted_value = '1'
LEFT JOIN {field_data_field_it_ac} field_data_field_it_ac ON node.nid = field_data_field_it_ac.entity_id AND field_data_field_it_ac.entity_type = 'node'
LEFT JOIN {field_data_field_clon} field_data_field_clon ON node.nid = field_data_field_clon.entity_id AND field_data_field_clon.entity_type = 'node'
LEFT JOIN {field_data_field_ts_year} field_data_field_ts_year ON node.nid = field_data_field_ts_year.entity_id AND field_data_field_ts_year.entity_type = 'node'
LEFT JOIN {field_data_field_it_volume} field_data_field_it_volume ON node.nid = field_data_field_it_volume.entity_id AND field_data_field_it_volume.entity_type = 'node'
LEFT JOIN {field_data_field_it_cl} field_data_field_it_cl ON node.nid = field_data_field_it_cl.entity_id AND field_data_field_it_cl.entity_type = 'node'
WHERE (( (og_membership_node.gid = '20' ) )AND(( (node.status = '1') AND (node.type IN  ('item')) AND (field_data_field_deleted.field_deleted_value IS NULL ) )))
ORDER BY field_data_field_it_ac_field_it_ac_value ASC, field_data_field_clon_field_clon_nid ASC, field_data_field_ts_year_field_ts_year_value ASC, field_data_field_it_volume_field_it_volume_value ASC, field_data_field_it_cl_field_it_cl_value ASC
LIMIT 20 OFFSET 0

Which brings in the preview the results I need.
In order to get the same results in MySQL, I run the same query without the brackets {}, and I get irrelevant results... How should the brackets be replaced, how should I alter the above query in order to get the same result I get from the view?
Comment: Ignoring the syntax error, your first and second queries are completely different.  Why would you expect them to return the same results?
Comment: If you don't have a database prefix, then `{og_membership}` would simply be replaced with `og_membership`. I'm afraid I don't really understand the rest of the question. You said you replaced the curly brackets and didn't get the same results, but from the code you've posted, you've changed a lot more than just removing the brackets. Hence my earlier question about why you'd expect the same results when you've completely changed the query
Comment: could you please tell me what {node} stands for? the first query is with the default view settings, and the second with the use of function MYMODULE_views_pre_execute(&$view) {
  dpq($view->build_info['query']);
}
Comment: It doesn't really "stand" for anything, it means the `node` table. The brackets are used to supplement the table name with an optional global prefix that can be enabled when the `$databases` are declared
Comment: yes, but how then the mysql query should be in order to get the proper results from the db say how this should be changed: {og_membership} my problem is i get node ids, insttead of the values i get when the view runs in drupal
Answer: You should remove the square brackets, but also do some other modifications. As this wuold take me too long to debug, you can use hook_views_pre_execute() to view the exact query:
function MYMODULE_views_pre_execute(&$view) {
  dpq($view->build_info['query']);
}

Make sure the Devel module is enabled for this.
Comment: could you please elaborate a bit more, since i have already found this solution to many previous answers, but how exactly should i run it, where should i give my view name, what MYMODULE has to do here, i do not write a custom module.... Yes i have devel module enabled
Comment: If you are not used to creating custom modules yourself, place the above code at the bottom of the devel.module file (inside the "devel" module). Change the word "MYMODULE" by "devel". Then clear caches and go to the page where your view is located. Then, the query should appear. Make sure you remove the code back afterwards.
Comment: please see my edit, did not work

How run a view in MySQL


How to check if string is BSON in C# .net core?

Question: I have login method:
[HttpPost("login")]
public ResponseBody<UserContext> Login([FromBody] RequestBody<Operator> userCredentials)
{}

RequestBody have T Data field.
is it possible to convert this method to be able to handle both JSON and BSON?
Answer: Add BSON support to your API, this artcile should help. And based on request type API can supprort both JSON and BSON.
From article:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.Add(new BsonMediaTypeFormatter());

        // Other Web API configuration not shown...
    }
}

Now if the client requests "application/bson", Web API will use the
  BSON formatter.
Comment: I'am using AutoFac and i can't find where I can add bsonmediatypeformater or AddBsonSerializerFormatters.


Wavelet Theory -- where do I start?

Question: I am in the process of implementing a Fixed-Point Fast Fourier Transform.  The Fixed-Point FFT requires mathematical background in the area of wavelets and lifting schemes.
What are good resources/pre-requisites in order to learn wavelet theory? I have dived head first onto lifting schemes, but quickly realized that I am lacking in the mathematical background.
My math background goes all the way to Differential Equations to Discrete Math with some proofs.  Would like to get a perspective on what I should know first before I do wavelet theory.
Thanks!
Comment: Take a look at Ten Lectures on Wavelets by Daubechies. You will probably want to study functional analysis first, up to Hilbert spaces and their frames. A lot of advanced wavelet theory is about tweaking frames to achieve some desirable effect.
Comment: Also, AFAIK working with wavelets on manifolds other than $\mathbb{R}^n$ requires some harmonic analysis, so if you want to do those, you may want to check it out.
Comment: Thanks! I'll take a look at it.
Answer: Wavelet theory has developed as an interdisciplinary topic, so you'll find literature that explains the subject from the viewpoint of engineers and programmers, mathematicians with a background in discrete math, signal processing, system theory, or functional analysis.
One topic that everybody has to understand is basic Hilbert space theory (Hilbert spaces themselves and linear operators on them). There are a lot of books that cover that.
If your background is in signal processing, I'd recommend

Stéphane Mallat: "A Wavelet Tour of Signal Processing, The Sparse Way", 3rd edition.

This book contains a lot of applications. An introduction that has a stronger focus on the mathematical background is this:

Eugenio Herandez, Guido Weiss: "A First Course on Wavelets" (CRC Press 1996)

(BTW: Did you mean fixed-point FFT algorithms?).
Comment: Yes, I meant fixed point.  I'll give the Mallat book a shot!

Wavelet Theory -- where do I start?


getting Error "The slice reducer for key "weathReducer" returned undefined during intialization in my expo app"

Question: running into Error: The slice reducer for key "weatherReducer" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:6 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:6 in handleError
at node_modules/@react-native/polyfills/error-guard.js:49:36 in ErrorUtils.reportFatalError
at node_modules/metro-runtime/src/polyfills/require.js:204:6 in guardedLoadModule
at http://192.168.0.12:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false:146332:3 in global code

Comment: Then please be aware that in modern Redux you don't need to return state, so if your code looks like that answer, you are probably writing an outdated style of Redux that is about 4x the amount of code needed nowadays. Please read https://redux.js.org/introduction/why-rtk-is-redux-today
Comment: Show your code for that reducer?
Comment: hi, as mentioned by the single answer below i made a rookie mistake, i dint return a default state (equal to initial-state) for the reducer switch statement. That was the error
Comment: Wow , thank you very much , let me go through the article and get back to you.
Answer: In general when writing a reducer function, there is an initialization call which invokes the reducer without an action argument. If you're in that call, you must return initialState.
var initialState = {
  temperature: undefined,
  units: 'celsius',
  isLoading: false,
}

function weatherReducer(state, action) {
  switch(action) {
    case 'SET_TEMPERATURE':
      return { ...state, temperature: action.temperature }
    // ...
    default:
      return state || initialState // <- here
  }
}

Comment: this clears the error , thanks !
Comment: @bitbuoy can you please accept the answer as solution? It's the green check under the votes.


Need help finding (linux compatible) source code for 'pathchar' program

Question: Am unable to locate the source for pathchar (Van Jacobson's wonderful hack - http://www.caida.org/tools/utilities/others/pathchar/) inspite of searching over many places. What happened to it and is it still part of some obscure package on linux?
Please help me find the latest source for pathchar.
Thanks!
EDIT: pathchar isn't around; this page mentions an alternative called clink. Found the source for clink on github.com/AllenDowney/clink
Answer: The page here suggests that there is no source code available for pathchar

... No source code available

However, the page also lists clink as a

A reimplementation of pathchar...
Source freely downloadable.

Perhaps it or one of the other tools on the page will help you.
There is also an email address on the page you link to for the page maintainer - perhaps they can help.
Comment: Thanks; the page for clink is throwing an HTTP 403 (forbidden). :(
Comment: @megazoe: Well contact it's author his email is listed on the first page I linked to.
Comment: Hadn't noticed the first page given; found the source for clink on github now. Thanks


Question about Basic Algebra Rules (Adding something to both sides)

Question: I have a question about basic algebra. Ofcourse, you can add something to both sides to make the equation hold true, but where can you not?
Here for example: $10x(3)=10$ and adding 10 to both sides $10x(3+10)=20$ is not going to hold true. Is there like a list I could look at for those kinds of rules?
I'm watching a video of a teacher explaining how to solve a quadratic equation and he just casually adds something to a multiplication and the same on the other side. So I don't really understood how it's possible since on the one side we are not multiplying and on the other we do, that can't really hold the same value?
Comment: Adding 10 to 10x(3) is 10x(3)+10!  Be careful with brackets
Answer: You have to add the same number to both sides. You added $10(10x)$ to one side and $10$ to the other side.


Silverlight 4 xap request is always redirected

Question: My Windows 8.1 development PC is having trouble loading my Silverlight 4 app, which is hosted inside of an MVC 3 website. I am able to log in to the website just fine, which uses ASP.NET's authentication framework, but when the browser attempts to load the Silverlight XAP file, it gets a 302 redirect back to the login page.
I suspect there is a problem with my IIS configuration, but I am stumped. Any hints or tips would be very much appreciated.
Comment: I suppose its not directly related to SL. Focus on authentication parts.Is there any authentication for SL project or do you use asp.net membership for mvc project only? Maybe SL project doesn't see the session according to the settings. These are just my guesses from your question without much detail. I hope it helps you to focus on right part.
Answer: Register the MIME type for .xap in IIS. Then IIS will serve the file.
application/x-silverlight-app
Comment: Those were already configured on my dev machine. Do you have any other ideas?