"Hidden" axiom of choice?

Question: Let $\mu$ be a measure on $S$ such that:

$\mu\left(\emptyset\right)=0$ and $\mu(S)=1$
if $X\subseteq Y$, then $\mu(X)\leq\mu(Y)$
$\mu\left(\{a\}\right)=0$ for all $a\in S$
if $X_n$, $n=0,1,2,\ldots$, are pairwise disjoint, then $\displaystyle\mu\left(\bigcup \limits_{n=0}^\infty X_n\right)=\sum \limits_{n=0}^\infty\mu(X_n)$
$\mu$ is two-valued, i.e. $\mu(X)=1$ or $\mu(X)=0$ for all $X$

Let $U=\{X\subseteq S\colon\mu(X)=1\}$. $U$ is a non principal ultrafilter on $S$, and this implies a weaker axiom of choice.
I'm not sure where I used it, but I guess it's in that measure. Can you show me an example of such a measure? Alternatively, can you tell me where I need $\sf AC$ if it's not in the measure?
Edit: Let $S$ be uncountable and $\mu\left(X\right)=0$ if $X$ is finite or countable. It seems to me that this measure can be construct without any assumption about $\sf AC$. And this leads to a nonprincipal ultrafilter, which in fact does require some weak form of $\sf AC$? I still don't understand..
Comment: "Let $\mu$ be..." presupposes a $\mu$ satisfying those properties exists, which does indeed rely on AC.
Comment: Is your measure defined on all subsets of $S$? Such a measure could't even be shown to exist with the axiom of choice.
Comment: To use the $\sf AC$ you need a proof or a reasoning of some sorts, there is none here.
Comment: I'm sorry, this example came from Jech's _Set theory_ pages 125-126. I just want to know why does this construction rely on AC since I can't see it.
Comment: @izabera: Your construction of a nonprincipal ultrafilter doesn't rely on the AC: you have correctly provided a construction independent of the AC that turns such a $\mu$ into a nonprincipal ultrafilter. What you *haven't* done is try to construct $\mu$, or show such a thing exists.
Comment: What sort of weak version of the axiom of choice do you expect to prove from this? What is the quantifier on the set $S$?
Comment: @MichaelGreinecker This measure is not translation invariant.
Comment: @izabera I did not write "can be shown not to exist". A measure of this kind must be defined on the powerset of a *measurable cardinal*. The existence of such a cardinal is widely believed to be consistent, but a relative consistency proof is not possible. Look [here](http://mathoverflow.net/questions/136134/do-measurable-cardinals-exist-assuming-zfc).
Comment: The notion of translation requires $S$ to be a group to begin with. Is it a group?
Comment: The filter of co-finite sets [given in the Edit] doesn't need AC-- it's the existence of an ultrafilter (in which EVERY set is measuarable), extending that filter which needs (some weakened version of) AC. I assume "for all X" in the last bullet means "all subsets X of S."
Answer: Think about how such a $\mu$ would be created.  We know its value for finite sets.  Now we go through the infinite sets on at a time.  The first set is $A$.  Decide $\mu(A) = 1$.  Then necessarily $\mu(A^c) = 0$.  Now go to the next set, call it $B$.  If $B$ is in the sigma algebra generated by the finite sets and $A$, then the value is known.  Otherwise set $\mu(B) = 1$, and look at the next infinite set.
You will have to make these choices again and again.  In fact you will have to make these choices a transfinite number of times.  Since you have to make infinitely many choices, the axiom of choice has to be invoked.
Is it possible that there exists a clever argument to find a $\mu$ in a more constructive manner?  The only way to show this cannot be done is to prove there exists models of set theory in which such a $\mu$ doesn't exist.  And I believe that this has been done.
Comment: You probably must emphasize that you are not giving a proof that choice is used to build $\mu$, only an intuitive argument.
Comment: That is what I was trying to say with my last paragraph.  I'll slightly edit it to make it clearer?
Comment: One issue here is that your description already uses a well-ordering of $\mathcal P(S)$, but the existence of a non-principal ultrafilter on $S$ is strictly weaker, so your conclusion is flawed: there are other ways of "building" $\mu$, and these ways are more "constructive" than you suggest.
Comment: @AndresCaicedo I thought that the existence of a non-principle ultrafilter was independent of ZF.  What are the "more constructive" ways of making non-principle ultrafilters?  I guess I thought it was just an axiom that you could use instead of AC, that happens to be strictly weaker.
Comment: What I mean is; The axiom of choice is strictly stronger than the statement that $\mathcal P(\mathbb N)$ can be well-ordered, which is strictly stronger than the statement that there is a non-principal ultrafilter on $\mathbb N$, which is still not provable in $\mathsf{ZF}$. Of course, we can interpolate many more statements in this list.
Comment: @StephenMontgomery-Smith I edited the question, is that example constructive enough?
Comment: It doesn't work.  Think about $X_1$ and $X_2$ being two disjoint uncountable sets.
Comment: @StephenMontgomery-Smith The measure is $0$ if the set is finite or countable, but it may be $0$ in other cases too...
Comment: To construct the measure, you have to specify which sets have measure zero and which have measure one.  You haven't defined the measure, because if I give you any set which is uncountable and whose complement is uncountable, then there is no way I can tell from your definition what its measure is.
Comment: Yeah I kinda realized that's where it requires a "choice"

"Hidden" axiom of choice?


Relationship between coefficients of a polynomials and its roots.

Question: The roots of the equation $x^4 -3x^2 + 5x - 2 = 0$ are $\alpha$, $\beta$, $\gamma$ and $\delta$.   $\alpha^n + \beta^n + \gamma^n + \delta^n$ is denoted by $S(n)$. Find values of $S(2)$ and $S(4)$ and of $S(3)$ and $S(5)$.
Hence, find the value of
$\alpha^2 (\beta^3 + \gamma^3 + \delta^3) + \beta^2 ( \alpha^3 + \gamma^3 + \delta^3) + \gamma^2 (\alpha^3 + \beta^3 + \delta^3) + \delta^2 (\alpha^3 + \beta^3 + \gamma^3)$
This topic is a rather strange one, and I can't seem to locate the formulas I need, and I need them for my exam. If you do use any formula (except $\sum\alpha$, $\sum\alpha\beta$, $\sum\alpha\beta\gamma$ and $\alpha\beta\gamma\delta$), please state it. Thank you in advance.
Comment: The coefficients of the equation are the [elementary symmetric polynomials](http://en.wikipedia.org/wiki/Elementary_symmetric_polynomial) in the roots.  The $S(n) are the [power sum symmetric polynomials](http://en.wikipedia.org/wiki/Symmetric_polynomial#Power-sum_symmetric_polynomials).  It is a theorem that you can write the latter in terms of the former.  The trick is to do so explicitly.  The algorithm to write one symmetric polynomial in terms of a family of others is to construct a polynomial whose leading coefficient agrees with the first, subtract, and repeat.
Comment: Newton's identities (http://en.wikipedia.org/wiki/Newton%27s_identities) are helpful here.
Answer: $$S(2)=\left(\sum\alpha\right)^2-2\sum\alpha\beta$$
$$S(3)=\left(S(2)-\sum\alpha\beta\right)\left(\sum\alpha\right)+3\sum\alpha\beta\gamma$$
See here to verify the second identity.Now, summing cyclically we have:
$$S(4)-3S(2)+5S(1)-8=0$$
More generally, multiplying by $x^n$ and summing cyclicaclly we get the recurrence relation:
$$S(n+4)-3S(n+2)+5S(n+1)-2S(n)=0$$

Finally, for your bizarre looking last expression, we have
$$\sum a^2\left(S(3)-\alpha^3\right)=S(3)\sum a^2-\sum\alpha^5=S(2)S(3)-S(5)$$
Comment: I cannot thank you enough for that general formula and answers. However, I don't understand that last expression. Why do you subtract $α^3$ from $s(3)$ ?
Comment: @George You're welcome :) That is because $\alpha^2(\beta^3+\gamma^3+\delta^3)=\alpha^2(\alpha^3+\beta^3+\gamma^3+\delta^3-\alpha^3)=\alpha^2(S(3)-\alpha^3)$ . I would also recommend reading the links in the comments, because it gives the general case.
Answer: Denote
$A(1) = \alpha+\beta+\gamma+\delta  = 0$;

$A(2) = \alpha\beta+...+\gamma\delta  = -3$;

$A(3) = \alpha\beta\gamma +...+\beta\gamma\delta  = -5$;

$A(4) = \alpha\beta\gamma\delta  = -2$.
Applying Newton's identities, we obtain
$S(1) = A(1) = 0$;

$S(2) = A(1) S(1) - 2A(2) = 0+6=6$;

$S(3) = A(1) S(2) - A(2)S(1) + 3A(3) = 0+0-15=-15$;

$S(4) = A(1) S(3) - A(2)S(2) + A(3)S(1) - 4A(4) = 0+18+0+8=26$;

$S(5) = A(1) S(4) - A(2)S(3) + A(3)S(2) - A(4)S(1) + 5A(5) = 0-45-30+0+0=-75$

(one can obtain last identity, when consider equation $x^5-3x^3+5x^2-2x=0$ with $5$ roots $\alpha,\beta,\gamma,\delta,0$, where $A(5)=0$, and previous $A(n)$ are the same).

Easy to see, that
$$\alpha^2 (\beta^3 + \gamma^3 + \delta^3) + \beta^2 ( \alpha^3 + \gamma^3 + \delta^3) + \gamma^2 (\alpha^3 + \beta^3 + \delta^3) + \delta^2 (\alpha^3 + \beta^3 + \gamma^3)$$
$$=\alpha^2 (\alpha^3+\beta^3 + \gamma^3 + \delta^3) + \beta^2 ( \alpha^3 + \beta^3+\gamma^3 + \delta^3) + \gamma^2 (\alpha^3 + \beta^3 + \gamma^3+\delta^3) + \delta^2 (\alpha^3 + \beta^3 + \gamma^3 + \delta^3) - \alpha^5-\beta^5-\gamma^5-\delta^5$$
$$
= (\alpha^2+\beta^2 + \gamma^2 + \delta^2)(\alpha^3+\beta^3 + \gamma^3 + \delta^3)
- \alpha^5-\beta^5-\gamma^5-\delta^5 = S(2)S(3)-S(5).
$$
$$
= 6\cdot (-15) - (-75) = -90+75=-15.
$$

Note:
equation $x^4-3x^2+5x-2=0$ has $2$ real and $2$ complex roots:

$x_1\approx -2.344470$;

$x_2\approx 0.578277$;

$x_{3,4} \approx 0.883096 \pm 0.833866i$.
Comment: Thank you, the last part was made clear with the second part. The link to Newton's identities isn't very clear (I am not too familiar with the language), and the comment above gave me another equation ($S(n+4)−3S(n+2)+5S(n+1)−2S(n)=0$) with which I solved using $S(-1)$. If you would be so kind as to say the general equation (as a sum) using your notation of $A(n)$ and $S(n)$ so that you could clear it up, please?
Comment: @George, Newton's identities (in my notation) will look like
$$
kA(k) = \sum_{j=1}^k (-1)^{j-1} A(k-j)S(k), \tag{1}
$$
or
$$
kA(k) = \sum_{j=0}^{k-1} (-1)^{k-j+1} A(k)S(k-j),\tag{2}
$$
where $A(0) = 1$.

If you'll consider equation
$$
(x^4-3x^2+ 5x-2)x^n=0,
$$
you'll have $A(0)$, $...$, $A(4)$ as were earlier, but $A(5)=...=A(n+4)=0$.

So, for $k=n+4$ you'll get (looking at $(2)$)

$$
(n+4) \underbrace{A(n+4)}_{=0} = A(0)S(n+4) - A(1)S(n+3) + A(2)S(n+2) - A(3)S(n+1)+A(4)S(n) - 0+0-0+...;
$$
so
$$
0 = A(0)S(n+4) - A(1)S(n+3) + A(2)S(n+2) - A(3)S(n+1)+A(4)S(n).
$$


C printf: insert line above printed text

Question: I want to print with printf above printed lines WITHOUT overwriting old ones. The code below prints
0
1
Hallo
A0
A1
A2
A3
A4

I want the output to be
0
1
Hallo
A0
A1
A2
A3
A4
2
3
4

Is there a possibilty to do this with escape codes (like line up)?
#include "stdio.h"

#define ANSI_LINE_UP                "\033[3A"

int main() {
    for (int i = 0; i < 5; i++) {
        printf("%d\n", i);
    }

    printf(ANSI_LINE_UP "Hallo\n");
    for (int i = 0; i < 5; i++) {
        printf("A%d\n", i);
    }

    return 0;
}

I use Kubuntu 18.04, if this is relevant.
To make it a bit clearer what I want:
I want to have the output of some printf at the end, so it looks like this:
printf(...)
   printf(...)
specialprintf(,,,)
   specialprintf(,,,)
Note: The order of all prints might be different while execution. I just need the normal ones first, then the special ones. If the special ones are in a different order, it is still fine.
This is part of an embedded project. @Arkku solution is good, but I don't quite get it working as I want.
Comment: Do you have a real case or just curious? Your example does not make much sence because it could be easily done by modifying order of `printf`s, and escape codes are generally neither portable nor easy to use.
Comment: I had hoped that ANSI insert line ("\033[3L") would do the trick, but I tried it and it doesn't work (at least not on macOS using the Terminal app)
Comment: let me know my edit is proper one.
Comment: The most portable way would be to use [ncurses](https://www.gnu.org/software/ncurses/).
Comment: This is just a simple example. I want to do something more complex but it should do the same.
Comment: It must work using printf as this should also work while printing text via UART from a micro controller. I can't use ncurses there.
Comment: In light of additional comments, it seems that the real question is entirely different from this. I suggest asking another question with the actual problem, since multithreaded access to a single terminal is definitely not the question you asked here.
Comment: The multi threading is no issue, everything is protected by semaphores. I just have to figure out how many lines I have to move around. I think @Arkku has solved it, I will mark it as solution when I solved my last few problems. Thanks a lot for your help.
Answer: Obviously this depends on what your terminal supports, but in case it supports the \033[<count>L insertion, it should work as follows:
int main() {
    const int up_lines = 3;
    const int new_lines = 6;

    for (int i = 0; i < 5; ++i) {
        printf("%d\n", i);
    }

    for (int i = 0; i < new_lines; ++i) {
        // make space for existing lines to move down
        putchar('\n');
    }
    // move up and insert the new (empty lines)
    printf("\033[%dA\033[%dL", up_lines + new_lines, new_lines);

    for (int i = 0; i < new_lines; ++i) {
        printf("A%d\n", i);
    }

    // move back down below original lines
    printf("\033[%dB", up_lines);

    return 0;
}

Basically you first make room for the original lines to move down by outputting a number of newlines equal or greater to the number of lines you mean to insert (this step becomes relevant when the terminal position is so near the bottom that the old lines would move off screen). Then you move up to the insertion position (which has now moved by the number of newlines you printed) and insert the number of lines with \033[<count>L.
edit: Obviously you can repeat this as many times as you like, i.e., you don't have to know in advance how many lines you will insert and where, as long as you move back down to the last line after every batch of inserts. For example, you could insert one line at a time by always printing just one newline at the bottom, then moving up to the insertion position (remembering to account for the one line you just added in between), inserting the line there, and moving back down to the bottom.
Comment: It works in this example, however I don't know how many lines will be inserted. I want to print some output at the end, so I have to get the cursor up after printing these special lines. I don't want to overwrite other lines, it would be just a nice feature. Thanks for your quick answer.
Comment: @Icebear You don't have to know how many lines will be inserted: you can use this same technique to insert any number of lines at a time in any position as many times as you like. For example, to insert one line at a time, print one newline, move up to the position, insert the line, move back down, repeat as many times as you want.
Comment: @Icebear Alternatively, instead of dynamically printing the empty lines, obtain the height of the terminal and fill one screen in the beginning, then move up to the top and operate within that space.
Comment: It is part of an embedded project. I want to print some lines generated by different threads independently from each other. Thread A has no way to find out how much Thread B has printed. I thought there might be something like an insertion mode.
Comment: @Icebear You don't need to find out how much another thread has printed, just how many positions up you want to move from the current position. Move up by that much, insert, move down by the same amount. Or if you are thinking that each thread has an independent cursor where they can just insert without moving up, that was never going to work since the terminal is a shared resource… (Not to mention it would be an entirely different question, e.g., "how to maintain independent cursor positions for multiple threads on the same terminal".)
Comment: @Icebear Meanwhile "thread A has no way to find out how much thread B has printed" is not true: you should mutex access to the terminal anyways, so if only one thread holds the terminal at a given time, they can also hold a shared variable that tracks the number of lines or cursor position or whatever.
Comment: The problem, I posted here is now solved. I have my embedded problem nearly solved. I use a RTOS that protects printf automatically.


GHCI vs compiled function difference

Question: The goal is to input a float and return a string containing only the absolute value of the digits before the dot.
Basically putting in -14.4 should return "14"
When I type in the sequence of instructions via GHCI I run into no problem.
Yet when I use it in a compiled function like this:
testFront :: Float -> String
testFront x = tillDot $ show $ abs $ x

tillDot :: String -> String
tillDot x = case x of
  [] -> ""
  x -> takeWhile (/= '.') x

then suddenly I run into the error shown in the the screenshot.

I figured out that I had to put the negative number using ().
The question is: Can I somehow do this within the file? Something that automatically puts my input into ()? Or do I have to write a seperate function that does that?
Comment: It's interesting that you started your GHCi session with `abs $ -14.4` instead of `abs -14.4` which would have raised the same error. Later on you then use `testFront -14.4` and not `testFront $ -14.4` which would have worked.
Answer:
The question is: Can I somehow do this within the file? Something that automatically puts my input into ()? Or do I have to write a seperate function that does that?

The reason you need to wrap these into parenthesis is because there is a difference between:
f - 14

and:
f (-14)

Indeed, for the former it will subtract 14 from the value of a variable named f. If f is for example 25, it will return 11.
For the latter it will call a function f with -14 as argument.
Except for a minus, no operator has an unary form. The parenthesis are thus necessary to disambiguate between the unary and binary form.
Comment: @VulpesNix `f -1` does not call function `f`, it calls function `(-)` (subtraction) with arguments `f` and `1`. There's nothing you can do in `f` to prevent this.
Comment: @VulpesNix: well it is indeed different than most other programming languages, and that makes it annoying. But t.b.h. after a while one gets used to it, and actually it makes the language simpler imho. In fact one could also see `(-14)` as *operator sectioning* and a function, and it is thus a bit "ugly" that this is an exception in a language that is otherwise actually quite consistent.
Comment: @VulpesNix There is a GHC extension that can address this to some extent: [`-XNegativeLiterals`](https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/negative_literals.html#extension-NegativeLiterals)
Comment: So I assume this means that the user is forced to put their negative number into () parenthesis and that I can't somehow convert the unary into binary form, right?
Comment: @VulpesNix: indeed. The function also does not "know" the expression of the parameter, so you can not fix this. If I recall correctly there has been a lot of discussion about whether to allow an unary minus in the first place, and not just use `f (negate 14)`, so to prevent ever writing something like `f (-14)` in the first place for an unary minus, since it is the one (and only) exception in the entire language.
Comment: Thanks a lot! Bit annoying but I guess that's Haskell :)

GHCI vs compiled function difference


The property 'name' is part of the object's key information and cannot be modified. Entity Framework

Question: I am trying to update a record and I get this error message after the context.SaveChanges();

The property 'name' is part of the object's key information and cannot be modified.

Here is the code for the update function:
 if (context.EAT_SourceNames.Any(e => e.name == newSourceName))
 {
    MessageBox.Show("Name already exists in the Database");
 }
 else
 {
    var nameToUpdate = context.EAT_SourceNames.SingleOrDefault(e => e.name == sourceName.name);
    if (nameToUpdate != null)
    {
       nameToUpdate.name = newSourceName;
       context.SaveChanges();
       RefreshDGVs();
     }
 }

My SourceNames class looks like the following:
    public EAT_SourceNames()
    {
        this.EAT_Sources = new ObservableListSource<EAT_Sources>();
    }

    public string name { get; set; }
    public string version_id { get; set; }
    public string allocation_name { get; set; }

I searched for similar questions, but could not find any working solution.
Comment: Is there a PK on the table at all? If not, EF uses all of the fields/columns as part of the "key information."
Comment: Note that there is an intermediate step between explicitly declaring an ID and using all required columns as ID: if you have a field "Id" or of form "Id" (so SourceNamesId), it will use that as a single PK instead.
Comment: Dit you generate your model from the database or vice-versa (database-first or code-first)?    Is `name` a primary key on the database table?  Are you trying to update the original record or copy to a new one with a new key?
Comment: I doubt there is a "solution". Keys are used in the database to connect tables together, so you're normally prevented from modifying records that are part of the key unless you do so in both tables. We can't tell the relationships that your table might have, because you haven't posted that information.
Answer: See the answer from yildizm85 to this question: entity framework not working on table without identity column
"Entity Framework requires a Primary Key to generate a model from the database. If there is no Primary Key on a table it will simply select the non-nullable columns as a concatenated primary key and the Entity will be read/only."
Looking at your EAT_SourceNames object it appears there is no primary key field so the Entity Framework is using the column 'name' as part of the composite key which means it is read-only.
The solution would be to add a Primary Key field to EAT_SourceNames and then your 'name' field would no longer be part of the primary key.
Comment: I did not know this... I try to make it reflex to add a primary key, but it can be an easy mistake. This is good to know.
Comment: 'Name' was a primary key in our table, we added a new Primary Key 'id'. Thanks!
Answer: Same happened to me today. I set new entity's ID with the old record's ID and the error is gone.
//This checks whether there's a record with same specific data.
var kayitVarMi = _db.Sorgu.FirstOrDefault(a => a.Serial == sorgu.Serial);

                if (kayitVarMi != null) // If there's
                {
                    sorgu.Id = kayitVarMi.Id; //This one does the trick
                    _db.Entry(kayitVarMi).CurrentValues.SetValues(sorgu);
                }
                else // If not
                {
                    _db.Sorgu.Add(sorgu);
                }

                // This whole block is in a transaction scope so I just check recordability.
                if (_db.SaveChanges() > 0)
                {
                    _sorguKaydedildiMi = true;
                }

Answer: Here is the proper solution of it.
You have to  unchecked entity key of Name from your EAT_SourceNames.
You can do this by following steps.

Open your .edmx file.
Right click on your display and select Mapping Details.
Click  on Model Browser and you will find it at right side of your screen.
Now In that go to Entity Types folder and click on your table in your case EAT_SourceName.
Now you will find the model of EAT_SourceName , now right click on name and uncheck Entity Keys.
Now Clean and Rebuild your Solution.
Answer: The only way I can think to update a text primary key is by using the following.
I do not believe it is best practice to use a "functional" primary key.  A primary key's purpose is simply to uniquely identify a row.
context.Database.ExecuteSqlCommand("UPDATE Table SET [Name] = {0} WHERE [Name] = {1}", nameProperty, oldNameProperty);

Answer: Probably  name is a part or full Primary Key for your EAT_SourceNames entity.
You cannot modify object's PK, is it EF's limitation (see this thread).
Answer: The point is that you work with an object. The "name" property identifies the object, that's why you can't modify it.
The solution is to modify the value in the table with a SQL statement (UPDATE) and reload the context.
Sincerely.


Give an example of a non-self-adjoint operator on a Hilbert space $H$ whose range is $H$ and which is not invertible.

Question: Give an example of a non-self-adjoint operator on a Hilbert space $H$ whose range is $H$ and which is not invertible.
I cannot think of an example to save my life. Any solutions/hints are greatly appreciated.
Comment: By the rank nullity theorem, any $H$ with such a map must be infinite-dimensional.
Comment: Think about left and right shift!
Answer: The canonical example would be the reverse shift on $\ell^2 (\mathbb N) $. That is, the operator  $T $ given by $$T (a_1,a_2,\ldots)=(a_2,a_3,\ldots). $$
Answer: How about the shift map on $\ell^2(\mathbb{N})$?
Comment: How do you define it for $\ell^2(\mathbb{R})$?
Comment: @Freeze_S Oops.  Typo.  I intended $l^2(\mathbb{N})$, just as the answer above me.  Didn't want to totally give it away though.
Comment: Do you know `\ell` which gives "$\ell$"?
Comment: @Freeze_S Just saw that!  I do not deal with these spaces on a daily basis, so it has never really come up for me.


ACL's Permissions and Business Logic

Question: I would like to know where people draw the boundary between assigning permissions to a user in a muliti user appliction and the business logic.
For example if a user can have permission to access a number of cars do you assign these permissions directly through the user class by adding them to a collection of car objects on the user or do you assign them in the ACL and use the ACL to retrieve the list of cars that the user has access to?
Are there any guidelines for when you should use the ACL for this sort of thing and when it should be part of the business logic?
Answer: Normal practice is "role based security".
For instance you might set up two roles "salesperson" and "maintainence".
"salesperson"s would have permision to drive,refuel and park a set of cars.
"maintenance"ers would have permision to drive, service and repair the set of cars.
You would than allocate your employees to one or other of the roles.
Comment: Yes but you could also but salesperson and maintenance as part of your domain model as subclasses of employee and assign the relationship through an association to the car class.  Is this better or worse than using the role based security approach.
Comment: Usually the answer is "Yes" as you can group things like login, network, file access etc. into an OS based ACL. In this way when a new salesperson is hired you just add them into the group and thay get all the access they need.

ACL's Permissions and Business Logic


Modify loaded input field value with AngularJS

Question: I am using AngularJS as part of the MEAN stack. I have a model represented by job. job.tag is an attribute of the model represented by an array. The code below is the input field on a page used to edit the job attributes (the job has already been created with an array of various strings represented by job.tag).
<input data-ng-model="job.tag" type="text" id="tag" maxlength="50">

When the page used to edit the attributes is loaded - the input field is populated by a string representing the array which looks like "x,y,z" - when the array is converted into a string (the value which populates the text input field), commas are used to separate each element in the array. When the field is populated, how do I replace the commas with a whitespace, so the field displays "x y z"?
Comment: you could use a custom filter: `ng-model="job.tab | take-out-comma-filter`.
Answer: What you need to realize is that your model is an array and your input is expecting a string.
By default, javascript converts an array into a string (via array#toString) with array#join dash separated.
More than that, If your try to change the view it will override your array model with the string from the input. This is how ngModel two-way-data-binding works.
Fortunately , ngModel is so awesome that it allows you to intercept the two-way-binding with your own formatters and parsers. The $viewValue and the $modelValue` can have different values, and the binding is fully configurable.
use ngModelController:

$formatters to format / convert model -> view
$parsers to format / convert view -> model

Here is a plunker: http://plnkr.co/edit/HFjDHCHnBOStmYjk84ub?p=preview
A simple directive:
app.directive('array', function(){
  return {
    require: 'ngModel',
    link: function(scope,elm,attrs,ngModel){

      ngModel.$parsers.push(function(str){
        return str.split(/\s+/)
      })

      ngModel.$formatters.push(function(arr){
        return arr.join(' ');
      });
    }
  }
})

And the markup:
<input data-ng-model="job.tag"
       type="text"
       id="tag"
       data-array
       maxlength="50">

Answer: Have you checked the javascript string object utility functions such as replace()?
http://www.w3schools.com/jsref/jsref_replace.asp
Comment: yes...I know how replace works - and that is what I am using to substitute, I just don't know how to implement it.


How to hide or keep away /node

Question: I want to avoid the URL pointing to a node on my site contains the "node" part (e.g. http://example.com/node/1). Is it possible?
Answer: You need the Path module for URL aliases. (It is a Drupal core module.)
Once the module is enabled, you can edit a node, and set a path alias for the node. Now, you can access your node through the path alias you just created.
Drupal will use the path alias you set as URL for the node, except for sub-paths (e.g. node/1/edit).
Answer: The best way is using Pathauto module. It's suitable for your work.
The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
Answer: You can use the Path module for the URL alias, and for every pages use a path alias.

How to hide or keep away /node


Vite CommonJS Resolver throws Unexpected Token Error when importing ESM

Question: I have a create-react-app project I'm migrating to Vite. That project uses "styled-components" like this:
import styled from 'styled-components';

const someDiv = styled.div`...`;

Now the issue comes up when running vite build:
vite v4.0.2 building for production...
✓ 51 modules transformed.
[commonjs--resolver] Unexpected token (1:167492) in /project/node_modules/styled-components/dist/styled-components.browser.esm.js
file: /project/node_modules/styled-components/dist/styled-components.browser.esm.js:1:167492
1: import{typeOf as e,isElement as t,isValidElementType as n}from"react-is";import r,{useState as o,useContext as i,useMemo as s,useEffect as a,useRef as c,createElement as u,useDebugValue as l,useLayoutEffect as d}from"react";import h from"shallowequal";import p from"@emotion/stylis";import f from"@emotion/unitless";import m from"@emotion/is-prop-valid";import y from"hoist-non-react-statics";function // ... rest of file

So it seems like it is trying to import styled-components.browser.esm.js using the commonjs--resolver, but there are import statements at the top of that file and it seems to get confused.
Any ideas why the "Unexpected token" error might happen and how this can be resolved? Shouldn't it import it as ESM?
UPDATE 07/02/2023:
On a Github discussion it was noticed by someone else, that everything works when there is no define block in the vite.config.ts: https://github.com/vitejs/vite/discussions/11495.
However, this is a questionable solution if you actually need to define something there.
Answer: I opened a bug report with Vite and it turns out the issues is about how define works, it replaces the word "process" everywhere with what is put into define in the vite config, leading to the syntax/token errors.
Detailed answer is here: https://github.com/vitejs/vite/issues/12246#issuecomment-1450153095
Answer: From Vite documentation: https://vitejs.dev/guide/env-and-mode.html

For JavaScript strings, you can break the string up with a Unicode zero-width space, e.g. 'import.meta\u200b.env.MODE'.

For Vue templates or other HTML that gets compiled into JavaScript strings, you can use the  tag, e.g. import.meta.env.MODE

So my define became:
 define: {
    'process.<wbr>env': {}


due to which characters it does not work json_decode() ? - PHP

Question: I have a javascript file with an array inside and I would like to include the javascript in a php file, extract the array and convert it to php.
Strangely json_decode() doesn't work, probably due to some characters.
Can you tell me which characters are not allowed and why?
$file_contents = 'var dati_login = [["1111","2021-10-30"],["_fbp=fb1111152; i18next=en-US; cookielaw_accepted=1; _ga=GA1.1.1111.1611118; e2sid=11115; _lr_uf_-qrlpn5=111-e111e-424c-9043-1111; _lr_tabs_-qrlpn5/e2={"sessionID":0,"recordingID":"111159d18955a","lastActivity":163480041112}; _lr_hb_-qrlpn5/e2={"heartbeat":1118402}; _ga_THFZJ5FYF8=GS1.1.11188.8.131.521468.0","2021-10-30"]]';
$json_string = substr($file_contents,strpos($file_contents,'['));
$array_dati = json_decode($json_string);    //ecco l'array in php
print_r($array_dati);

but json_decode() not work...
i know the problem is in array[1][0] but i don't understan which characters....
Comment: Go to  and find out for yourself
Answer: you need to encode the inner data of $file_contents to \"
$file_contents = 'var dati_login = [["1111","2021-10-30"],["_fbp=fb1111152; i18next=en-US; cookielaw_accepted=1; _ga=GA1.1.1111.1611118; e2sid=11115; _lr_uf_-qrlpn5=111-e111e-424c-9043-1111; _lr_tabs_-qrlpn5/e2={\"sessionID\":0,\"recordingID\":\"111159d18955a\",\"lastActivity\":163480041112}; _lr_hb_-qrlpn5/e2={\"heartbeat\":1118402}; _ga_THFZJ5FYF8=GS1.1.1118.104.22.1681468.0","2021-10-30"]]';

Comment: ok but how can i do this with php ?
Comment: It is all the depend on what is the source of your data? who builds it? on what stage?


CKEditor simple image upload functionality

Question: I'd like to have a simple, one-click, image upload functionality with CKEditor. I'm using D6 and CKEditor 3.6.1. I do not want a server file browsing functionality, only uploading images from the user's own computer.
I've done a thorough search on this subject and have tried different suggested approaches. It seems like the solution that best suits my needs is installing the IMCE module and the CKFinder plugin for the CKEditor module. So I did just that, and followed the installation instructions found here: http://drupal.org/node/738092
The uploaded image manages to get to the destination folder on my server, but when I open CKEditor's 'Image properties' dialog and hit the 'Send to the server' button, nothing changes on the UI.
What I wish to happen is for CKEditor to close the 'Image' dialog and insert the uploaded image into the textarea.
Here are some screenshots to better explain my situation:
- Uploading a file from my desktop

- Expected result - 'Image' dialog automatically closed and image inserted to textarea

- Actual result - 'Image' dialog stays open and nothing changes

Does anyone ever implemented an image upload functionality this way? Is there a better way to get what I want?
Comment: If you solved your problem, please post it as an answer, instead of editing into the question, and mark as accepted once the allotted amount of time has passed
Answer: If you ever get to D7, this module does exactly what you're looking for:
One Click Upload module

Button for BUEditor and CKEditor which allows upload files in one click.
Features

Upload images and insert into editor image code
Upload files and insert into editor link code
Multi-upload files and images
Integration with image styles
Editable html templates
Comment: It is very useful, but the image uploaded cannot be resized.
Comment: This is the correct answer. @Sithu, if you click on the uploaded image and open image property box by clicking to the image icon on CKEditor toolbar, you can set image size and other properties.
Answer: Now CKUtils Image plugin is available right for this thing!
See also another plugins from set, for example to upload previews with link to full-sized image.
Answer: You could use the One time Upload Module in order to full fill your need if you wish to use Drupal 7 version.

Features:

Upload images and insert into editor image code
Upload files and insert into editor link code
Multi-upload files and images
Integration with image styles
Editable html templates

For more detail about the module you could read the README.txt of this module.
Answer: Simply try the the following plugin which allows you to directly upload files to the server without needing any file browser. Great and simply the best experiences you will get!
http://doksoft.com/soft/ckutils/index.html
Answer: You can use the dragndrop_uploads module. It provides versions for both Drupal 7 and Drupal 6, the latter are just hidden behind the "View all releases" link, probably because they are unsupported now.
Despite the name, it's not a generic file upload module but made for image uploading into rich text editors. From the project page:

The Drag'n'Drop Uploads module adds the ability to drag an image from your local filesystem, drop it onto a node body textarea and have the file automatically uploaded and referenced in your node. […] [It provides] Support for the WYSIWYG module.
Answer: To upload an image, simply drag-and-drop from your desktop or from anywhere. You can also copy the image and paste it on the text area using ctrl+v.
Comment: Welcome to Drupal Answers :) Does this answer relate to the question in any way? Are you saying that CKeditor has a built-in feature to allow HTML5 drag/drop of files from the local file system? If so could you expand on where you've got that information from please?
Comment: Dragging the image and dropping it on the form element doesn't automatically upload the image, nor does it close the dialog box.


Conditional expected value

Question: Could someone help me out proving this proposition?
Let X and Y be two random variables defined in the same probability space taking values in $\mathbb{N}$ . Let $g:\mathbb{N} \rightarrow \mathbb{N}$ be any function and suppose that $h:\mathbb{N} \rightarrow \mathbb{N}$ is a bijective function. Then
$$\mathbb{E} \left[ g(X) | h(Y)\right] = \mathbb{E} \left[ g(X) | Y\right] $$
Thank you so much!
Answer: I preassume that $\mathbb N$ is equipped with $\sigma$-algebra $\wp(\mathbb N)$ so that every function $f:\mathbb N\to\mathbb N$ is measurable.
Random variable $h(Y)$ is measurable with respect to the $\sigma$-algebra generated by $Y$.
If $\ell$ denotes the inverse of $h$ (which exists because $h$ is bijective) then $Y=\ell(h(Y))$ showing that conversely random variable $Y$ is measurable with respect to the $\sigma$-algebra generated by $h(Y)$.
These two facts show that $Y$ and $h(Y)$ generate the same $\sigma$-algebra $\mathcal A$ so that: $$\mathbb E[Z\mid Y]=\mathbb E[Z\mid\mathcal A]=\mathbb E[Z\mid h(Y)]$$ for any integrable random variable $Z$.
Comment: @Did Thanks for the edit. I overlooked that $g$ was in use also.
Comment: You are welcome. (Nice answer, quite to the point.)

Conditional expected value


Finite population correction for calculating margin of error

Question: Let's say that I have a population of 10000, and I have a sample of 300 that have responded to an online survey. Of 10000 invitations, 300 hundred have replied. Would I be able to use the finite population correction for margin of error?
Population: 10000
Sample: 300
Response: 3%
Comment: It sounds like you have an *intended sample size* of 10000 and a 97% non-response rate.  Your "population" is probably much, much greater than 10000.
Comment: if you have a representative sample why do you need corrections?
Comment: Perhaps my understanding of "population" is misconstrued. Essentially, I'm trying to estimate the margin of error associated with a survey I recently ran on the clients of a company. What I'd like to be able to say is something like. "X% Clients of company Y agree that Z, with a margin of error of A."
Answer: With a 3% response rate, it is highly likely that self-selection has made this a biased sample.  whuber has also pointed out that 10000 may not be the whole population.
If the population was 10000 and if you had a random sample of 300 then you could make a finite population correction.  Wikipedia suggests a multiplicative factor for the standard error of $$\sqrt{\dfrac{N-n}{N-1}}$$ which with $N=10000$ and $n=300$ is about $0.985$, not something that is going to make a lot of difference.
Comment: Yes, perhaps my terminology is incorrect and certainly self-selection is a problem in all online research. However, 10k is truely the universe for this population. So how do I calculate MoE? Or can I?
Comment: Which formula for M of E is less important than whether to report one.  There is a short discussion at http://stats.stackexchange.com/questions/7134/accommodating-entrenched-views-of-p-values that is relevant to this.  Lots and lots of people report, for self-selected samples, inferential statistics derived from methods intended only for random samples.  But as a reflective, informed person, you'll know that to do so is unsound and that margins of error will not have their nominal limits.  At the post linked above I described a sort of workaround to this, which was met with mixed reviews.
Comment: The Wikipedia article also says that the FPC is intended for use when the sample size is greater than 5% of the population. For example, if your sample is 25%, the FPC is .8703, which could make more of a difference


Reason why RHEL Apache is installed on middleware folder

Question: What's on RHEL the cause which Apache (HTTPD) is installed on the folder "/opt/middleware/httpd/", instead the usual installation folder? What should I apply on my server to have this similar feature, since I am trying to replicate a client environment.
Answer: This is not a standard httpd installation. It was installed by some third party. You may find it quite difficult to identify the third party without help from the client. You can try poking around for clues, but if you want to be sure you will need to ask the client what this is and why they have done it instead of using the normal httpd included with RHEL.


Gallery in jQuery with list

Question: I was looking for some gallery with previous/next buttons, and i found it. I have code:
var speed = 0;
$('#mask-gallery, #gallery li').width($('#slider').width());
$('#gallery').width($('#slider').width() * $('#gallery li').length);
$('#mask-gallery, #gallery li').height($('#slider').height());
$('#gallery li:first').addClass('selected');

$('#btn-next, #gallery').click(function () {
 newsscoller(0);
 return false;
});

$('#btn-prev').click(function () {
 newsscoller(1);
 return false;
});

function newsscoller(prev) {
    var current_image = $('#gallery li.selected').length ? $('#gallery li.selected') : $('#gallery li:first');
    if (prev) {
        var next_image = (current_image.prev().length) ? current_image.prev() : $('#gallery li:last');
    } else {
        var next_image = (current_image.next().length) ? current_image.next() : $('#gallery li:first');
    }

    $('#gallery li').removeClass('selected');
    next_image.addClass('selected');
    $('#mask-gallery').scrollTo(next_image, 250);
}

http://jsfiddle.net/R27FS/
And i have one question. Anybody have idea how it script can redirect user for the defined page (location.href = '';) after last slide?
Thanks for replies!
Comment: noooooo never redirect on last slide! there's no gallery with such functionality! rather add a click or create a button on the last slide and make it clickable! think about users, if you surprise them (badly) they'll never come back again. I'm one of them.
Comment: I agree, no one would want that.  Almost as bad as background music!
Comment: all the same I will be grateful for some solution :)
Answer: One option is to set the 'next' link to an actual location on the last slide. And then return true; on the click event if href!="#"
DEMO
var speed = 0;
$('#mask-gallery, #gallery li').width($('#slider').width());
$('#gallery').width($('#slider').width() * $('#gallery li').length);
$('#mask-gallery, #gallery li').height($('#slider').height());
$('#gallery li:first').addClass('selected');

$('#btn-next, #gallery').click(function () {
    var href = $(this).attr("href");
    if (href != "#" && href != "") return true;
    newsscoller(0);
    return false;
});

$('#btn-prev').click(function () {
    newsscoller(1);
    return false;
});

function newsscoller(prev) {
    var current_image = $('#gallery li.selected').length ? $('#gallery li.selected') : $('#gallery li:first');
    var next_image;
    $("#btn-next").attr("href", "#");
    if (prev) {
        next_image = (current_image.prev().length) ? current_image.prev() : $('#gallery li:last');
    } else {
        if (current_image.next().length) {
            next_image = current_image.next();
        }
        if (!next_image.next().length) {
            $("#btn-next").attr("href", "http://www.google.com");
            //'target' required for it to work in jsFiddle b/c of
            //iframe, remove in your code.
            $("#btn-next").attr("target", "_blank");
        }
    }

    $('#gallery li').removeClass('selected');
    next_image.addClass('selected');
    $('#mask-gallery').scrollTo(next_image, 250);
}

Gallery in jQuery with list


D8 - Access Webform submission values programatically

Question: I have a webform whose results (some specific fields) I want to display in a table in a view. I am able to achieve that using the Webform Views Integration module. The view displays the output as
Field Name
Field Value

I want it to be displayed as

Field Value

Although it can be done via CSS using label{display:none;}, is there any way to do it out of the box or using modules?
Also, I want to overwrite the default webform submission layout which I can achieve using the answer here. But when I try to access the elements of the webform submission using {{html.fieldName}} or {{data.fieldName}}, it again prints out the label with it. I tried the nolabel filter but it does not work.
Answer: You need to apply the patch from this issue.
Comment: This patch works perfectly when webform views are exposed to a table but when I override the template using TWIG file, it still shows with the label.
Comment: I recommend we move any discussion related to bugs into the Webform View Integration module's issue queue. https://www.drupal.org/project/webform_views


put sentences into list - python

Question: I understand that nltk can split sentences and print it out using the following code.
but how do i put the sentences into a list instead of outputing onto the screen?
import nltk.data
from nltk.tokenize import sent_tokenize
import os, sys, re, glob
cwd = './extract_en' #os.getcwd()
for infile in glob.glob(os.path.join(cwd, 'fileX.txt')):
    (PATH, FILENAME) = os.path.split(infile)
    read = open(infile)
    for line in read:
        sent_tokenize(line)

the sent_tokenize(line) prints it out. how do i put it into a list?
Comment: huh? `sent_tokenize` returns a list of sentences, at least the docs say "Given a text, returns a list of the sentences in that text".
Comment: @eyquem, you're just wrong. `for line in infile:` is _the_ Python idiom for reading lines from files. Although it only gets individual lines from the file, rather than the whole file at once. Is that what you mean?
Comment: @eyquem, ok, I'll restate myself: "To obtain the file's content, we must do f.read()" is confusing, because "must" suggests that it's the only way to do so. In any case, I agree that using "read" as your file pointer name is not a good choice.
Comment: it prints a list of sentences. but when i try paragraph=sent_tokenize(line) it doesnt work.
Comment: Are you running this in the Python interpreter?
Comment: @2ero because when defining `f = open(infile)` , **f** isn't the content of the file, it's a kind of pointer in the file, an object memorizing the position of the read/write head of the hard disk. To obtain the file's content , we must do `f.read()`
Comment: @senderle No, I am right, and you're right. I didn't write that `for line in read` isn't pythonic, I say that the name **read** to designate the file's pointer is baaaad: **read** is then no more the function **read()**, it's the pointer
Comment: alright. the nltk documentation is not very clear. @senderle, nltk.tokenize's sent_tokenize(line) does return a list but it also prints out the  list. problem solved. but how to i access the list? para = sent_tokenize(line) then para[0] ?
Comment: @senderle Oh , I see, subtile remark, senderle, my expression is ambiguous, you're right. I will pay attention to that from now. I will express: `for line in f` is a way to obtain the content of a file, `f.read()` is another, `f.readlines()` is a third one, `line = 'go' while line: line = f.readline()` is one more... and the first is a very pythonic one. I agree. I upvote
Answer: Here's a simplified version that I used to test the code:
import nltk.data
from nltk.tokenize import sent_tokenize
import sys
infile = open(sys.argv[1])
slist = []
for line in infile:
    slist.append(sent_tokenize(line))
print slist
infile.close()

When called like so, it prints the following:
me@mine:~/src/ $ python nltkplay.py nltkplay.py
[['import nltk.data\n'], ['from nltk.tokenize import sent_tokenize\n'], ['import sys\n'], ['infile = open(sys.argv[1])\n'], ['slist = []\n'], ['for line in infile:\n'], ['    slist.append(sent_tokenize(line))\n'], ['print slist\n'], ['\n']]

When doing something like this, a list comprehension is more concise and IMO more pleasant to read:
slist = [sent_tokenize(line) for line in infile]

To clarify, the above returns a list of lists of sentences, one list of sentences for each line. If you want a flat list of sentences, do this instead, as eyquem suggests:
slist = sent_tokenize(infile.read())

Comment: i understand now. it's sort of like declaring a list from a function that returns a list but the functions prints out the list if it isn't input into a variable. sorry still pretty C-minded and the interpreter style is pretty different from perl. yep. the list comprehension is more pleasant but more perl/python like than C. it looks like perl though, so i like it. hahaha. Thanks a lot!
Comment: Just FYI, the behavior you're describing only happens in the python interpreter, AFAIK. So if you type `>>> sum([1, 2, 3])` in the interpreter, it prints 6, but if you put the line `sum([1, 2, 3])` in `sum.py` and call `python sum.py` from the command line, nothing happens at all.
Comment: is **sent_tokenize()** able or unable to find sentences in a text containing **\r\n** ? If it can't, `for line in infile:` is necessary. If it can do it, `sent_tokenize(f.read())` should work. But I don't know nltk
Comment: @eyquem, yes, good point, I was thinking the same thing. I checked, and yes, `sent_tokenize` tokenizes across newlines, so `sent_tokenize(f.read())` works.
Comment: @senderle That's why you got the points, that's because you had nltk installed and you could do the test. Eh eh :)
Comment: @senderle, ohh.. now i get how interpreter works. i had been dealing with compilers. @eyquem, noted on my bad python syntax, hahaa..
Answer: You must not use a keyword name (read) to name an object of your programm.
.
If you want to append in a list, you must have a list:
reclist = []
for line in f:
    reclist.append(line)

or with a list comprehension
reclist = [ line for line in f ]

or using the tools of Python
reclist = f.readlines()

or I didn't understand what you want
EDIT:
Well, considering the Jochen Ritzel 's remark, you want
f = open(infile)
reclist = sent_tokenise(f.read())

Comment: Actually `read` isn't a keyword in python... not that I advise using it this way.
Comment: i understand that f.readline() reads a line. the nltk function sent_tokenize(afewsentences) prints out the sentences but i need them onto a list. is there another nltk function that does that? if not, how do i put the output into a new string and then manipulate it?
Comment: @senderle Right ! **read** is the name of a built-in function, that's all, you are right.
Comment: @2ero **readline()** with NO **s** reads a line , and **readlines()** WITH an **s** reads the entire file , cut it in lines , and put them in a list.
Comment: @eyquem, sorry i am in asia now so i dozed off while coding. @harvey thanks for helping with the delete

put sentences into list - python


Google Maps Module custom markers and routeplanner

Question: On my Drupal site, I have a nice Google maps module with custom markers.
The only thing I want to add is a route planner that makes use of my custom
Markers.
Any suggestions?
Comment: This question appears to be off-topic because it is a feature request for module, and should be posted in it's issue queue. If you plan to write this feature yourself, please read [this question on meta](http://meta.drupal.stackexchange.com/q/2561/16495), and it's answers.
Answer: Have you already tried https://drupal.org/project/routeplanner ? It's a very simple and lightweight Module to create a route from any address to a fixed point of interest.
Comment: Dear Twinkel, Thank you for your reply. Yes i've tried the routeplanner module indeed. Unfortunaly i haven't been able to get it to work.. But not all is lost. I will try again on a "dummie website" where i can fool around without anny permanent changes. Thanks again for your reply. Greets Michel


Regular sequence in Cohen-Macaulay ring is regular on Maximal CM-module

Question: I saw an exercise which says the following:

For a Cohen-Macaulay ring $R$ and a maximal Cohen-Macaulay module $M$, an $R$-regular sequence is also $M$-regular. Why is this true?

The only thing I know about MCM is that $\operatorname{dim}(R) = \operatorname{dim}(M)$, so $\operatorname{depth}(R) = \operatorname{depth}(M)$. How should I proceed?
Answer: One way of looking at this problem is that the set of zero divisors for $M$ is the union of its associated primes.  When $R$ is Cohen-Macaulay and $M$ is maximal Cohen-Macaulay, we know the associated primes of both $R$ and $M$ are minimal primes of $R$.  But $R$ is fully supported, so if $x$ is a non-zerodivisor on $R$, thus avoiding every minimal prime of $R$, it must also avoid every minimal prime of $M$.  Induction then extends this from a single element to showing an $R$-regular sequence must be $M$-regular.


Como pegar valores de array javascript/jquery ajax

Question: Estou fazendo uma requisição ajax e retornando os dados pelo php com json_encode
lado do servidor:
 $id=1;
 if(isset($_POST['id'])){
   $id = $_POST['id'];
 }else{
   http_response_code(400);
 }
 $produto = listaAssociada($id);
 echo json_encode(listaAssociada($id));

função listaAssociada
  $query = "SELECT p.nome,p.descricao as produtodescricao,p.img as produtoimg,e.titulo,e.descricao as explicacaodescricao,e.infoadicional,e.img as explicacaoimg FROM Produto as p inner join Explicacao as e on p.idExplicacao=e.idExplicacao where p.idProduto= $id";
$consulta = mysqli_query($mysqli, $query);

    if(mysqli_num_rows($consulta) != 0) {
        while($item = mysqli_fetch_array($consulta)) {
            $resultados['nome'] = $item['nome'];
            $resultados['produtodescricao'] = $item['produtodescricao'];
            $resultados['explicacaodescricao'] = $item['explicacaodescricao'];
            $resultados['titulo'] = $item['titulo'];

        }

        return $resultados;
    }else{
        return 0;
    }

parte do script


From the result of Hilbert's tenth problem, does it follow that there exist infinitely numbers of equation...

Question: From the results of the Hilbert's tenth problem, does it follows that there exist infinitely numbers of Diophantine equations where it is impossible to determine whether or not there are integer solutions?
Conversly, is it true that there exist infinite number of Diophantine equations where it can be determine rather or not there are integer solutions?
If both are true, why do people still have the reason to study it?
Hilberts 10th Problem (wiki) is:

Given a Diophantine equation with any number of unknown quantities and with rational integral numerical coefficients: To devise a process according to which it can be determined in a finite number of operations whether the equation is solvable in rational integers.
Answer: There are algorithms for determining the solvability in integers of certain classes of Diophantine equations. For example, we can deal quite easily with linear equations in arbitrarily many variables, and there are infinitely many of those. There is also an algorithm for quadratic Diophantine equations in arbitrarily many variables, though this is less obvious.  The answer for cubics is not known. There is no general algorithm for determining the solvability of quartic equations in arbitrarily many variables.
There is a polynomial $P(w,x_1,x_2,x_n)$ with integer coefficients such that  there is no algorithm that will determine, given input $w$, whether there are integers $x_1,x_2,\dots,x_n$ such that $P(w,x_1,x_2,\dots,x_n)=0$.  As a consequence of this, there are infinitely many $w$ such that the equation has no solution, but the fact that it has no solution is not provable in first-order Peano arithmetic. A similar remark could be made about ZFC.  I do not think that this result can be equated with "impossible to determine," but it goes some distance toward that.
The above results are very beautiful.  But they do not necessarily have a direct connection with classical questions in Diophantine equations, such as questions abut elliptic curves. The work on Hilbert's $10$th problem in fact produced interesting number-theoretic results, and generated new number-theoretic problems. It has enriched Number Theory, and in no way diminished it.


Surjectivity of $\mathscr G\to f_*f^{-1}\mathscr G$

Question: Let $f:X\to Y$ be a continuous map, and let $\mathscr G$ be a sheaf on $Y$. There is a canonical morphism $\varphi:\mathscr G\to f_*f^{-1}\mathscr G$, hence a map $\varphi_y:\mathscr G_y\to f_*f^{-1}\mathscr G_y$, for any $y\in Y$. If $x\in X$, is it true that $\varphi_{f(x)}$ is an isomorphism?
I explain why I think it's true. By definition $\mathscr G_{f(x)}=\operatorname{colim}_{U\ni f(x)}\mathscr G(U)$; $f_*f^{-1}\mathscr G_{f(x)}$
instead is $$\operatorname{colim}_{U\ni f(x)}\operatorname{colim}_{V\supset ff^{-1}(U)}\mathscr G(V) .$$ Given an open $f(x)\in U\subset Y$, any open $ff^{-1}(U)\subset V\subset Y$ contains $f(x)$; moreover $ff^{-1}(U)\subset U$, so the double colimit is (isomorphic to) the colimit over the system of open sets containing $f(x)$, i.e. $\mathscr G_{f(x)}$. Since the map $\varphi_{f(x)}$ is compatible with the legs of the colimits, it is a (unique) isomorphism.
My doubt arises from an exercise (2.13) in Liu's algebraic geometry book; he asks to prove that, in the same hypothesis as above, $\varphi$ is surjective if $f$ is a closed immersion. If the image of $f$ is closed (but $f$ is not necessarily an immersion),
$\varphi_y$, for $y\notin f(X)$, is surjective as its codomain is the terminal object; so from the argument of the paragraph above, it seems that $\varphi$ is surjective just if the image of $f$ is closed. Likely, the result of the paragraph above needs the assumption of $f$ being an immersion, but I don't understand why. Thank you
Edit. Let $f:X\to Y$ be a continuous map. I'll denote the sheafication of a presheaf $\mathscr P$ with $\mathscr P^\#$, the pullback of a sheaf $\mathscr G$ on $Y$ with $f_p\mathscr G$, and the sheafication of the pullback with $f^{-1}\mathscr G$; I'll denote by $\varphi$ the canonical morphism $\mathscr G\to f_*f^{-1}\mathscr G$. Above I proved that  $$\mathscr G_{f(x)}\to (f_*f_p\mathscr G)_{f(x)}, $$ and thus $$\mathscr G_{f(x)}\to (f_*f_p\mathscr G)_{f(x)}\to (f_*f_p\mathscr G)_{f(x)}^\#, \ (*)$$ are isomorphisms for all $x\in X$. Instead I have to consider $$\varphi_{f(x)}:\mathscr G_{f (x)}\to (f_*f^{-1}\mathscr G)_{f(x)},$$ different from $(*)$ because, as you say, pushforward doesn't commute with sheafication. If $f$ is an immersion, $(f_*\mathscr F)_{f(x)}\to \mathscr F_x$ is an isomorphism for any sheaf $\mathscr F$ on $X$ and any $x\in X$. Also, $\varphi_{f(x)}$ factors as $$\mathscr G_{f(x)}\to (f^{-1}\mathscr G)_x\to (f_*f^{-1}\mathscr G)_{f(x)},$$ which is a composition of isomorphisms. This shows that $\varphi_{f(x)}$ is an isomorphism, and if $f(X)$ is closed, $\varphi_y$ is trivially surjective for all $y\notin f(X)$, guaranteeing that $\varphi_y$ is surjective for all $y\in Y$.
Comment: Let's make things easy for ourselves and consider the special case where $X$ is discrete and $Y$ is a point. Do you still believe the claim?
Comment: @ZhenLin if $Y=\{y\}$, then $\mathscr G_y=\mathscr G(Y)$. Also $f_*f^{-1}\mathscr G(Y)$ equals $f^{-1}\mathscr G(X)$ equals $\mathscr G(Y)$. Also $\varphi_Y$ seems to be the identity. I really tried to find the mistake but I couldn't
Answer: I'll expand on Zhen Lin's comment since it's a nice simple example and you seem to be making the same mistake when looking at that example as you are in the main part of the question.
I think the core problem here is that you're forgetting that you need to sheafify the colimit when defining the inverse image functor.
I.e. $f^{-1}\mathscr{G}$ is a sheaf on $X$ defined as the sheafification of the presheaf
$$\operatorname{colim}_{V\supseteq f(U)} \mathscr{G}(V).$$
It's also worth pointing out that sheafification doesn't commute with pushforward in general, so you can't compute the stalk of the pushforward of the inverse image with a colimit in the way that you want. After all, if you could commute the pushforward with the sheafification, then when taking the stalks you could drop the sheafification, and you'd be left with the colimit in your question, so this wouldn't be an issue. But they don't commute, so the argument in your question doesn't apply.
Now let's look at Zhen Lin's suggestion from the comments, where we take $X$ discrete and $Y$ a point.
A sheaf on $Y$ is defined by just the set $\mathscr{G}(Y)$. Similarly since $X=\{x_1,\ldots,x_n\}$ is discrete (and I'm going to just let it be finite for convenience's sake), a sheaf on $X$ is defined by the sets $\mathscr{H}(\{x_i\})$ for $1\le i \le n$. In particular, the sheafification of a presheaf $\mathscr{H}$ is easy to compute. It's just
$$\mathscr{H}^\#(\{x_{i_1},\ldots,x_{i_k}\})=\prod_{j=1}^k \mathscr{H}(\{x_{i_j}\})$$
So to compute $f^{-1}\mathscr{G}$, we just need to compute
$$f^{-1}\mathscr{G}(\{x_i\}) = \operatorname{colim}_{V: x_i\in f^{-1}(V)}\mathscr{G}(V)$$
Since $Y$ is a point, the only nonempty open set is $Y$ itself, so we have
$$f^{-1}\mathscr{G}(\{x_i\}) = \mathscr{G}(Y).$$
(Note that we can also see this from the fact that these sets are also the stalks at the points, since it's always true that the stalks of the inverse image at any point $x$ are isomorphic to the stalks of the original sheaf at $f(x)$.)
Then $f_*f^{-1}\mathscr{G}$ is determined by its value on $Y$, which is
$f^{-1}\mathscr{G}(X)$, which is $\mathscr{G}(Y)^n.$ Note that this is also the stalk at the unique point in $Y$, so the natural map cannot be an isomorphism on stalks.
Comment: I think that I understood your correction, thank you. I also made an edit to the post after your answer, with the solution of the exercise, if you want to check it.


d3 xhr adding loading cursor

Question: I am trying to make a xmlhttprequest from
d3.xhr("Data-mapper?Function-name=tree-data", "application/json", function (i,d){
    console.log(d);
    return d;
});

I am able to get the response data as well but i want to know if i can add a loading cursor when the call is made.. Or progress bar ...
One more thing i wanted to ask is how can we send data when we make a call to get data from server side i.e

d3.json(...) or d3.xhr(...)
Comment: acutally wanted to ask one more question  when i making call `d3.xhr("DataMapper?function-name=PieChart","application/json",
     function(i,d){
      jsondata=JSON.parse(d.response);
      console.log("inside "+jsondata);
      return d.response;
      }); console.log("jsondata "+jsondata);` I have now kept this inside the html script .The issue is  i am able to get data inside the function but when i try outside the function i dont get the data .But if the same code i paste it in console of chrome i am able to see both the data . why is this so??
Answer: You can add a "loading" screen by adding it in the beginning and removing in the callback:
addLoadingScreen();
d3.json(..., function(error, data) {
  // do something
  removeLoadingScreen();
});

I have used this technique here.
To answer your second question, you can pass parameters as GET parameters:
d3.json("http://www.foo.com/script?parameterA=foo&parameterB=bar", function(error, data) {
});

Answer: HTML

loading...

JS
d3.json("http://filltext.com/?rows=5&fname={firstName}&lname={lastName}&delay=10", function (err, data){
    var pre = document.getElementById('pre');
    pre.innerHTML = JSON.stringify(d, null, 4);
    console.log(data);
});

JSFIDDLE Demo

d3 xhr adding loading cursor


JavaScript not executing as response in Rails

Question: I have a form that creates messages in my view, and I want the list of messages on the same page to update on create. So I am using Ajax. The return from the create action seems to be html, and not just the js script, and the script is not executing. (I tried putting in an alert function to test).
Instead the script is appended to the end of the response. What am I doing wrong?
My controller action:
def create
    @order = Order.find(params[:order_id])
    @customer = @order.customer
    @message = current_user.messages.create(
      body: message_params[:body],
      order_id: @order.id
      )
    respond_to do |format|
      if @message.save
        format.html { redirect_to @message, notice: 'Message was successfully created.' }
        format.js
      end
    end

create.js.haml:
%script(type="text/javascript")
  $("#messages").append("
Hello
");

My form
= simple_form_for :message, remote: true, url: order_messages_path(@order), method: :post do |f|
  = f.error_notification
  = f.hidden_field :customer_id, value: @order.customer.id
  .form-inputs
    = f.text_field :body
  .form-actions
    = f.button :submit

And the response comes back with the full html:
  (...)

      (...)

Server response:
Started POST "/orders/1/messages" for 127.0.0.1 at 2015-07-15 21:48:31 +0200
Processing by MessagesController#create as JS
  Parameters: {"utf8"=>"✓", "message"=>{"customer_id"=>"1", "body"=>"There is a light."}, "commit"=>"Save Message", "order_id"=>"1"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Order Load (0.3ms)  SELECT  "orders".* FROM "orders" WHERE "orders"."id" = $1 LIMIT 1  [["id", 1]]
  Customer Load (0.3ms)  SELECT  "customers".* FROM "customers" WHERE "customers"."id" = $1 LIMIT 1  [["id", 1]]
   (0.2ms)  BEGIN
  SQL (0.8ms)  INSERT INTO "messages" ("body", "order_id", "creator_type", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["body", "There is a light."], ["order_id", 1], ["creator_type", "user"], ["user_id", 1], ["created_at", "2015-07-15 19:48:31.996217"], ["updated_at", "2015-07-15 19:48:31.996217"]]
   (1.2ms)  COMMIT
  Rendered messages/create.js.haml within layouts/application (3.6ms)
  Rendered layouts/_navigation.haml (1.4ms)
Completed 200 OK in 463ms (Views: 453.0ms | ActiveRecord: 3.2ms)

Comment: Ah, I figured it out. I need to include
Comment: format.js {render :layout=>false}
Answer: First of all, I think the %script(type="text/javascript") is not necessary. Try removing it and putting
format.js { render "create.js.haml" }

The #messages element exists, right?
Comment: Yeah, still the same thing. #messages exists alright.

The response is not being executed as JavaScript.
Comment: Can you put the server console output for that request?
Comment: It renders the create.js.haml file alright, but seems to return more than that as a response.
Comment: Could you put an alert into the create.js.haml file and see what happens?
Comment: It was the the layout being rendered by Rails. http://stackoverflow.com/questions/3412375/jquery-ajax-haml-js-erb-files-not-firing/3413707#comment50849234_3413707
Comment: Wow, that's sound weird... but great!


Python Gerar layout txt a partir de um arquivo txt

Question: Tenho um arquivo txt que estou fazendo tratamento para gerar um layout em outro arquivo txt. Quando uso o comando print o mesmo gera corretamente, porém quando coloco para escrever em outro arquivo ele gera somente a primeira linha.
num = input ("Digite local: ")
num2 = input ("Digite sub local: ")
f = open("update_teste.txt","w+")
with open ('contagem.txt') as fo:
    for s in fo:
        print  ("0",num, num2, s[0:12], s[14:19], sep="")
new = ("0"+ num+ num2+ s[0:12]+ s[14:19])
with open ("update_teste.txt", "w+") as arquivo:
    arquivo.writelines (str(new))
    print (new)

Arquivo contagem.txt:
1234567890128;00001
5687544567456;00001
7898433340878;00002
8888021201451;00002

update_teste.txt:
00100588880212014500002

Answer: O problema é que você está lendo todo o arquivo e depois só guarda a última linha em new (pois ela está fora do for que lê o arquivo, e depois do for a variável s terá a última linha que foi iterada, todas as anteriores já foram "perdidas", pois você só as imprimiu mas não guardou-as em nenhum lugar).
Enfim, se quer ler de um arquivo enquanto escreve no outro, faça tudo no mesmo loop:
num = input ("Digite local: ")
num2 = input ("Digite sub local: ")
with open('contagem.txt') as fin, open("update_teste.txt", "w") as out:
    for s in fin:
        out.write("0" + num + num2 + s[0:12] + s[14:19] + "\n")

Ou seja, para cada linha que leio de um, já escrevo a respectiva linha no outro. Detalhe para o \n, que adiciona a quebra de linha no final.

Se estiver usando Python >= 3.6, pode usar f-string em vez de concatenação:
with open('contagem.txt') as fin, open("update_teste.txt", "w") as out:
    for s in fin:
        out.write(f"0{num}{num2}{s[0:12]}{s[14:19]}\n")

Também mudei o modo de abertura do arquivo "update_teste.txt" de w+ para apenas w, pois w+ abre o arquivo para leitura e escrita, mas como você só está escrevendo nele, não é necessário usar o +. Veja a documentação para mais detalhes.
E retirei a terceira linha (f = open("update_teste.txt","w+")), pois não fazia sentido abrir o arquivo ali, para não usá-lo para nada e depois abri-lo novamente no segundo bloco with.
Comment: Bom dia, muito obrigado ! Atendeu minha necessidade perfeitamente.
Answer: Acredito que se você apenas concatenar um "\n" no final da sua variável new o problema já estará resolvido!
Mais duas coisas: Aquela variável f que está abrindo o update_teste.txt pode estar atrapalhando o funcionamento, pois o arquivo não está sendo fechado.
Acredito que quando for passar a variável new pro writelines não é necessário o str(), pois a variável ja é construída por uma concatenação de strings.
Espero ter ajudado!


Division of a cubic equation by one of its factors

Question: I'm trying to divide a cubic equation by a factor.
This is the equation:
$$ -\lambda^3 -\lambda^2 + 10 \lambda - 8 = 0$$
and this is the factor : $(\lambda - 1)$
I Googled about it and I found the Euclidean division, but I couldn't find some understandable way to do it.
Answer: Try googling "polynomial long division": You can go directly to this entry in Wikipedia:
Polynomial Long division
Dividing one polynomial by another proceeds just as long division proceeds. And the best way to see how it works is to see some examples (as the linked entry contains), and just try it, do it, practice it.  It won't help you much to provide you with the result: you'll want to see "how" so you can use it here and in any other situation you'll be certain to run across.
Comment: Does this help, Aimad?
Answer: $$\lambda^3+\lambda^2-10\lambda+8=(\lambda -1)(\lambda^2+2\lambda-8)=(\lambda-1)(\lambda-2)(\lambda+4)$$
Comment: How does that show a "way to do it"?
Comment: As much as sending the OP to some link, which he could have googled by himself...:) Anyway, I try to make him think: (1) the division is exact since $\,1\,$ is a root of the cubic, (2) putting $\,\lambda -1\,$ and "completing powers" (for example, that $\,2\lambda\,$ must be there in the middle so that we'll get get $\,\lambda^2\,$ in the final outcome), etc. I'm assuming, of course, that the OP has already studied some long division...
Comment: The OP clearly stated that s/he tried Googling...but couldn't find anything. Read the question: "I Googled about it and I found the Euclidean division, but I couldn't find some understandable way to do it."
Comment: I have deleted several off-topic comments. Please try to stay constructive.
Comment: Thank you very much, @ZevChonoles .
Comment: Ditto...Thank you very much, @Zev


Como cortar uma string?

Question: Exemplo:
nome = "Josénildo da Silva Ramos do Carmo";

Cortar para ter até X caracteres, ficando assim:
nome = "Josénildo da Silva ";

No caso cortei para 20 caracteres.
Como faço isso em C#? Só sei em C (que é vetor). Em C# não consegui achar como.
Answer: É bem simples:
nome = nome.Substring(0, 20);

Neste caso está pegando 20 caracteres à partir do caractere na posição 0.
Documentação do método. À partir daí você pode ver na documentação todos os métodos que o tipo String permite. É bom dar uma decorada em tudo para saber o que já existe pronto.
Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Comment: Obrigado á ambos, não poderia imaginar que era tão simples assim rsrs (acostuma com C que é um terror kk). Você respondeu um pouco mais rápido que o @Caique C. (segundo o site aqui) então está como resposta certa.
Comment: É, C não tem o tipo `string` então tem que fazer tudo na mão, em C# boa parte das operações estão prontas no tipo.
Answer: Utilize o método Substring.
var nome = "Josénildo da Silva Ramos do Carmo";
var novoNome = nome.Substring(0, 20);

O primeiro parâmetro indica o index inicial e o segundo é a contagem de caracteres que deve ser cortada, ou seja, o método acima vai pegar da posição 0 até 20 da string.

Como cortar uma string?


Reverse Proxy multi-subnets

Question: I'm having some problems that I think I should not be ordinarily facing.  But after being beating senseless by this, I'm calling out uncle.
I have previously posted something along these lines here: (Clickety)
Now, I'm looking for any answer to my problem
We have a network as follows:
<code>               __________ DMZ (10.0.0.0/24)
              |
WAN -----  PFsense ---------- LAN (192.168.1.0/22)
              |
              |_________ Wireless (172.169.50/24)
</code>
WAN has one IP and since we're a Red Cross society, we have no money because in fact we are a charity case we cannot afford to get more IPs (they cost a pretty penny here in Jordan)
So access to all services on the inside of the firewall is a must.
Here's the funny part. I'm a developer that had to assume the mantle of admin.
I've tried the previous acls in the link above and even with more acls, all I can ever get is a route to the webserver on the DMZ; even though I'm trying to access the DVR which is on the LAN subnet and the DNS resolves it correctly.
Of course, it gets more complicated as there are other services that need the involvement of ssl (specifically, exchange\owa).
So, I've come to you my friends, shuffling on my knees, face battered and soul withering, reaching out with my hands, asking for an answer that I hope will not destroy the network(s) or my soul.
Basically, I'm trying to get reverse proxy to work on my network, preferably with minimal change, so that we can use our services from web-side the firewall.  If it can be done with squid (the one on PFsense) then fantastic.
Many thanks for any and all answers.
Comment: What's the question ?
Comment: Whoops!

Basically, how to get reverse proxy to work, preferably with the network as is intact.  Editing the question too.  Sorry about that.
Answer:
Put anything that needs public access on the "DMZ" segment. That is standard security.
In PFsense, use the "Firewall: NAT: Port Forward" to assign public WAN-IP:port to the resource on the DMZ

There are 65534 ports to choose from although some are more standard that others e.g. port 80 for HTTP.
Comment: I've already done that with some of the services, with port 80 being forwarded to the webserver itself, but I keep on getting bombarded with questions because people keep on forgetting the port numbers. That's why I wanted to implement a reverse proxy, this way they'd simply use subdomains and that gets routed accordingly.

Just to be clear:

Instead of http://www.myweb.com:8000, we would use: http://surveillance.myweb.com
Answer: I can't answer regarding Squid, but this is easily done using Apache and mod_proxy. I'm not familiar with pfsense so I don't know if you can integrate Apache with it, but if you can:
Just set up a site using virtual hosts for each internal site you're hosting. Then within the pfsense firewall redirect requests for your WAN IP on port 80 to whatever IP you've set to listen for the virtual host.
For example, here's a santized config we're using (quotes instead of tag brackets).
<code>
NameVirtualHost 192.168.3.17:80
NameVirtualHost 192.168.3.17:443
Listen 80
Listen 443

#####Exchange Configuration#####
"VirtualHost 192.168.3.17:80"
        ServerName mail.domain.com:80
        ProxyPass https://mail.domain.com/
        ProxyPassReverse https://mail.domain.com/
        SSLRequireSSL
"/VirtualHost"

##### Wiki Configuration #####
"VirtualHost 192.168.3.17:80"
        ServerName wiki.domain.com:80
        ProxyPass / http://wiki.domain.com/
        ProxyPassReverse / http://wiki.domain.com/
"/VirtualHost"
</code>
Then just add in appropriate entries for the host records so that name resolution works for your reverse proxy entries.
Comment: for my point of View its not a problem, just setup dns correctly, add a nginx instance and reverse proxy each host viola

Reverse Proxy multi-subnets


A weird exercise for proving a tensor

Question: I have the following exercise:
Give a variant arbitrary values in some coordinate system and let
it transform by the proper tensor rules. Show that this construction produces a
tensor. More specifically, single out a particular coordinate system $Z^{i'}$ and choose an arbitrary collection of values $T^{i'j'}_{k'}$. Then, in coordinates $Z^i$ , define $T^{ij}_k$ by
$T^{ij}_k=T^{i'j'}_{k'}J^i_{i'}J^j_{j'}J^{k'}_{k'}$
Show that $T^{ij}_k$ is a tensor. Here the $J$:s represent entries in the jabocian matrix. If $T$ is a tensor the definition here is
$T^{ij}_k=T^{i'j'}_{k'}J^i_{i'}J^j_{j'}J^{k}_{k'}$
I have several questions.
What does it mean to "single out" a coordinate system?
The exercise also wants me to choose a collection of values for the symbol $T^{ij}_k$. That would mean I'd have to make up 27 different values for it, right? I fail to see why this would get me anywhere.
The only step I see here is to replace $J^{k'}_{k'}=1$ so I get $T^{ij}_k=T^{i'j'}_{k'}J^i_{i'}J^j_{j'}$, which doesn't seem to help either.
What do I need to do here, exactly?
Comment: Is this the pavel grinfield book ? :-)
Comment: Indeed it is lol.
Comment: If I recall, he defined a tensor as a variant that transforms through some set of rules. I think the idea here is that he defined the tensor in the context of some coordinate system (primed), then he used this definition to write out the definition in an arbitrary one (unprimed). So, to prove that our $T_{k}^{ij}$ is a tensor, find a new coordinate system and show that it transforms by the jacobians again.
Comment: ^ take the above with a grain of salt as I am not fully confident in the subject yet
Comment: Yes the definition of the above tensor T according to the book would be $T^{ij}_{k}=T^{i'j'}_{k'}J^i_{i'}J^j_{j'}J^k_{k'}$. However, I don't really know how to really get there and I also have the other things I asked about that bother me about that assignment
Answer: I think you need to chose a third coordinate system (say $Z^{i''}$) and then show that changing coordinates from $Z^{i}$ to $Z^{i''}$ gives the same result as the components of $T$ in the system $Z^{i''}$. Does that make sense?
Edit:
You noted that $Z^i=Z(Z'(Z''))$, so the chain rule tells you that
$$\delta^i_j = J^i_{i'}J^{i'}_{i''}J^{i''}_j$$
Hence
$$J^i_{i''} = J^i_{i'}J^{i'}_{i''}.$$
Can you go on?
Remember that I asked you to show that
$$T^{ij}_k J^{i''}_iJ^{j''}_jJ^k_{k''} = T^{i''j''}_{k''}.$$
Comment: So you want me to express  $T^{ij}_k$ in double primed coordinates right? But how do I express $Z^i$ in terms of $Z^i''$ other than $Z^i=Z(Z'(Z''))$?
Comment: @Joel You got the idea. That is all you have. I added an edit. Is it clearer now?

A weird exercise for proving a tensor


How can I get rid of the bold setting the text?

Question: I have h1 h2 and a for the text formatting.
In fact....h2 and a are identical,but I'd like to change a to non-bold text.
How can I do that?
here is my what I have put together so far:http://jsbin.com/tifuhute/44/
Comment: `font-weight: normal;`
Comment: There are no `` elements in the jsbin you provided...What exactly are you trying to change?
Comment: Sorry....just changed it, but it is acting weird. The padding doesnt seem to be where it should be....although it has it at 15 px.
Comment: So you no longer need to change the weight of the text but now the padding? If that's the case, I would recommend posting a new question asking for help with that issue.
Comment: yeah, it seems so. font-weight normal sorted it out. Thanks.
Comment: Also, why are you using an anchor tag for something that isn't a link? You should use `` or `` instead.
Answer: Set font-weight: normal;
to your css class:
#text h2 {
    color: #151515;
    font-family: Arial, Helvetica, sans-serif;
    text-align: left;
    font-size: 14px;
    padding-left: 15px;
    padding-right: 15px;
    font-weight: normal;
}

Comment: you can also just do `h1, h2, h3, h4 ,h5, h6 { font-weight:normal }` to effect every header in your document. By default your browser should render header tags as bold, so you have to override it.


How to allow a role to add user without adding user name, password, roles, etc

Question: I created a role. I would like the users of the role be able to add some people without entering user name, password, roles, active, etc. These people that the role will add are actually customers. When we get new customers, specific role users will login to the system and add the customers to the system and these people/customers do not need to access the system.
I did search google and i found this site link but I could not follow it.
Do you know how I can do it?

I thought about it. Here is the problem. After I add the customers, I need to be able to link each customer to another module content(e.e. xxx.com/module/add). The module that I am using it has a field which allows to select a user only exists in the system. If I create a content type 'customer' like you said, module field does not see these customers when i go to xxx.com/module/add. Module field only sees these customers if they are users of the system. Not sure how to proceed?

Other module name is simple reservation which has a field 'This reservation is for'. This field is only takes users names from the system.
sr_week.tpl.php has the below code to get the users ( i guess)

          <?php if (($reservation["for_uid"] > 0) && ($reservation["uid"] != $reservation["for_uid"])) {
              print(" (". t("for") ." ". l($for->name, 'user/'. $for->uid)) . ")";}
              else print(" ");?>

Comment: What is this other module that you are using? There might be a suitable replacement that would allow you to use nodes.
Comment: I added comment above.
Answer: It sounds like these people you're adding should not be added as users to the system.  You should only add users if they are going to be actually logging into Drupal.
If you're just trying to keep a record of clients then you should store them as nodes.  Configure a new content type called something like "customer" and add and configure the appropriate fields that you wish to store about these customers.
Comment: I have added comment above.


Proof for $-\sup(A) = \inf(-A)$

Question: Let $A$ and $-A = \{ -x \mid x \in A \}$ be two bounded sets.
I have to prove that $-\sup(A) = \inf(-A)$, i did it in the following way and wish to know if it is sufficient:
$ \exists x\in A$ such that $\sup(A) - \epsilon < x, \forall \epsilon > 0$,  multiplying by -1 we get:  $-\sup(A) + \epsilon > -x, \forall \epsilon > 0$, and this is the inequality for $\inf(-A)$ and since $\inf(-A)$ is unique, it follows that $-\sup(A) = \inf(-A)$
Is this wrong?
Comment: this proof is alright.
Comment: Related and **not** a duplicate is this [answer](http://math.stackexchange.com/a/478617/55235).
Answer: The "proof" is not written in standard prose, capitalization, or punctuation. That is the first thing you should fix.
There is at least one error at the beginning. The sentence "there is an $x \in A$ such that $\sup(A) - \epsilon < x$ for all $\epsilon > 0$" means "there is an $x \in A$ such that for all $\epsilon > 0$, $\sup(A) - \epsilon < x$". This is not what you meant to say, and it is false for any set $A$ that has only one point.
In general, when a "for all ..." appears at the end of a sentence with other quantifiers, that final "for all ..." becomes the innermost quantifer.
In this case you want it to be the outermost quantifier, you want to say
"for all $\epsilon > 0$, there is an $x \in A$ such that $\sup(A) - \epsilon < x$". In general, you can avoid this error by not writing "for all ..." at the end of a sentence until you have more practice with quantifiers. If you write the quantifiers at the beginning, it is easier to see how they are nested.
Comment: `In general, when a "for all ..." appears at the end of a sentence with other quantifiers, that final "for all ..." becomes the innermost quantifer.` Golden rule which I had to figure out by myself after two years of studying.

Proof for $-\sup(A) = \inf(-A)$


Changing the laucher activity in Android app updated version

Question: I am adding a splash screen as lauch activity in a app which already in the market. When I install the new build in the device (LG Optimus p350)which is already has the previous application, I can not install the new build. Can any one please help me with this?
Comment: you can uninstall the previous build and then try to install the new build
Comment: When i uninstalled the prev application its working. But what is the issue the above scenario?
Answer: Make sure both applications'

package have same name.
APK was signed with same keystore.
Comment: both has same keystore and package name
Comment: so how are you pushing the apk to device, using eclipse or using terminal?
Comment: Currently I have put new signed apk in the sdcard and installed from there for testing purpose. In the app I have a version upgrade api, in which new apk is downloaded from the server and installed from the code.
Comment: Is there is any way to uninstall the app and reinstall the updated app from the code??


Qual é a melhor performance em comparação de tamanho de strings?

Question: Qual a melhor opção a nível de performance?
E alocação de memória?
Utilizar a opção 1 ou 2?
String text = "ola mundo";

Opção 1:
If (  Strings.len(text) > 0 ) {}

Opção 2:
If ( text != "") {}

Comment: Opção 2 :  If ( text != "") {}
Answer: Primeiro, não deveria usar Strings.len(), isso é algo usado na biblioteca de compatibilização com Visual Basic e, embora possível, não deveria ser usado em código novo, especialmente em C#. Não que ele seja problemático, apenas que mantém o uso de algo que não é o padrão. Use:
var text = "ola mundo";
WriteLine(text.Length > 0);
WriteLine(text != "");

Coloquei no GitHub para referência futura.
A diferença deve ser pequena. Ambos acessam um dado muito básico. Algumas pessoas podem pensar que haverá uma contagem de quantos caracteres o texto tem, mas esta informação está disponível e não precisa ser calculada.
A segunda opção pode ser otimizada. Pode ser que a simples comparação das referências já indique que é igual e não precisa fazer mais nada (não acho que seja o caso neste exemplo, mas entendo que este exemplo não é bem o que deseja saber, ele foi usado só para simplificar).
Pode ser que a comparação do código hash da string já indique ser diferente, claro que se ele tiver que calcular o hash pode custar caro, por isso tenho dúvidas se ele faria.
Mesmo o caso pior quando ele compara o primeiro caractere já identificará se é igual ou não. Como de um lado só tem um caractere, o terminador, não precisa verificar mais nada. Estou falando hipoteticamente, não é assim que funciona na prática.
De fato podemos olhar o código fonte da função que descobre a igualdade entre duas strings e ver que é ela faz o mesmo que a opção 1 (feito da forma adequada):
public static bool Equals(String a, String b) {
    if ((Object)a==(Object)b) return true;
    if ((Object)a==null || (Object)b==null) return false;
    if (a.Length != b.Length) return false;
    return EqualsHelper(a, b);
}

Dá para ver que há 2 ou 3 branches (comparações, a grosso modo) antes de verificar se os tamanhos são iguais, isso é um custo extra. Mesmo na verificação do tamanho tem que pegar o tamanho das duas strings e não apenas uma como na opção 1. É pior se usar uma comparação fora do padrão.
Note que estas questões são detalhes de implementação, então o que vale hoje pode não valer amanhã e depende muito da situação exata.
Embora não dê para afirmar parece claro que a opção 1 é mais rápida. Isto pode mudar ou pode ter alguma otimização que elimine o excesso de código da opção 2, mas na prática sabemos que isto não ocorrerá.
Não precisa olhar o bytecode gerado até porque ele nem sempre é um indicativo da real performance, a não ser quando é idêntico, o que neste caso não tem a menor chance de ser.
Se quer saber a diferença exata tem que medir, se só quer qual é mais rápido está aí a informação. Ela pode ser útil porque se a sua rotina for usada em um laço grande pode dar uma boa diferença de performance.
Nenhuma das duas opções alocam memória, então não faz diferença.
Comment: @RovannLinhalis aí é diferente, se você sequer sabe se s *string* não é nula, não pode usar nenhuma das opções da pergunta, O fonte deste método é só `value == null || value.Length == 0`.
Comment: @RovannLinhalis exatamente. Verificar direto só se tiver certeza que não é nulo, o que poderá ser possível garantir isso até pelo compilador no C# 8.
Comment: costumo usar o `String.IsNullOrEmpty()`, dá no mesmo ?
Comment: ok, acho válida a menção, normalmente se vai verificar se a *string* está vazia, é para trabalhar com ela depois, e um código assim geraria uma exceção: `string valor = null;
  if (valor != "")
  {
   string novoValor= valor.ToUpper();
  }` obrigado =]
Answer: Não acho que esse deve ser o tipo de coisa que alguém que está escrevendo olá mundo deveria se preocupar.
Se você realmente quer saber qual é melhor ou pior, o ideal é você olhar diretamente no assembly gerado. Lembre-se de colocar no perfil Release, caso contrário não terá as otimizações.
Outra idéia é usar ferramentas de profiling.


Xcode beginner - compiling issue

Question: I am very new to the Xcode environment. I would like to compile some .c and .cpp files. So I created a project with the generic c++ plugin (is it the right choice?). It builds the file with success, but I have no result displaying, even for the "hello world" printf file. Can anyone help? If someone could reccomend some good tutorial, that would be great!
Here is my example code:
#include <stdio.h>

int main (){
    printf("Hello World");
    return 0;
}

Comment: We need code... we need a specific question... we need something.
Comment: yep, it's just a test code :-)#include

int main (){

    printf("Hello World");
}
Comment: You say it builds and there is no result. Did you actually try running it?
Comment: In fact, I push the run button, then the outbut is "build succeeded", but in the console, nothing such as a result
Answer: You should create a Command Line Tool project, not Generic C++ Plugin.
Once you do that, your output will show up in the console window in xcode.

Xcode beginner - compiling issue


How many values of $\theta$ give $cos(\theta)$ is algebraic

Question: I recently saw Lindemann's proof that $\pi$ is transcendental by using the fact that $e^{i\pi} = -1$, and this made me realize that the Lindemann-Weierstrass theorem implies that the $\cos$ , $\sin$  of all rational angles is transcendental.
Do we know anything about the other direction, that is, which transcendental numbers give algebraic answers for the trig functions.
Thanks :)
Comment: Try using the intermediate value theorem - what is the image of $\cos$ and $\sin$?
Comment: The intermediate value theorem would suggest that for every algebraic number $\in [-1,1] \exists$ corresponding transcendental numebr , but the only way I can think to represent them would be to use arcsin or arccos, is there anything I should research to better understand what these arcsin or arccos transcendental numbers represent beyond being the inverse sin or cos functions, if there is anything to be understood there.
Answer: I don't have much depth to offer here, but I do find the question quite engaging; so I fooled around with it for awhile and was able to affirm my hunch that, at the very least, the cosine of any rational multiple of $\pi$ is algebraic over $\Bbb Q$; the calcuations are pretty simple though a little "grungy"; here's what I've got:
Set
$\theta = \dfrac{p \pi}{q}, \; 0 \ne p, 0 < q \in \Bbb Z; \tag 1$
then
$e^{i\theta} = \cos \theta + i \sin \theta = \cos \left (\dfrac{p \pi}{q} \right ) + i \sin \left ( \dfrac{p \pi}{q} \right ); \tag 2$
$(e^{i\theta})^q = e^{iq \theta} = \cos q \theta + i \sin q \theta$
$= \cos q \left ( \dfrac{p \pi}{q} \right ) + i \sin q \left ( \dfrac {p \pi}{q} \right ) = \cos p \pi + i \sin p \pi = (-1)^p; \tag 3$
$(e^{i\theta})^q = (\cos \theta + i\sin \theta)^q =  \displaystyle \sum_0^q i^{k}\dfrac{q!}{k!(q - k)!} \cos^{q - k} \theta  \sin^k \theta; \tag 4$
we may break this sum into two sums, over even and odd $k$, which are then its real (even) and imaginary (odd) parts; we will effect this operation by introducing a new index $j$ such that
$\displaystyle \sum_0^q i^{k}\dfrac{q!}{k!(q - k)!} \cos^{q - k} \theta  \sin^k \theta = \sum_{j = 0}^{ 2j \le q} i^{2j} \dfrac{q!}{(2j)!(q - 2j)!} \cos^{q - 2j} \theta  \sin^{2j} \theta$
$+ \displaystyle \sum_{j = 0}^{ 2j + 1 \le q} i^{2j + 1} \dfrac{q!}{(2j + 1)!(q - 2j - 1)!} \cos^{q - 2j - 1} \theta  \sin^{2j + 1} \theta; \tag 5$
since $i^{2j} = (-1)^j$ and $i^{2j + 1} = (-1)^j i$, the sums on the right may be re-written and we have
$(e^{i\theta})^q = \displaystyle \sum_{j = 0}^{ 2j \le q} (-1)^j \dfrac{q!}{(2j)!(q - 2j)!} \cos^{q - 2j} \theta  \sin^{2j} \theta$
$+  \displaystyle i \sum_{j = 0}^{ 2j + 1 \le q} (-1)^j \dfrac{q!}{(2j + 1)!(q - 2j - 1)!} \cos^{q - 2j - 1} \theta  \sin^{2j + 1} \theta; \tag 6$
we see from (3),
$(e^{i\theta})^q = (-1)^p, \tag 7$
that $(e^{i\theta})^q$ is real; therefore, the second sum on the right of (6) vanishes; being a real multiple of $i$, this entire sum represents the imaginary part of $(e^{i\theta})^q$; we therefore need not deal further with this second sum, and will from here on only focus on the first, which is the real part of $(e^{i\theta})^q$; thus,
$(e^{i\theta})^q = \displaystyle \sum_{j = 0}^{ 2j \le q} (-1)^j \dfrac{q!}{(2j)!(q - 2j)!} \cos^{q - 2j} \theta  \sin^{2j} \theta = (-1)^p; \tag 8$
our next step is to use the identity
$\sin^2 \theta = 1 - \cos^2 \theta \tag 9$
to eliminate the $\sin^{2j} \theta$ factors in (8), replacing them by
$\sin^{2j} \theta = (\sin^2 \theta)^j = (1 - \cos^2 \theta)^j, \tag{10}$
whence
$(e^{i\theta})^q = \displaystyle \sum_{j = 0}^{ 2j \le q} (-1)^j \dfrac{q!}{(2j)!(q - 2j)!} (\cos^{q - 2j} \theta) (1 - \cos^2 \theta)^j = (-1)^p, \tag{11}$
or
$(e^{i\theta})^q - (-1)^p = \left (\displaystyle \sum_{j = 0}^{ 2j \le q} (-1)^j \dfrac{q!}{(2j)!(q - 2j)!} (\cos^{q - 2j} \theta) (1 - \cos^2 \theta)^j \right ) + (-1)^{p + 1} = 0, \tag{12}$
which shows that $\cos \theta = \cos (p\pi / q)$ satisfies the polynomial
$P_{p, \; q}[x] =  \left (\displaystyle \sum_{j = 0}^{ 2j \le q} (-1)^j \dfrac{q!}{(2j)!(q - 2j)!} x^{q - 2j} (1 - x^2)^j \right ) + (-1)^{p +1} \in \Bbb Q[x], \tag{13}$
and is hence algebraic over $\Bbb Q$.  In fact, it is easy to see that the  coefficients of $P_{p, \; q}[x]$ are integers, so that indeed
$P_{p,\; q}[x] \in \Bbb Z[x]. \tag{14}$
Now it should come as no surprise that the "results" derived here are well-known, and deeply analyzed; see this wikipedia article on Chebyshev_polynomials.


Gluing function on subspace

Question: I am considering function $f(s,t,x,y,z)$ in $\mathbb{R}^5 = {[s,t,x,y,z]}$ satisfing
$f \equiv s \pmod{ (x-s,y-t,z-s-t)}$
$f \equiv s+2t \pmod{ (x-s,y+t,z-s-t)}$
$f \equiv -s \pmod{ (x-s,y+t,z+s+t)}$
$f \equiv -s \pmod{ (x+s,y-t,z-s-t)}$
$f \equiv s+2t \pmod{ (x+s,y-t,z+s+t)}$
$f \equiv s \pmod{ (x+s,y+t,z+s+t)}$.
I found such $f$ in fraction form $f= (z-y)x/s = -(z-x)y/t + (s+t) = (x-y)z/(s+t) + t$,
but I cannot find $f$ in polynomial form.
Does such polynomial exist? If not, why?

Geometrically, I am considering the ring $A=\mathbb{R}[s,t,x,y,z]/I$, where $I = (x^2-s^2,y^2-t^2,z^2-(s+t)^2, (s-x)(t-y)(s+t+z), (s+x)(t+y)(s+t-z))$ has vanishing set corresponding to the union of 6 planes defined by the 6 ideals described above.
Since $f$ on any two planes agree on their intersection, I expected $f$ can extend to whole function on $A$, but it seems I cannot. How should I understand it?
Answer: Why could I expect $f$ can extend?
I found counterexample in lower dimension.
There is no polynomial function in $k^2$ satisfying
$f(x,y)=y$ on $x=0$, $f(x,y)=0$ on $y=0$, and $f(x,y)=0$ on $y=x$
(because $f$ must divisible by $y(y-x)$)
If rational function is allowed, I have for example $y(y-x)/(y+x)$ (excluding the origin)

Gluing function on subspace