Can JAXB output an ArrayList as comma separated values?

Question: I have something like
@XmlElementWrapper(name="Mylist")
List<Items> myItems = new ArrayList<Items>()

and that comes  out like
<Mylist>
   <myItems>item 1</myItems>
   <myItems>item 2</myItems>
   <myItems>item 3</myItems>
</Mylist>

Is it possible to make this come out more like
<Mylist>
   <myItems>item 1, item 2, item 3</myItems>
</Mylist>

Since the data I am after is all just textual anyway?
Answer: You can use @XmlList to make it a space separated value.
For a comma separated list you will need to use an XmlAdapter.  For more information on XmlAdapter see:

http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
Comment: Are you saying in the new adapter class then I would simply cat all the items in the list together, and use @XmlValue on the newly created string?
Comment: Yes, then going the other direction you could tokenize the String on the ',' character.
Answer: Here's an XmlAdapter to handle comma separated lists:
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class CommaSeparatedListAdapter extends XmlAdapter<String, List<String>> {

    @Override
    public List<String> unmarshal(final String string) {
        final List<String> strings = new ArrayList<String>();

        for (final String s : string.split(",")) {
            final String trimmed = s.trim();

            if (trimmed.length() > 0) {
                strings.add(trimmed);
            }
        }

        return strings;
    }

    @Override
    public String marshal(final List<String> strings) {
        final StringBuilder sb = new StringBuilder();

        for (final String string : strings) {
            if (sb.length() > 0) {
                sb.append(", ");
            }

            sb.append(string);
        }

        return sb.toString();
    }
}

You would use it like this:
@XmlElementWrapper(name="Mylist")
@XmlJavaTypeAdapter(CommaSeparatedListAdapter.class)
List<Items> myItems = new ArrayList<Items>()

Answer: you can accomplish that by making the field transient @XmlTransient and creating a method for calculating a String with a comma-separated.
@XmlTransient
List<Items> myItems = new ArrayList<Items>()

@XmlElement(name = "myItems")
public String getItemsAsCommasSeparated() {
    return String.join(", ", myItems);
}

About the wrapping <Mylist> if it is really necessary you will have to wrap the list into a another object.


Let $ T:\ell^2 (\Bbb Z_{N})\to\ell^2 (\Bbb Z_{N})$ be defined by $(T(z))(n)=z(n+1)-z(n)$

Question: Let $T$ be a linear transformation of $\ell^2 (\Bbb Z_{N})$, for some given integer $N>0$.  I am being asked to find all the eigenvalues of $T$ but I don't quite know how to approach this.  Can I get some help?  I feel like there is too less information.
Comment: What is $Z_N$ ?
Comment: I gathered from the comments elsewhere that it represents the (finite set of) integers modulo $N$, so I made that clear. (Fairly strange to see the $\ell^2$ space of a finite set, but in the context of `fourier-analysis` I can understand the choice of notation). You complaint of "too less information" is not founded; this is a perfectly clear linear operator for which you can easily write down the matrix (on an obvious basis).
Answer: If $Tz = \lambda z$, then
$$
\lambda z(n) = (Tz)(n) = z(n+1) - z(n)
$$
so $z(n+1) = (\lambda + 1)z(n)$ for all $n$.
Let $z$ be an eigenvector; if $z(1) = 0$, then $z(2) = 0$, implying $z(3) = 0$ and so forth. Thus $z(1) \neq 0$, and so we can assume it is $1$ (as eigenvectors are only determined up to scale). In this case, $z(n) = (1 + \lambda)^{n-1}$. Under what circumstances does a sequence defined this way belong to $\ell^2(Z_N)$?
Comment: Either $z(1) = 0$ or it doesn't. If it does, then the fact that $z(n+1) = (\lambda + 1)z(n)$ means $z(2) = (\lambda + 1)0 = 0$, $z(3) = (\lambda + 1)0 = 0$, etc. That is, *all* entries of $z$ are zero. Since the sequence of all zeros *cannot* be an eigenvector, then we must have $z(1) \neq 0$.
Comment: How are you coming up with z(1)=0, z(2)=0 and so forth.  I don't understand what you're doing can you please elaborate more?
Comment: Sorry, I should have cleared this up a long time ago, but what exactly does $Z_N$ denote here?
Comment: set of integers mod n
Comment: so this is square summable sequences of integers mod $n$?
Comment: I'm not so sure what you mean.
Comment: This space consists of sequences $\{z(n)\}$ such that $\sum_n (z(n))^2 < \infty$ and with every $z(n)$ and integer mod $N$? In particular, it seems you can only have $\sum_n (z(n))^2 < \infty$ if $z(n) = 0$ eventually (if there is $N$ such that $z(n) = 0$ for all $n \geq N$).
Comment: On further thought, I guess only $(z(n))^2 = 0$ eventually is required.


Order of elements within a group

Question: If $G$ is a finite group of order (size) $n$ then, for any $g \in G$, the order (period) of $g$ is a divisor of $n$.
Proof: $g$ must have finite order since $G$ is finite. If the order (period) of $g$ is $m$ then the order (size) of the cyclic subgroup $\left<g\right>$ it generates is also $m$. Since $G$ has a subgroup of size $m$, Lagrange's Theorem tells us that $m$ is a divisor of $n$.
What does this proof mean by "$g$ must have finite order since $G$ is finite". Firstly, are we talking about the order (period) or order (size) and either way why does $G$ being finite mean $g$ has finite order?
Comment: $g$ must have finite order since $G$ is finite means there must exist $n \in \mathbb N$ such that $g^n = e$ where $e$ is the identity of $G$. If $g$ did not have finite order, that would mean that there does not exist $k \in \mathbb N$ such that $g^k = e$, we write $\vert g \vert = \infty$ in that case.
Answer: If $G$ is finite, and $g \in G$, look at the sequence $g^i$ for integer $i \ge 1$, i.e. $g^i = \{ g, g^2, . . . , g^k, g^{k + 1}, . . . , \text{etc.} \}$  Since $G$ is finite, this sequence of elements of $G$ must repeat itself at some point; thus we must have $g^l = g^k$ for $l > k \ge 1$.  If we then choose $k$ to be the least integer for which such repetition occurs for some $l$, and $l$ to be the first integer after $k$ for which it does occur, we must have $g^{l - k} = e$, the identity of $G$, and $g^m \ne e$ for any $m < l - k$.  The order of $g$ is thus $l - k$.  Thus $G$ finite implies the order of any $g \in G$ finite, and now the argument based on Lagrange's theorem shows that the order of $g$ must divide that of $G$.
Hope this helps.  Happy Holidays,
and as always,
Fiat Lux!!!
Answer: For your first question: The period of $g$.
For your second question:
Suppose for a contradiction that g does not have a finite period. Then it will generate an infinite number of elements, resulting in an group with infinite number of elements which is a contradiction to the supposition that $G$ is finite.
Comment: @user2850514 $g$ is not assumed cyclic, but the group $\langle g\rangle$ it generates clearly is cyclic (i.e. it is generated by a single element, namely $g$)
Comment: 1) Ok. Can a group have an order and can a groups element have a size? - 2) So are we supposing g is cyclic then?
Comment: I refer to the size of the group as the order of the group $G$ and the period/order of the element in the group $G$ as the smallest number $n$ such that $g^n=1$ where 1 is the identity. An element of the group will not have a 'size' as it is not a set and does not contain anything.
Comment: Ok, but then surely we are talking about a subgroup of $G$, namely $\left< g \right>$ for $g\in G$, rather than the actual group $G$?
Comment: Yes, since the key idea in the proof is the group $\left< g \right>$ generated by the element $g$.
Comment: Ok, but if we just consider the line "$g$ must have finite order since $G$ is finite", how does $G$ being finite make $g$ finite, at this point we have not introduced the cyclic subgroup yet. If $g$ has finite order then there is an $m \geq 1$ such that $g^{m} = e$, does this mean that each $g^{i}$ for $1 \leq i < m$ must be inside $G$?
Comment: I've proved in my answer that if the order of the group $G$ is finite and $g\in G$ then the order of the element $g$ must be finite. For your second question, yes, $\forall 1 \leq i < m$, $g^i \in G$, since a group is closed under its binary operation.
Answer: It depends on the definition of order of an element.
My preferred definition is

Let $G$ be a group and $g\in G$. The order of $g$ is the number of elements of $\langle g\rangle$, if finite; otherwise we say the order is infinite.

Given $g\in G$, we can define $\varphi_g\colon\mathbb{Z}\to G$ by
$$
\varphi_g(n)=g^n \qquad(n\in\mathbb{Z})
$$
and $\varphi_g$ is easily seen to be a homomorphism; the image of $\varphi_g$ is exactly $\langle g\rangle$.
The homomorphism theorem then says that $\varphi_g$ induces an isomorphism between $\mathbb{Z}/\ker\varphi_g$ and $\langle g\rangle$. A known fact about subgroups of $\mathbb{Z}$ gives that $\ker\varphi_g=k\mathbb{Z}$, for a unique $k\ge0$.
If $k=0$, $\varphi_g$ is injective and so $g$ has infinite order.
Otherwise $k$ is exactly the order of $g$. In this case, $g^k=\varphi_g(k)=1$ and, for $0<n<k$, $g^n\ne1$, because $n\notin k\mathbb{Z}=\ker\varphi_g$. Another consequence, in this case, is that if $g^n=1$, then $k\mid n$.
Of course, if $G$ is finite, also $\langle g\rangle$ is finite and so the order of $g$ divides $|G|$ by Lagrange's theorem.

Defining the order of $g$ as the least positive integer $k$, if it exists, such that $g^k=1$, forces proving again, but in a complicated way, that the subgroups of $\mathbb{Z}$ are of the form $n\mathbb{Z}$. I see no reason for not using the homomorphism theorem, which is one of the most basic tools in group theory.
However, as already said in other answers or comments, when $G$ is finite there are two distinct positive integers $m<n$ such that $g^m=g^n$, so $g^{n-m}=1$. Therefore the order of $g$ is finite, according to the other definition.
Answer: Suppose $g$ is an element of the group $G$ with infinite order. What is the order of the group $G$ then? Can it be finite?

Order of elements within a group


I have a vector of length 1, and two angles (in $xz$ plane and $yz$ plane), how do i get the $x,y,z$ compontents of this vector?

Question: I just can't see what's wrong, this should be relatively simple...
I have a vector which has length 1.
Then, I have two angles. The first ($\gamma$) is the angle between the projection of the vector in the $xz$ plane and the $z$ axis.
The second ($\beta$) is the angle between the projection of the vector in the $yz$ plane and the $z$ axis.
All I need now are the (cartesian) vector components $(x,y,z)$.
How do I calculate them?
I got: $x = \sin(\gamma)\\
y = \sin(\beta)\\
z = \cos(\gamma) \cdot \cos(\beta)$
But this can't be correct, because the length of this vector is not always 1.
Can you help me and find the error, please?
Answer: I think you got $x=\sin\gamma$ by saying that you have a right triangle in the $xz$-plane with side $x$ opposite angle $\gamma$, but then you are also assuming the length of the hypotenuse is $1$. It isn't. The hypotenuse is a projection of a vector of length $1$, but (unless the $y$-coordinate turns out to be zero) it is itself a vector of length strictly less than $1$.
Perhaps a more fruitful approach begins with $\tan\gamma=x/z$.
Comment: Yes! I think this would lead much more quickly to the solution than the dot product approach I used in my answer. +1.
Comment: $x = z\tan\gamma$ and $y=z\tan\beta$ and $x^2+y^2+z^2=1$ so $z=\pm1/\sqrt{1+\tan^2\gamma+\tan^2\beta}$, huzzah!
Comment: This is indeed much quicker, but I liked coffeemath's answer, too. And there is one more good about it: actually, I do have the tangens values of both angles.


Current Date till Hour in Oracle

Question: I want to get the date with just the current hour.
Using trunc(sysdate) gives us something like 2017-06-16 00:00:00
But, I want the current hour as well :
2017-06-16 10:00:00
2017-06-16 11:00:00

and so on.
I want it to be a date (and not char), as I need it for comparison with a date column.
date_column <= day_with_hour

Answer: The trunc() function takes a second optional argument, which default to 'DD' to truncate the time to midnight. You can use 'HH' instead (or 'HH24' if you prefer for consistency with other formatting you're using elsewhere - it doesn't affect the result) to get what you want:
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';

select sysdate, trunc(sysdate, 'HH') from dual;

SYSDATE             TRUNC(SYSDATE,'HH')
------------------- -------------------
2017-06-16 09:27:43 2017-06-16 09:00:00

The date format models are also in the documentation, and a subset of those are allowed for trunc().
So your query would use:
date_column <= trunc(sysdate, 'HH')

Comment: Thanks a lot @Alex. Exactly what I've been looking for.

Current Date till Hour in Oracle


How to tune a ukulele to compensate for intonation issues

Question: I'm just starting out on the ukulele coming from a guitar background. Compared to the guitar, the intonation isn't great, and from everything I've read, the shorter neck means that's the nature of the instrument.
The uke is new, from one of the K brands, and professionally set up.
I'm not sure if I should tune it so the open string is in-tune, a fretted string, or compromise (and if I do, which which fret)?
Answer: It all depends on what you will be playing but it'd be wise to compromise and tune to your median fret. I know that if I am going to be playing around the 10th fret then I'll tune my guitar to the 10th fret.
This technique won't be practical when playing in all ranges of frets. You can however sharp/flattern a string to best compensate with what you'll be playing but sometimes finding that compensation point doesn't help your situation at all and can make both ranges of frets sound out of tune.
A good way to fight this is to be more tactical in your playing and instead of jumping up to the 8th fret for a note, just simply play the same note on another string that brings it into the lowFret->higherFret fret range - the range of where it would be 'safe to play' without having noticeably bad intonation issues on your ukulele.
Hope this helps :)
Comment: This led me down an interesting rabbit hole on equal temperament and guitars with frets at different locations for each note so every note is in tune. I also got to read up on the other temperaments and how the equal temperament is a compromise between integer ratios for intervals and being able to transpose a piece into another key.
Comment: @DavidEhrmann- this is indeed a rabbit hole.  Theoretically, you really need moveable frets to get perfect intonation, even equal temperament, on the guitar, because of having strings of the same material, but different pitches at the same length.  If you want a look at what can be done with such a guitar, with frets tuned to "funny" temperaments, check out the wonderful music of tolgahan çoğulu- https://www.youtube.com/watch?v=MYK_PF9WTRE
Answer: While you can retune so that more of what you're playing will be in tune, I think it's better to fix the problem. Ukes can have good intonation with a proper setup. I find that the best solution to intonation issues up the neck is to cut a compensated saddle for the uke. It's not perfect but it's the best solution I've found.
The general procedure is to measure the amount of deviation from the norm and compensate for it. On each string, find out how sharp or flat the note at the 12th fret is. When you get those numbers, the next step is to file a saddle so that the point of string contact makes the string slightly longer or shorter than the others. It's more or less a manual version of setting the intonation on an electric guitar with individual saddles.


How to modify a HTML file with angular schematics

Question: Let's say we have an existing angular component including menu.component.html :

home

about

The goal is to add a new link with angular schematics, just after "about"

contact

Any ideas?
Comment: How much have you looked at how to build your own schematic? Have you gone through articles such as this: https://medium.com/@tomastrajan/%EF%B8%8F-how-to-create-your-first-custom-angular-schematics-with-ease-%EF%B8%8F-bca859f3055d
Comment: I went through many articles. I found examples of modifying specific elements like a constructor or declaration in a module. here is an example [link](https://www.softwarearchitekt.at/post/2017/12/01/generating-angular-code-with-schematics-part-ii-modifying-ngmodules.aspx).
Answer: You can do something like:
export function myComponent(options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const content: Buffer | null = tree.read("./menu.component.html");
    let strContent: string = '';
    if(content) strContent = content.toString();

    const appendIndex = strContent.indexOf('
');
    const content2Append = '
contact
 \n';
    const updatedContent = strContent.slice(0, appendIndex) + content2Append + strContent.slice(appendIndex);

    tree.overwrite("./menu.component.html", updatedContent);
    return tree;
  };
}

Note that this is a very primitive solution. There are DOM parser libraries in nodejs which can make your life easier (jsdom). And you can take content2Append variable as an input and clean it up for your use case.
Comment: @saKins see my answer in how to use jsdom along with the tree recorder to update Angular templates.
Comment: Unfortunately jsdom doesn't support angular template syntax and I've been trying to search for a template parser that can help me add and manipulate a template any suggestions would be greatly appreciated!
Answer: Eko's answer is correct. I would like to expand on this answer and do two things:

Use the tree recorder to update the template
use jsdom to find the location in the template to update

With jsdom and similar tools, serializing an Angular template either will not work -- or break any camelCase, [boxed], (parenthetical), #tagged -- attributes. So we will only use jsdom to find the location of where we want to update.
function updateTemplate() {
  return (tree: Tree) => {
    const buffer = tree.read(TEMPLATE_PATH);
    const content = buffer?.toString();
    if (!content) {
      throw new SchematicsException(`Template ${TEMPLATE_PATH} not found`);
    }

    // the includeLocations flag is very important here
    const dom = new JSDOM(content, { includeNodeLocations: true });
    const element = dom.window.document.querySelector('ul');
    const locations = dom.nodeLocation(element);
    if (!locations) {
      throw new SchematicsException(`<ul> could not be found in ${TEMPLATE_PATH}`);
    }

    // now we update the template using the tree recorder
    // we don't use jsdom to directly update the template
    const recorder = tree.beginUpdate(TEMPLATE_PATH);
    const listItem = `  <li><a href="/contact">contact</a></li>\n`
    recorder.insertLeft(locations.endTag.startOffset, listItem);
    tree.commitUpdate(recorder);

    return tree;
  };
}

Again, eko's answer is correct. This answer illustrates how to use jsdom and the tree recorder together to update an Angular template -- which is useful for inserting directives, events, tags and methods into elements, wrapping sections and more complex transformations.
Comment: FYI, the simple htmlparser library seems to be able to read HTML without breaking the Angular-specific attributes. you can fairly easily modify the DOM. Rewriting it as a string is not as simple though.
Answer: Update : With the latest 1.0.0rc3 cheerio version, the xmlMode does self close tags, and this kills your template !
So instead, go with 0.22.0 cheerio version and lose the xmlMode option !

I'm testing shematics and I need to update angular component templates as well.
Here is a useful article :
https://medium.com/humanitec-developers/update-and-insert-auto-generated-code-to-existing-typescript-html-and-json-files-with-angular-9b37bdadf041
Now, be careful, with the latest versions of cheerio, you should use the xmlMode option to load your component template, or you will have a whole HTML document instead :
https://github.com/cheeriojs/cheerio/issues/1031#issuecomment-368307598
You would end up adding some HTML to an Angular template this way :
function addComponent(): Rule {
  return (tree: Tree) => {
    const filePath = './src/app/app.component.html';
    const content: Buffer | null = tree.read(filePath);
    let strContent: string = '';
    if(content) strContent = content.toString('utf8');
    const $ = cheerio.load(strContent, {
      xmlMode: true
    });
    const contentToInsert = `<my-comp></my-comp>`;
    $.root().append(contentToInsert);
    tree.overwrite(filePath, $.html());
    return tree;
  };
}

I hope this can help :)


Can Panels just be uninstalled if you want to switch themes?

Question: I used panels + panels everywhere with precision theme to build a website.
I now rather want to use Zen theme with basic blocks.
I wish to keep the content types with their fields.
If I uninstall panels will all instances of it be removed from the site?
Or should I rather just rebuild the site from a new clean installation?
Comment: Only your custom theme was using panels?
Comment: Yes, The site is also really basic.
Answer: Usually, uninstalling removes everything created by the module, its setting and its database tables.
But for what you are after, you don't even need to uninstall them, not even disabling to be honest, just don't use panels tools in your new theme.
Considering that, I would delay the idea of removing them and the old theme to after the new one is ready.
Just because of "how i did it in the other theme?" kind of questions


Is it viable to run MS SQL Server 2005 under VMWare?

Question: My firm is considering virtualising our MS SQL Servers in a VMWare environment.
I'm not directly involved in the project but as a heavy user of our existing servers I'll have some input in the process.
Does anyone have any general advice for me about this type of arrangement? Or is it perfectly normal and supported to run Virtaul SQL Servers?
Answer: Running SQL Server in a Virtual Machine is supported as stated in this MS KB:
http://support.microsoft.com/kb/956893
You can expect an overhead due to virtualization, that will cost around 5% of performance, if all best practices are respected.
Your vmware server will need to be power enough to support your SQL workflow. You will need to measure how much resource use the current SQL Server.
VMware best practice for SQL Server:
Microsoft SQL Server and VMware Virtual Infrastructure
Other resources: http://communities.vmware.com/docs/DOC-8964
Answer: We have LOTS of physical MSSQL servers and although our 1:1 reference platform is also physical all other platforms (integration, dev, test etc.) are VM'ed including these MSQL servers (both 2003 and 2008 by the way). We've had no problems with them at all, although clustering requires a methodical approach.
Answer: will surely work, but...  Virtualization for production servers is a non-sense for me (It's absolutely ok for developpers, eventually to have a warm standby server at low cost, or to made prospective tests, but not for production).
In term of performances, bad things will arrives (excepted if the load on the server is ridiculous), especially when the other db on another VM will start competing for disk access... (because it's ultimately the goal)
cf. pros and cons of server virtualization (a bit outdated, but the general concept is still true).
my two cents! (anyway, I'm surely not an expert about those things... just matter of good sense)
Comment: The article isn't that outdated (last year) but I'd very strongly argue that the author's focus is not one that is universally shared by most organisations and System Admins. x86 Virtualization is a high performance, highly reliable technology today that is not only an acceptable substitute for typical businesses production server needs but it also enables capabilities (Live Migration, Lockstep\Fault Tolerance, hardware independence, dynamic resource scheduling) that increase uptime significantly and makes systems management easier.
Comment: You'll prob want to tell all of the thousands of small and large companies using Virtualized infrastructure for their production server that they are wrong.
Comment: When it comes to hypervisor, performance is not an issue if properly done, as always. Virtualization often makes visible bad settings/implementations/architecture, which are normally hidden behind oversized and under used servers.


Why does palm muting give a higher output than a normally played power chord?

Question: Assuming you have the same amount of (high) gain, and the same amount of distortion, a palm muted strum gives a higher output than when you hit the same chord with the same amount of energy, non muted. Why is that?
Suppressing the amplitude of vibrations of the strings should adversely affect the amplitude of the output signal but that doesn't appear to be the case. I am assuming this has something to do with reduced harmonic vibrations that might cause destructive interference but I'm not sure about the physics. Could someone explain the physics of this?
By higher output I mean the power or loudness of the signal. Here's the simplest demonstration.
Comment: I don't agree with the premise of this question -- for me, palm muted is, well, muted.
Comment: You might need to explain what you mean by higher output. Is this something you measured? If so how?
Comment: I've added a video that kinda explains what I'm talking about. Its mostly there when you use high gain sounds.
Answer: It's because of the pseudo-compression that using distortion effect gives. The same will be true if you use a clean channel with a compressor, or if your amp has a natural compressing effect, as many do.
What's happening is...
You play a chord normally: You get quite nice mid-range strum of the strings, nothing surprising there.
You play a palm muted chord: you're suppressing mainly the upper frequencies and mid-range, allowing the bass in the notes to poke through more. Also the heavier strings tend to remain ringing longer than the lighter ones, which stop almost immediately so the sound is biased towards bassy and lower strings.
If using distortion or compression, the bassier sound saturates the amp (or effects box) and becomes "dominant" (in terms of volume, not music-theory-dominant .. er .. or any other kind of dominant) and you get a much chunkier sound.
Bassier notes are generally higher output so the overall effect, while it might not really sound louder (or it might), is a higher output.
If you try all this on a straight guitar with no distortion/compression, or an acoustic guitar, then you won't get the saturation and the palm-muted chords will sound quieter.
Comment: Yep, I think you nailed it man. I had a feeling this was the case. So is it like when you have natural harmonics, you remove certain harmonics from the harmonic pattern of the not and you get the corresponding harmonic. So in case of a palm mute your hand position is very close to the bridge and most high order harmonics are removed from the signal's harmonic pattern leaving behind the lower frequency harmonics? (Do I make sense?)
Ps: Thanks :)
Comment: ps. great question :-)
Comment: Yes, exactly that :-)  - with compression (or distortion) I think of it as :  the sound wants to be the same volume (owing to the effect), so whatever you take away, what's left kind of rushes in to fill the gap. Gotta say I love this effect and use it a lot
Comment: So do I... It just suddenly hit me that I didn't know how it worked exactly.
Comment: +1 to the question and +1 to the answer. But I get a similar result with a DI box too. Is it possible that my pick-ups have some built-in compression too? (I always feel that's the case but it's not easy to confirm)
Comment: Pickups will also influence the output. The output current is actually caused by electromagnetic induction which is directly related to the coils in the pickup, and hence related to the design of the pickup. Hence, certain pickups are said to be higher output than others. I can't say anything about built-in compression though. Magnetic pickups usually do not have any DSP built-in.
Comment: @cyco130 - I guess Blinkytop's answer plays a part too , in that case? I don't think pickups generally have any compressing effect though
Answer: I imagine when your palm is muting the strings, you are picking them from a different angle or using a different muscle in your arm or wrist that is supplying more energy to the attack.
When you attack with your pick deeper in the strings, it tends to be generally louder because it takes more energy for your hand to pull the pick across.
Comment: I agree with the fact that a pick has more attack if you palm mute but try the same picking technique without your palm muting the strings. I'm pretty sure the signal would not clip even if you use more force (don't break the strings).
Intuition tells me that this isn't the only factor and that the physics of sound are involved in this phenomenon. Could someone please confirm this?
Comment: I agree with this too - I think when you palm-mute a string, assuming you're using a pick as well, the point where it hits the strings is a kind of "sweet spot" given they're muted. I suspect it's possible to clunk the strings harder under these circumstances without them doing anything nasty like rattle against the neck etc.


Echo equivalent in PowerShell for script testing

Question: I would like to output variables and values out in a PowerShell script by setting up flags and seeing the data matriculate throughout the script.
How would I do this?
For example, what would be the PowerShell equivalent to the following PHP code?
echo "filesizecounter: " . $filesizecounter

Comment: Check out the script-editor/debugger that comes with [PowerGUI](http://www.powergui.org/index.jspa). It may be suitable for what you are doing. I understand that Powershell 2 comes with a debugger too (but I haven't tried it).
Answer: There are several ways:
Write-Host: Write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to be set.
Write-Debug: Write directly to the console, if $DebugPreference set to Continue or Stop.
Write-Verbose: Write directly to the console, if $VerbosePreference set to Continue or Stop.
The latter is intended for extra optional information, Write-Debug for debugging (so would seem to fit in this case).
Additional: In PSH2 (at least) scripts using cmdlet binding will automatically get the -Verbose and -Debug switch parameters, locally enabling Write-Verbose and Write-Debug (i.e. overriding the preference variables) as compiled cmdlets and providers do.
Comment: The nice thing about Write-Debug and Write-Verbose is that you can leave your debug statements in your code, and just turn on the output when you need it using the appropriate preference variable.  Saves time and is a nice feature for other users of  your functions.
Comment: You also want to get familiar with Out-String, because with any non-trivial object, you'll need to use that to convert the object to a display-able string before using any of those three Write-* cmdlets.
Answer: Powershell has an alias mapping echo to Write-Output, so you can use:
echo "filesizecounter : $filesizecounter"

Comment: `echo` is an alias to `Write-Output` as per Microsoft's [TechNet](https://technet.microsoft.com/en-us/library/hh849921.aspx) and discussed [here](http://stackoverflow.com/a/17623902/857209)
Comment: Why wouldn't you want to bypass the pipeline if all you want to do is echo "debug" output to the console to trace execution of a script? Write-Output has a weird side-effect where the content of the last call to Write-Output will be left on the stack, overriding any variable you attempt to explicitly return from a function. Side-effects like that feel like an awfully screwy way for a language to behave.
Comment: Thanks Glenn, it looks like the alias has been remapped in the 6 years since I posted this. Which is good, one really shouldn't use Write-Host as it bypasses the pipeline. I've updated my reply to indicate this. Thanks!
Answer: PowerShell interpolates, does it not?
In PHP
echo "filesizecounter: " . $filesizecounter

can also be written as:
echo "filesizecounter: $filesizecounter"

In PowerShell something like this should suit your needs:
Write-Host "filesizecounter: $filesizecounter"

Answer: Write-Host "filesizecounter : " $filesizecounter

Answer: By far the easiest way to echo in powershell, is just create the string object and let the pipeline output it:
$filesizecounter = 8096
"filesizecounter : $filesizecounter"

Of course, you do give up some flexibility when not using the Write-* methods.
Answer: echo is alias to Write-Output although it looks the same as Write-Host.
It isn't What is the difference between echo and Write-Host in PowerShell?.
echo is an alias for Write-Output, which writes to the Success output stream. This allows output to be processed through pipelines or redirected into files. Write-Host writes directly to the console, so the output can't be redirected/processed any further.
Answer: The Write-host work fine.
$Filesize = (Get-Item $filepath).length;
Write-Host "FileSize= $filesize";

Answer: It should also be mentioned, that Set-PSDebug is similar to the old-school echo on batch command:
Set-PSDebug -Trace 1

This command will result in showing every line of the executing script:

When the Trace parameter has a value of 1, each line of script is traced as it runs. When the parameter has a value of 2, variable assignments, function calls, and script calls are also traced. If the Step parameter is specified, you're prompted before each line of the script runs.
Comment: I think this is the right answer, frankly as the default behavior of PS is not to write out commands automatically. +1 Vote!
Answer: PowerShell has aliases for several common commands like echo. Type the following in PowerShell:
Get-Alias echo

to get a response:
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           echo -> Write-Output

Even Get-Alias has an alias gal -> Get-Alias. You could write gal echo to get the alias for echo.
gal echo

Other aliases are listed here:
https://learn.microsoft.com/en-us/powershell/scripting/learn/using-familiar-command-names?view=powershell-6
cat dir mount rm cd echo move rmdir chdir erase popd sleep clear h ps sort cls history pushd tee copy kill pwd type del lp r write diff ls ren
Answer: I don't know if it's wise to do so, but you can just write
"filesizecounter: " + $filesizecounter

And it should output:

filesizecounter: value
Comment: `"filesizecounter:  $filesizecounter"` is even shorter.
Answer: Try Get-Content .\yourScript.PS1 and you will see the content of your script.
also you can insert this line in your scrip code:
get-content .\scriptname.PS1
script code
script code

....
Comment: Doesn't show actual values processed (e.g. env var substitution) so not an answer to the question asked.


Postfix cannot send to external domains

Question: I set up my Postfix with a sasl link to a Dovecot user / domain database.
Postfix is giving the following error message when trying to send mail to external recipients (internal are fine):
Server error: '550 5.1.1 : Recipient address rejected: User unknown in virtual mailbox table'
<code># postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
content_filter = scan:127.0.0.1:10025
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
html_directory = no
inet_interfaces = all
inet_protocols = all
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination =
myhostname = (my.hostname.com)
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES
receive_override_options = no_address_mappings
sample_directory = /usr/share/doc/postfix-2.6.6/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_type = dovecot
smtpd_tls_cert_file = /etc/postfix/postfix_cert.pem
smtpd_tls_key_file = /etc/postfix/postfix_key.pem
unknown_local_recipient_reject_code = 550
virtual_gid_maps = static:502
virtual_mailbox_base = /home/mailadmin
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_minimum_uid = 502
virtual_transport = virtual
virtual_uid_maps = static:502
</code>
I've been trying different things for the past few hours, but no luck.
What could be the cause?
Thanks.
Comment: Have you tried setting mydestination yet? Postfix is trying to deliver external mail on your local machine, and having 'mydestination =' could be a factor in that.
Comment: Yes, I tried that multiple times. I just set mydestination = $myhostname in main.cf, and reloaded postfix, but that did not change anything. Any other ideas?
Answer: After another whole day of reading documentation and tampering with settings, I was finally able to resolve the issue. The problem was in mysql_virtual_domains_maps.cf, which had a MySQL query that did not take an argument, and therefore always returned the same result (the list of all available domains). The correct situation is when the query only returns a result when there is a match. Hopefully this helps someone else, who happens to run into the same issue.

Postfix cannot send to external domains


How to inherit from QWidget in PyQt?

Question: Maigcally I can't inherit from QWidget using PyQt 4:
from PyQt4.QtGui import QApplication, QMainWindow, QWidget

class MyWidget(QWidget):
    pass

if __name__ == "__main__":
    app = QApplication([])
    window = QMainWindow()
    window.resize(200, 200)
    widget1 = MyWidget(window)
    widget1.resize(100, 100)
    widget1.setStyleSheet("background-color:#FFFFFF")
    window.show()
    app.exec_()

It doesn't work. I just can't see the widget. But, using QLabel instead of QWidget works.
Thanks.
Solution
Reimplement paintEvent:
class MyWidget(QWidget):
    def paintEvent(self, event):
        o = QStyleOption()
        o.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, o, p, self)

Comment: How do you mean it doesn't work? Is there an error? Does the window not appear? You need to be a little more descriptive.
Comment: The widget doesn't appear inside the window.
Comment: Can you attach a screenshot of the difference? Based on your code, although you declare a parent of the DnDWidget, you don't actually place it inside the window, so I'd expect it wouldn't show up.
Comment: This is the preview of the code above: [link](http://i.imgur.com/MwdoNQ5.png). And this is the preview if I inherit from QLabel: [link](http://i.imgur.com/ZDPiDTc.png)
Answer: You are subclassing correctly. The "problem" is just that the QWidget has the same background colour as the main window (your call to setStyleSheet is not working).
As proof, run this code from a terminal:
from PyQt4.QtGui import QApplication, QMainWindow, QWidget, QLabel

class MyWidget(QWidget):
     def enterEvent(self, evt):
        print 'a'

if __name__ == "__main__":
    app = QApplication([])
    window = QMainWindow()
    window.resize(200, 200)
    widget1 = MyWidget(window)
    widget1.resize(100, 100)
    widget1.setStyleSheet("background-color:#FFFFFF")
    window.show()
    app.exec_()

When you move your mouse into the first 100,100 pixel square, you will see the letter 'a' being printed in the terminal
Comment: When using this code, changing the stylesheet to any color deosnt work
Comment: Any idea why the call to setStyleSheet is not working? I'm running into the same issue and I assumed that MyWidget should behave exactly like QWidget when it inherits from QWidget and doesn't override any methods.

How to inherit from QWidget in PyQt?


How to calculate such an simple integral?

Question: I have this integral: $\displaystyle \int^{\infty}_0 kx e^{-kx} dx$.
I tried integrating it by parts:
$\dfrac{1}{k}\displaystyle \int^{\infty}_0 kx e^{-kx} dx = ... $. But I'm stuck
now. Can you help me please?
Comment: Where are you stuck? Can you say what you have tried?
Answer: hint: $\displaystyle \int kxe^{-kx}dx = -\displaystyle \int xd(e^{-kx})$
Comment: @Yang-Hui I would like to clarify this answer for you a bit more. DeepSea is recommending you make the substitution $u=e^{-kx}$, making $$du=d(e^{-kx})=-ke^{-kx}\,dx$$
Comment: Am I right @DeepSea ?
Comment: @ChaseRyanTaylor: You got it Chase !
Comment: $$\Huge\ddot\smile$$
Answer: Just take $kx = y$ so you will have $$\int_{0}^\infty\frac{y}{e^y}dy$$
Take $u = y$ and $dv = \frac{1}{e^y}$, after integrate just remeber change $y = kx$
Answer: Try explicitly writing out what $u$ and $dv$ are in your integration by parts. In this case, you should have $u=kx$, and $dv=e^{-kx}\,dx$. Thus, $du=k\,dx$, and $v=-\frac{1}{k}e^{-kx}$. Now apply the integration-by-parts formula:
$$\int_{0}^{\infty}{u\,dv}={\left.uv\right|}_0^{\infty}-\int_{0}^{\infty}{v\,du}$$


Is Conway's "Course in Functional Analysis" suitable for self-studying?

Question: Is John B. Conway's book "A Course in Functional Analysis" a good book for self-studying functional analysis?
(I have a solid knowledge of undergraduate analysis and linear algebra, group theory, general topology and I am familiar with basic techniques and theorems of complex analysis. I usually prefer generality instead  of unneccesary constrictions and am comfortable with the omission of trivial steps in proofs.)
Comment: It's a great book so it should be doable, but you might also want to supplement it with Kreyszig's book. There are also lots of good functional analysis course notes pdfs from graduate courses floating around online.
Answer: It has been a while since I studied it, but I've used this as a course text to a course I couldn't attend the lectures of, and it wasn't exceptionally hard to pass. Your comments give no immediate reason to suspect it would be a bad choice; but be prepared for a quite substantial amount of proofs "left to the reader".
Answer: I was going through this book today, and I think it would be way easier to digest the material if one read Kreyszig first (and also had some measure theory knowledge...)


codeigniter session not set first time

Question: I have a problem. I am setting session on a login page. But when the page redirects where session does not initiate on the first attempt. When I login second time then session has set.
I am stuck what is the problem.
Here is my code
<code>$data = $this->input->post();
    //$data['password'] = $this->encrypt->encode($data['password']);
    $result = $this->Login_m->get_userdata($data['username']);
    $result['password'] = $this->encrypt->decode($result['password']);
    //print_r($result);

    if (strtolower($data['username']) === strtolower($result['username']) and $data['password'] === $result['password'] ) {

        unset($result['password']);
        $this->session->set_userdata('user', $result);
        redirect("dashboard");
    }else{
        $this->session->set_flashdata("error","Given Username or Password is not correct");
        redirect("login");
        die();
    }
</code>
Please help.
Thank you in advance.
Comment: Try redirect('dashboard', 'refresh'); Also, I now always access the session variable directly $_SESSION['some_name']. Just as an aside, encrypt encode and decode should NOT be used for passwords. You should use one way hashing only. It is well described in php.net here http://php.net/manual/en/function.password-hash.php
Comment: do a `var_dump($this->session->userdata('user');` just before the `redirect` and see if the session is being set properly
Comment: Thank you soo much for your information. #PaulD. I will follow this.
Answer: I think this is because of browser cache. Try setting below no cache headers rules on refresh(Or in your constructor):
<code>header('Cache-Control: no-cache');
header('Pragma: no-cache');
</code>

codeigniter session not set first time


Problem with serialization callbacks and AddSubtype in protobuf-net

Question: <code>  public class A
  {
    public int X { get; private set; }
    public A(int x)
    {
      X = x;
    }

    public static implicit operator ASurrogate(A a)
    {
      return a == null ? null : new ASurrogate { X = a.X };
    }
    public static implicit operator A(ASurrogate a)
    {
      return a == null ? null : new A(a.X);
    }
  }

  [ProtoContract]
  public abstract class ASurrogateBase
  {
    public abstract int X { get; set; }
  }

  [ProtoContract]
  public class ASurrogate : ASurrogateBase
  {
    [OnSerializing]
    public void OnSerializing(StreamingContext context)
    {
      X = 17;
    }

    [OnDeserialized]
    public void OnDeserialized(StreamingContext context)
    {
      X = 117;
    }

    [ProtoMember(1)]
    public override int X { get; set; }
  }

  [ProtoContract]
  public class B
  {
    [ProtoMember(1)]
    public A A { get; set; }
  }

  class Program
  {
    static void Main()
    {
      var m = RuntimeTypeModel.Default;
      m.AutoCompile = false;
      m.Add(typeof(ASurrogateBase), true).AddSubType(1, typeof(ASurrogate)); // (*)
      m.Add(typeof(A), false).SetSurrogate(typeof(ASurrogate));

      var b = new B { A = new A(117) };
      using (var ms = new MemoryStream())
      {
        Serializer.Serialize(ms, b);
        ms.Position = 0;
        var b2 = Serializer.Deserialize<B>(ms);
        Debug.Assert(b.A.X == b2.A.X);
      }
    }
  }
</code>
The problem with this program is that neither serialization callback is invoked. If, however, I remove the statement (*), then everything works.
Is it by design?
Answer:
Is it by design?

No it isn't. The short version is that it wasn't considering inheritance of surrogates, and (for various reasons) most of the callbacks are only invoked by the effective base type of an inheritance chain (the exception here is OnDeserializing, which is invoked at sub-type levels as objects are created).
This is fixed in r414


Appcelerator - barImage hides the title text

Question: When I create a new window in Appcelerator I need to change the background image. This is done by setting "barImage". The window itself is a child of a navigation group and has its own children. When I use the "barImage" parameter it hides the nav bar title text on the initial load of the window. If I navigate to its child window and then back the title text is displayed in the nav bar.
<code>var sectionWindow  = Titanium.UI.createWindow({
    backgroundColor:'#fff',
    fullscreen:false,
    title:'My Sub Page',
    modal:true,
    barImage:'images/nav_bar.png'
});
</code>
How can I get the title text to consistently display?
Answer: I believe there are known issues with the barImage in the 1.7.2 release, please check the 1.8x CI builds where the issue has been addressed
Comment: Thanks, where can I get the 1.8x CI builds?


Procedure for extending a suspension period

Question: During the 1-1 draw between Liverpool and Crystal Palace (2022-08-15), Liverpool's Darwin Núñez was sent off for a headbutt on Crystal Palace defender Joachim Andersen.
It is my understanding that a straight red card for serious foul play / violent conduct is an automatic 3-game ban, however there have been numerous reports in the media in the aftermath of the incident that Núñez could be banned for more than the standard three games. As an example of this happening before, Luis Suarez was infamously handed a 10-game ban for biting Branislav Ivanovic in 2013.
What is the procedure for determining an extension to the 3-game ban?
For example, in Rugby Union, if a player is sent off they are required to attend a Disciplinary Committee hearing, in which the referee's report of the incident, the player's reflection on the offending action, the player's past discipline record, plus other factors, are all taken into account to determine how long the suspension is.
Note: For scope, and as I believe this will likely differ between football associations - I will be looking for procedures from the English FA, as that is who Núñez's suspension resides with. Although if there is a standardised FIFA/UEFA procedure that is followed by the FA, then that is fine, too.
Comment: I haven't had a chance to go through it in detail but I strongly suspect the answer is in the [FA Handbook](https://www.thefa.com/football-rules-governance/lawsandrules/fa-handbook) in Section 11 "Disciplinary Regulations", starting on page 172 of 713(!) of the handbook.
Answer: My understanding, as an experienced referee of soccer/football at many levels, of the way that suspensions are determined (in Australia at least) is that all the factors you have mentioned are considered against prior cases as precedent for punishment.
In Australian sports at many levels of professionalism, these decisions are specifically made by lawyers specialising in interpretation of the Laws of the Game (or equivalent for a given sport) and competition rules. This is intended to remove prejudice or biases from the decision and remove the sports governing body (such as the FA) from the process.
In this specific example, the review committee might look at factors such as malice, force or intent. While there is no excusing Núñez's actions, they would have been objectively worse if, for example, he had held Andersen's head and directed his headbutt more directly into his face, or followed the initial strike with one or more subsequent blows.
As for procedures, as far as I am aware, these are specifically held in confidence by the reviewing bodies, but can be assumed to be fairly similar to regular courtroom trial, albeit without a jury.
Comment: Hi! We're looking for more than an individual's understanding, unless you have professional knowledge of the matter (e.g., a referee or official of a football association).  In particular, rule citations or similar evidence are expected in answering questions like this.  Thanks!
Comment: Hi Joe, thanks for that, I do have experience as a referee at many levels of the game. I will add this to my answer, but was also trying to emphasise that these matters are actually beyond that of referees or even the governing body.


structural vs behavioural design patterns

Question: I just started reading design patterns and I have some basic doubt and was not clear even after going through many articles. Can someone please explain me following? I have seen many similar posts here but they are not very clear.

How did they segregate in to structural and behavioural patterns?
Is there any good book to follow?Now I am following Head first design patterns.
What is the easy way to remember all these patterns and apply? I thought of remembering UML diagram and concept for each pattern. Do you suggest any other way?
Comment: Head first *is* a good book, and much easier to read than the well known *Design Patterns: Elements of Reusable Object-Oriented Software*. Anyway, a similar question was asked [on Programmers](http://programmers.stackexchange.com/questions/124109/is-there-a-canonical-book-on-design-patterns). Quite a while ago, but most books that were good then will still be good. Voting to close this one as off topic because it's broad (three questions in one), opinion based (especially 3) and asking for off-site resources.
Comment: The best way to understand patterns is practice, practice, and practice :)
Comment: I would like to add that resource requests (including for books) are [off-topic at Programmers](http://meta.programmers.stackexchange.com/a/6487/22815). The linked question is quite old, and from before resource requests became off-topic at Programmers.
Answer:

How did they segregate in to structural and behavioural patterns?

From Gof book

"Structural patterns are concerned with how classes and objects are composed to form larger structures. "

some structural patterns:

Adapter
Decorator
Facade
Proxy
Flyweight

etc

"Behavior patterns are concerted with algorithms and the assignment of responsibilities between objects.  Behavioral patterns describe not just the patterns of objects or classes but also the patterns of communication between them."

Some behavior patterns:

Chain of Responsibility
Command
Iterator
Mediator
Observer
Visitor

etc

Is there any good book to follow?Now I am following Head first design patterns.

This question is out of scope of SO since we aren't really supposed to recommend books.

What is the easy way to remember all these patterns and apply? I thought of remembering UML diagram and concept for each pattern. Do you suggest any other way?

UML diagrams of design patterns are confusing because several patterns have identical or similar enough diagrams that you can't tell them apart. Unfortunately, the easiest way is to just use them enough to just know how to use them.  And keep a Design Pattern book handy to find motivations for the lesser used patterns you don't remember off the top of your head.


$|f(z)\mathrm{d}z|<M\cdot l(\gamma)$ type problem proof.

Question: We want to prove that
$$
\left|\int_{\gamma}\cos(z)\mathrm{d}z\right|\leq \frac{e^2+1}{2e}
$$
where $\gamma$ is a line segment from $z=0$ to $z=i$.
I have thought the following. The parametrization of the line is $z(t)=it$. This is clear. Then from the formula of $\cos(z)$, we have
$$
\cos(z)= \cos(it) = \frac{e^{i(it)}+e^{-i(it)}}{2} = \frac{e^{-t}+e^t}{2}
$$
But, I don't know how to continue my proof. Is $l(\gamma)=1$? Do we have to take the integral of $\cos(z)$? Any help would be appreciated.
Answer: You have
\begin{align}
\left|\int_\gamma\cos(z)\,dz\right|&=\left|\int_0^1\cos(it)i\,dt\right|\\
&=|i|\left|\int_0^1\frac{e^t+e^{-t}}2\,dt\right|\\
&=\int_0^1\frac{e^t+e^{-t}}2\,dt\\
&\le\int_0^1\frac{e+e^{-1}}2\,dt\\
&=\frac{e^2+1}{2e}.
\end{align}
Answer: $\cos(z)$ is the derivative of $\sin(z)$, so that
$$
 \int_{\gamma} \cos(z) \, dz = \sin(i) - \sin(0) = \sin(i) = \frac{e^{-1}-e^{+1}}{2i} = \frac{1-e^{2}}{2ie}
$$
for any path $\gamma$ from $0$ to $i$. Therefore is
$$
 \left| \int_{\gamma} \cos(z) \, dz \right| = \left| \frac{1-e^{2}}{2ie} \right| = \frac{e^{2}-1}{2e}
$$
and that is strictly less than $\frac{e^2+1}{2e}$.


Page specific menus in Wordpress

Question: I am trying to make a page specific menu in Wordpress, where each page has its own options... The link is http://dev.activenation.co.uk/leisure-centre/southampton-water-activities-centre/
As you go through the "Your Centre" pages, the grey menu changes. At the moment, we are using conditional if statements to load the specific menus, however, the client will need to add more leisure centres.
Was just wondering if there was a more time saving way of doing page specific menus, instead of coding conditional if statements?
Answer: If those Centres are subpages of "Your Centre" you could try to use this plugin which creates hierarchical pages / category / taxonomy lists.
Answer: Add a custom meta box to the 'page' content type that is a simple <SELECT> list of all of the custom WordPress menus. On save, pull the selected menu ID from the SELECT list and save it to the database. On the page template, check if the saved value exists and if it does, pull in the WordPress menu that has the saved ID.
This will allow an editor to create any number of menus, pick a specific one for each page, and share like menus between pages.
There are a lot of tutorials and code snippets around creating custom meta boxes, and displaying a simple select of the available menus. If you haven't done custom meta boxes before, this is a good intro project since it only has one form field and it's easy to validate the data.
Smashing Magazine has a great walk through on custom meta boxes: http://wp.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/
Comment: Thanks for the idea! Didn't think of this. Put a custom meta box on the pages, and made it look for a menu in the Wordpress menus section. Then I created all my menus in there. Thanks for your help! :)

Page specific menus in Wordpress


Drupal 7 rewrite is removing get parameters from query string

Question: I've recently upgraded a site to the latest release of Drupal 7. The site has a view that retrieves a url with query string parameters from the database and then uses the Drupal rewrite functionality to add a class to the link like so:  View
The issue is, since the upgrade the rewrite now removes the query string parameters. If I modify the view to display a simple link the parameters are there and it works fine. However, the rewrite applies styling to present a button rather than a simple link. I can't find any settings to resolve the issue so I suspect the upgrade overwrote a modification to the Drupal core made by the original developer of the site. Any idea how I can address this issue?
Answer: It turns out that there was a bug in the latest release that in /modules/contrib/link/link.module that was causing the query strings to be stripped from the URL in the token. I replaced the code in this file with the code from the pre-upgrade version and it began behaving as expected again. This, of course, is not a resolution to the issue, but at least the source of the problem has been identified. For more info, see the original bug report.
I later found that there is a patch for this issue in the dev version (7.x-1.x-dev) of this module. Download this module and replace it in your install and you should be all set.
Answer: oh ugh that is UGLY. I wish everyone would know DO NOT MODIFY core files!
Unless you have a backup you are pretty much dead in the water. Well you can recreate functionality but that's annoying if it was working. If you don't have a backup use this experience as a boot to get you backing up properly - take weekly database backups (or daily or monthly depending on site change rate) and a full database and code backup before upgrading. I would suggest the Backup/Migrate module to make that easy and mostly automated.
If you do have a backup do a diff between the version it was and the backup to find what files were changed and then get those changes out and into a module if possible.
Comment: I did have a backup and performed a diff but unfortunately there were almost 2800 files that had been modified.  A bit more research led me to the solution below.


How is the formula of Shannon Entropy derived?

Question: From this slide, it's said that the smallest possible number of bits per symbol is as the Shannon Entropy formula defined:

I've read this post, and still not quite understand how is this formula derived from the perspective of encoding with bits.
I'd like to get some tips like in this post, and please don't tell me that it's just because this is the only formula which satisfies the properties of a entropy function.
Thx in advance~
Comment: @zhangxaochen : That is precisely the first theorem of Shannon, it's a fundamental (simple though not trivial) result that is explained in every textbook of Information Theory, see eg. [Cover- Thomas](http://www.amazon.com/Elements-Information-Edition-Telecommunications-Processing/dp/0471241954). This is too broad for getting an answer here IMO
Comment: See http://math.stackexchange.com/questions/663351/what-does-the-logpx-mean-in-the-calculation-of-entropy.
Comment: @Martín-BlasPérezPinilla, I could agree to this formula qualitatively, but quantitatively, how to prove it's the smallest number of **bits**?
Answer: Suggest you read the proof that H is the only measure (up to a constant) that satisfies the axioms of information measure. It can be found here: "The Mathematical Theory of Communication" - Shannon & Weaver.
The proof of the theorem is easy to understand - only a couple of pages.
Answer: Log2 1/p is the number of bits needed to transmit symbols that occur with probability p.  For example, if it occurs 1 times in 8, we need 3 bits to encode all 8 possibilities. Now just take the average number of bits weighted by p for each symbol.
Answer: Here is a simple intuitive construction of Shannon's Entropy formula:
Understanding Shannon's Entropy...


Techniques of Integration w/ absolute value

Question: I cannot solve this integral.
$$
\int_{-3}^3 \frac{x}{1+|x|} ~dx
$$
I have tried rewriting it as:
$$
\int_{-3}^3 1 - \frac{1}{x+1}~dx,
$$
From which I obtain:
$$
x - \ln|x+1|\;\;\bigg\vert_{-3}^{\;3}
$$
My book (Stewart's Calculus 7e) has the answer as 0, and I can intuitively see this from a graph of the function, it being symmetric about $y = x$, but I cannot analytically solve this.
Comment: Since you have an absolute value you should split the integral as $\int_{-3}^0f+\int_0^3f$. Or you may notice that the integrand is an odd function, and since the interval $[-3,3]$ is symmetric about the origin you should get $0$.
Comment: Sometimes integrals are best evaluated with a graph, especially when absolute value is involved at times. Not all integrals need to evaluated with an antiderivative. In most cases with an absolute value in the integrand, you have to split up the integrand into two or more places where the function switches from negative to positive (so be careful with signs!)
Comment: I guess by solve you meant evaluate/compute!
Answer: Your rewriting is incorrect; when $-3\leq x\leq 0$, the original function takes the values
$$\frac{x}{1+|x|} = \frac{x}{1-x} \neq 1 - \frac{1}{x+1}$$
(your rewriting is only valid when $x\geq 0$)
To solve the problem, either notice that your function is odd:
$$f(-x) = \frac{-x}{1+|-x|} = - \frac{x}{1+|x|} = -f(x)$$
and conclude that the answer is $0$ because your interval is symmetric about the origin; or
divide the integral into two:
$$\int_{-3}^3\frac{x}{1+|x|}\,dx = \int_{-3}^0\frac{x}{1+|x|}\,dx + \int_{0}^3\frac{x}{1+|x|}\,dx.$$
In the first integral, you know $x$ is negative so $|x|=-x$; in the second, you have $|x|=x$. Now you can solve each part separately. The second integral can be solved with your decomposition:
$$\frac{x}{1+x} = \frac{-1+1+x}{1+x} = -\frac{1}{1+x} + 1$$
while the first one can be done similarly, with
$$\frac{x}{1-x} = -\frac{-x}{1-x} = -\left(\frac{-1+1-x}{1-x}\right) = \frac{1}{1-x} -1.$$
Answer: You have an odd function integrated over an interval symmetric about the origin. The answer is $0$.  This is, as you point out, intuitively reasonable from the geometry. A general analytic argument is given in a remark at the end.
If you really want to calculate, break up the region into two parts, where (i) $x$ is positive and (ii) where $x$ is negative. For $x$ positive, you are integrating $\frac{x}{1+x}$. For $x$ negative, you are integrating $\frac{x}{1-x}$, since for $x\le 0$ we have $|x|=-x$.  Finally,  calculate
$$\int_{3}^0 \frac{x}{1-x}\,dx\quad\text{and}\quad\int_0^3 \frac{x}{1+x}\,dx$$
and add. All that work for nothing!
Remarks: $1.$ In general, when absolute values are being integrated, breaking up into appropriate parts is the safe way to go.  Trying to handle both at the same time carries too high a probability of error.
$2.$ Let $f(x)$ be an odd function. We want to integrate from $-a$ to $a$, where $a$ is positive. We look at
$$\int_{-a}^0 f(x)\,dx.$$
Let $u=-x$. Then $du=-dx$, and $f(u)=-f(x)$. So our integral is
$$\int_{u=a}^0 (-1)(-f(u))\,du.$$
the two minus signs cancel. Changing the order of the limits, we get $-\int_0^a f(u)\,du$. so this is just the negative of the integral over the interval from $0$ to $a$. That gives us the desired cancellation.


Ordenando arrays com Bubble Sort

Question: Estou resolvendo uma questão do meu curso a qual eu preciso usar um algoritmo de ordenação de vetores com base no algoritmo Bubble Sort.
Fazendo um resumo prévio, a lógica consiste em passar por todos os valores do array, em pares, comparando um ao outro e verificando qual é maior. O número maior sempre irá para a direita, trocando com o valor menor, passando assim sempre o maior número para a extrema direita. Após passar por todos os números do vetor e ordenar a primeira vez, o laço de repetição se repete pela quantidade de números do array até ordenar todos os valores.
Eu escrevi esse código e ele está funcional:

let bubble = [82, 76, 6, 52, 45, 38, 24, 14, 54, 85, 143, 98, 65, 512, 96, 12, 4, 79];

function bubbleSort () {
    for (let i = 0; i < bubble.length; i++) {
        if (bubble[i] > bubble[i +1]) {
            let v1 = bubble[i]
            let v2 = bubble[i +1]
            bubble[i] = v2
            bubble[i +1] = v1
        }
    }
}

for (let j = 0; j < bubble.length ; j++) {
    bubbleSort();
}

console.log(bubble)

Saída do código:
[
   4,  6,  12,  14, 24, 38, 45,
  52, 54,  65,  76, 79, 82, 85,
  96, 98, 143, 512
]

Como ainda estou aprendendo, gostaria de saber como eu poderia refatorar o código para que eu não precisasse usar uma function para fazer a segunda repetição do laço. Tentei colocar for dentro de for mas ele acabou me retornando undefined quando imprimo a saída no console. Podem me dar dicas para que o código fique mais legível e simples?
Answer: A primeira coisa é colocar todo o algoritmo dentro da função. Se os 2 loops fazem parte do algoritmo, então ambos deveriam estar lá, você não deveria depender de um loop externo para que a função funcione corretamente.
Outro detalhe é que a função, da forma que foi feita, acessa o array bubble que foi criado fora da função. Ou seja, só funciona para aquele array. Seria melhor que ela recebesse o array como parâmetro, assim ela funciona para qualquer array:

function bubbleSort(array) {
    for (let i = 0; i < array.length; i++) {
        for (let j = i + 1; j < array.length; j++) {
            if (array[i] > array[j]) {
                let aux = array[i];
                array[i] = array[j];
                array[j] = aux;
            }
        }
    }
}

let numeros = [82, 76, 6, 52, 45, 38, 24, 14, 54, 85, 143, 98, 65, 512, 96, 12, 4, 79];
bubbleSort(numeros);
console.log(numeros);

// posso reaproveitar a função para ordenar outro array
let outroArray = [1, 5, 34, 2, 6, 7, 8, 12];
bubbleSort(outroArray);
console.log(outroArray);

Também fiz uma alteração nos loops. Não faz sentido tanto i quanto j começarem do zero (pois aí estarei comparando o elemento com ele mesmo). Outro detalhe é que, depois da primeira iteração, o primeiro elemento com certeza já será o menor de todos, então não tem porque compará-lo novamente nas iterações seguintes. Sendo assim, o loop interno sempre começa em i + 1 (em vez de sempre começar do zero).
Claro que isso não vai ser aquela otimização, já que bubble sort em si não é o algoritmo mais eficiente de todos, e para arrays pequenos a diferença será imperceptível. Mas de qualquer forma, fica mais rápido.
E vale notar que esta função modifica o array. Se quiser que ele não modifique o array original, faça como a outra resposta indicou.

Também coloquei ponto-e-vírgula no final das linhas. Pode parecer "frescura", e sei que o JavaScript "aceita" o código sem ponto e vírgula e "funciona", mas isso evita algumas situações bizarras que podem ocorrer se você não usá-los, como essa e essa (veja mais sobre isso aqui).
Answer: Se você quiser remover a função "intermediária" bubbleSort, basta "realocar" o laço for que está no corpo dela para dentro do for principal. Assim:

function bubbleSort(originalArray) {
  const bubble = [...originalArray];

  // Este é o laço que antes estava no escopo global:
  for (let j = 0; j < bubble.length ; j++) {

    // Este é o laço que antes estava dentro da função:
    for (let i = 0; i < bubble.length; i++) {
      if (bubble[i] > bubble[i +1]) {
        let v1 = bubble[i];
        let v2 = bubble[i +1];
        bubble[i] = v2;
        bubble[i +1] = v1;
      }
    }
  }

  return bubble;
}

console.log(bubbleSort([4, 2, 5, 3, 1]));

E funcionará como esperado. Note também que eu "extraí" todo o código para dentro de uma única função, coincidentemente chamada bubbleSort. Assim, poderemos chamar a mesma função diversas vezes passando diferentes arrays para serem classificados. Também fiz uma cópia do array passado como argumento para evitar mutações na lista original.
O problema do código acima é que ele sempre fará N^2 iterações, sendo N a quantidade de elementos do array a ser sorteado. Isso porque você não implementou nenhum meio de verificar se o array já foi devidamente classificado. Para ilustrar isso, vejamos o exemplo abaixo:

function bubbleSort(originalArray) {
  const bubble = [...originalArray];

  let counter = 0;

  for (let j = 0; j < bubble.length ; j++) {
    for (let i = 0; i < bubble.length; i++) {
      counter++;

      if (bubble[i] > bubble[i +1]) {
        let v1 = bubble[i];
        let v2 = bubble[i +1];
        bubble[i] = v2;
        bubble[i +1] = v1;
      }
    }
  }

  console.log(counter);
  return bubble;
}

bubbleSort([1, 2, 3, 4, 5]);
// Imprimirá 25 no console (25 iterações foram feitas).

Note que, mesmo que já devidamente sorteada, uma lista será varrida (desnecessariamente) 25 vezes, isto é, o quadrado do seu número de elementos.
Um simples booleano pode resolver esse problema. Usaremos ele para indicar, do "laço interno", quando uma mudança for realizada. Desse modo, a partir do "laço externo", poderemos verificar se uma "troca" foi feita em alguma das iterações do "laço interno". No caso disso não tiver acontecido, podemos assumir que o array já foi sorteado. Assim:

function bubbleSort(originalArray) {
  // Copiamos o array para evitar modificações no array original:
  const array = [...originalArray];

  for (let i = 0; i < array.length; i++) {
    // Booleano que usaremos para verificar se houve troca:
    let swapped = false;

    for (let j = 0; j < array.length; j++) {
      const current = array[j];
      const next = array[j + 1];

      if (current > next) {
        array[j + 1] = current;
        array[j] = next;

        // Marcamos `swapped` como `true` para indicar que houve troca.
        swapped = true;
      }
    }

    // Se não houve nenhuma troca nesta iteração, significa
    // que o array já está sorteado. Podemos, então, sair.
    if (!swapped) {
      break;
    }
  }

  return array;
}

console.log(bubbleSort([4, 2, 5, 3, 1]));

Note agora que, mesmo que um array já devidamente sorteado seja passado, ao invés de 25, somente ocorrerão 5 iterações (que é o melhor cenário). Podemos verificar isso adicionando o contador:

function bubbleSort(originalArray) {
  // Copiamos o array para evitar modificações no array original:
  const array = [...originalArray];

  let counter = 0;

  for (let i = 0; i < array.length; i++) {
    // Booleano que usaremos para verificar se houve troca:
    let swapped = false;

    for (let j = 0; j < array.length; j++) {
      counter++;

      const current = array[j];
      const next = array[j + 1];

      if (current > next) {
        array[j + 1] = current;
        array[j] = next;

        // Marcamos `swapped` como `true` para indicar que houve troca.
        swapped = true;
      }
    }

    // Se não houve nenhuma troca nesta iteração, significa
    // que o array já está sorteado. Podemos, então, sair.
    if (!swapped) {
      break;
    }
  }

  console.log(counter);
  return array;
}

bubbleSort([1, 2, 3, 4, 5]);
// Imprimirá 5 no console (5 iterações foram feitas — esse é o improvável melhor cenário).

Para o pior cenário, os N^2 ainda serão necessários, já que é uma característica intrínseca do algoritmo.
Algumas otimizações a mais podem ser feitas também. Mas, no geral, esse não é um algoritmo eficiente e existem alternativas mais performáticas. A outra resposta dá uma explicação um pouco mais detalhada sobre essa otimização.
Comment: Era exatamente isso que eu precisava, Luiz! Não estou ainda pensando em implementações melhores pois estou passando pelo caminho das pedras antes antes de chegar em recursos mais eficientes, seguindo a linha do meu curto. Me ajudou bastante, e a implementação com o boolean matou essa questão de passar diversas vezes pelos números mesmo demais de estarem sorteados. Ainda assim, percebi que não houve redução do tempo de execução do código (antes 0.05~, agora 0,05~), existe alguma explicação para isso?
Comment: Provavelmente o número de elementos é tão pequeno que faz pouca diferença. A adição do _boolean_ evita _algumas_ iterações adicionais, mas em quase nada ajuda para contornar a ineficiência intrínseca desse algoritmo (`O(N^2)` não é muito bom, no pior dos casos...). Ah, e como você é novo no site, não esqueça de verificar no [tour] a melhor forma de dizer obrigado. Bem-vindo. :-)
Comment: @DiegoAugustoF. Tem que ver também como vc está medindo (eu uso sites como o https://jsbench.me) - e também coloquei [uma resposta](https://pt.stackoverflow.com/a/478177/112052) com outra alternativa (mas não vai melhorar tanto assim, bubble sort é ineficiente por definição)
Answer: Acredito que a forma mais rápida é percorrendo até chegar no final dessa ordenação:
let bubble = [82, 76, 6, 52, 45, 38, 24, 14, 54, 85, 143, 98, 65, 512, 96, 12, 4, 79];

function bubbleSort(arr) {
         let t = arr.length;
        while (t) {
            for (let i in arr) {
                if (arr[ i ] > arr[i + 1]) {
                    let temp = arr[ i ];
                    arr[ i ] = arr[i + 1];
                    arr[i + 1] = temp
                }
            }
            t--;
        }
        return arr;
    }

    console.log(bubbleSort(bubble))

Mas se quiser melhorar, pode fazer isso:
let bubble = [82, 76, 6, 52, 45, 38, 24, 14, 54, 85, 143, 98, 65, 512, 96, 12, 4, 79];

function bubbleSort(arr) {
    return arr.sort((a, b) => {
        return (a < b+1) ? -1 : 1
 });
}
    console.log(bubbleSort(bubble))

Ordenando arrays com Bubble Sort


Function with multiple local minima

Question: I am trying to understand gradient descent algorithm by plotting the error vs value of parameters in the function. What would be an example of a simple function of the form y = f(x) with just just one input variable x and two parameters w1 and w2 such that its loss function has multiple minima? What i am trying to achieve is something similar to this :

How does one know if the function has multiple minima without plotting the graph ? What branch of mathematics deals with this topic ?
Comment: Also see [Global optimization](https://en.wikipedia.org/wiki/Global_optimization).
Comment: Slightly off-topic: What is the equation of this beautiful function? Could you please share it? Thanks...
Answer: Regarding example of functions with multiple local minima I would suggest visiting a website like the Virtual Library of Simulation Experiments: Test Functions and Datasets - Optimization Test Problems from Simon Fraser University. It contains many examples of functions with many local minima. A trivial two-factor example would be something like: $x \sin(w_1 x+w_2)$. In real-life terms most functions that might reflect some seasonality/periodicity will potentially have multiple local minima relating to that seasonal/periodic effect.
The most straightforward way to asses if a particular function has multiple local minima is to use calculus. Multiple local minima would relate to multiple instances of first derivatives being zero and second derivatives being positive. As Neil mentioned: "in two dimensions (like the plot he's drawn), the second derivative is a matrix, in which case a minimum corresponds to a positive definite second derivative matrix." Moving to multivariate functions will be reflected in dimensions of the function's derivatives. The object we use in that case is the Hessian matrix (which has mentioned we want to be at least positive semi-definite).
The branch of mathematics dealing with topic is called Mathematical Optimisation. Real-life examples of optimisation tasks are extensively involved in the field of Operational Research.
Comment: You might want to add that in two dimensions (like the plot he's drawn), the second derivative is a matrix, in which case a minimum corresponds to a *positive definite* second derivative matrix.
Answer: The functions that you are looking for are known as test functions or artificial landscapes.
Wikipedia has a very nice list of test functions for optimization. I recommend looking at the references from the link directly.
Comment: Updated link: https://en.wikipedia.org/wiki/Test_functions_for_optimization
Answer: If they are only a few and you can estimate a range where they will lay, you can try descent methods with different starting points that will converge to each of them.
This practice works some of the time, but as we increase the number of dimensions (or as we know less about the shape of the function), this simplistic approach will no longer be practical (see previous answers)

Function with multiple local minima


How to create box-shadow only on left and right with repeat box?

Question: I try to find solution how to use box-shadow to show shadow left and box on box. My problem shadow on bottom look darker then left and right.
If anyone has the solution already, please kindly help. Thank you.

    .box {
     margin:0;
     box-shadow: 0px 12px 15px 0 #7f7e7f, 0px 7px 2px -1px #7f7e7f;
     height: 150px;
     width: 50%;
     background: #cff;
    }

Answer: What you need to do is make use of two different box-shadows. One for the left side, and one for the right side. These two box-shadows should be separated by a  comma.
The first box-shadow should have a negative horizontal width, and the second box-shadow should have a positive horizontal width. This is the first value in the box-shadow shorthand.

.box {
  margin: 0;
  box-shadow: -10px 0px 0px 0 #7f7e7f, 10px 0px 0px 0 #7f7e7f;
  height: 150px;
  width: 50%;
  background: #cff;
}

Hope this helps! :)
Answer: Below is the code. Hope this is a great help :)

.box {
  margin: 0;
  box-shadow: -10px 0px 0px 0 rgba(0,0,0,0.2), 10px 0px 0px 0 rgba(0,0,0,0.2);
  height: 150px;
  width: 50%;
  background: #cff;
}

Comment: shadow is separate not like look one box
Comment: I have modified my css, then added blurry to the color of the shadow, I used rgba() so I can add opacity
Comment: rgba(0,0,0,0.2) - three zeros represents the color value for black and the last one 0.2 represents the opacity value of the color black
Answer: You can simply use the Box-Shadow generator , it's quite simple and fast to use
Example:

.box {
  margin: 0;
  box-shadow: -24px 11px 60px -22px rgba(0, 0, 0, 1), 24px 11px 60px -22px rgba(0, 0, 0, 1);
  height: 150px;
  width: 50%;
  background: yellow;
}


Problem 1.24, Introduction to representation theory, Etingof

Question: Let $k$ be a field and $n$ and $N$ be two nonnegative integers. Let $A = k[x_1, \ldots, x_n]$, and let $I \neq A$ be any ideal in $A$ containing all homogeneous polynomials of degree $\geq N$. Show that $A/I$ is an indecomposable representation of $A$.
Comment: We generally prefer that you at least share us your thoughts on the problem... Have you tried some small case, like the one you get when $N=1$ or $N=2$?
Comment: Well, $N = 1$ is trivial; in this case the representation is just the field $k$. Thinking about $N = 2$...
Comment: I can come up with a proof for $N = 2$ but it doesn't seem to be useful as I can't easily generalize it to $N > 2$. If $A_1 \oplus A_2 = A/I$, then either $A_1$ or $A_2$ must contain an element with a nonzero constant term. We assume it is not a constant otherwise this subrepresentation must obviously be the entirety of $A/I$. By multiplying this by each $x_i$ in turn we see that this subspace contains all $x_i$. Then the other subspace must be simply $k$, but then it cannot be invariant.
Comment: Well, then concentrate on the case $N=3$ which is at the frontiers of your knowledge!
Answer: Okay, I might have solved this finally. I think this may be a possible solution, but twice before this I thought I had a solution that subsequently turned out to be completely bogus.
If $A/I = A_1 \oplus A_2$, then either $A_1$ or $A_2$ must contain an element with a nonzero constant term. Without loss of generality, take this to be $A_1$, and let this element be $a$.  Furthermore, without loss of generality, take the constant term to be 1.
By multiplying each homogeneous polynomial of degree $N-1$ by $a$ (which kills off all the non-constant terms), we see that $A_1$, an invariant subspace, must in fact contain all homogeneous polynomials of degree $N-1$.
Then we successively multiply each homogeneous polynomial of degree $N-k$ by $a$, for $k = 2, 3, \ldots$. This kills off all the terms of degree at least $k$, and all the terms of degree $1, 2, \ldots k-1$ go to homogeneous polynomials of degree $N-k+1, \ldots, N-1$ which are in $A_1$, so we may subtract them off. This leave the contribution from the constant term, the original homogeneous polynomial. So we can successively show that all homogeneous polynomials of degree $N-k$ are in $A_1$, and conclude that $A_1 = A/I$.
Therefore $A/I$ is indecomposable.
Answer: I guess you had the right idea but I didn't get all the details of what you wrote. (especially, is a a polynomial of degree 1?)
That essential idea is that $A/I$ has a unit, which is a cyclic vector. Then, in full generality, a representation with a cyclic vector is indecomposable.
(I also discovered that great lesson by etingof and I'm try to do the exercices!!)
Comment: The representation $A \oplus A$ of $A$ has cyclic vector $(1,1)$ but is decomposable...
Comment: I mean the regular representation of $A\oplus A$
Comment: Oh, I didn't see your comments. First anwser: a cyclic vector is supposed to generate the whole representation so where is your direct sum of two non trivial subrepresentations (def. of decomposable)? Second: what is your reg. representation of $A\oplus A$? $A\oplus A$ (as a sum of two modules) is supposed to mean all couples $(a_1,a_2)$ and in that case $(1,1)$ is not cyclic. I guess that now you have to take away the downvote, mouahahaha
Comment: My first comment contains a typo which is clarified in my second comment. Regular representation means $A\oplus A$ acts on itself by multiplication. $(1,1)$ is a cyclic vector obviously. Subrepresentations include $A\oplus 0$ and $0\oplus A$. As for the downvote, you'll need to ask whoever did it.
Comment: It seems that you're right finally... I'll modify my answer later, i was actually thinking about something more than cyclicity, like a single element of the algebra acting repeatedly on the cyclic vector and generating the whole representation
Answer: Suppose $A/I=U\oplus V$ and write $\overline{1}=\overline{u}+\overline{w}$ with $\overline{u}\in U$, $\overline{v}\in V$. It is easy to see that $\overline u,\overline v$ are orthogonal idempotents. If we suppose $\overline{u}$ and $\overline{v}$ are non-zero, it follows that both $u$ and $v$ have non-zero constant term, since otherwise $\overline{u}^N=\overline{v}^N=0$, contradicting their idempotence.
Let $\lambda\in k^\times$ be such that $u+\lambda v$ has zero constant term. Then $$0=(\overline{u}+\lambda\overline{v})^N=\sum_{j=0}^N \binom{N}{j} \overline{u}^j(\lambda\overline{v})^{N-j}=\overline{u}^N+(\lambda\overline{v})^{N}=\overline{u}+\lambda^N\overline{v},$$
which is obviously contradictory.


No fitted ARIMA model

Question: I wanted to fit an ARIMA model to a daily database for three years but auto.arima couldn't find a model and showed the following error:
Unable to fit final model using maximum likelihood. AIC value approximated

Is it because ARIMA is not good for data with long seasonality?
Comment: I've used the auto.arima function, but this is not the classical way of fitting a model. It's a tool to help you fit the model, but you need to look at the AC/PACs/Residuals. Daily data might be difficult to fit with an ARIMA model, but I don't think the error message you got from auto.arima tells you anything.
Answer: Daily data often involves daily indicators , monthly indicators , weekly indicators , holiday effects along with level shifts/local time trends AND ARIMA structure. Oftentimes there are unusual values that need to be treated.
Comment: thank you. does it mean that I can not use auto.arima for daily data?
Comment: I wouldn't advise it as memory (ARIMA) is often insufficient to characterize the time series.
Comment: Dr Hyndman mentioned in this post http://robjhyndman.com/hyndsight/dailydata/#comments that we can use fourier series and use ARIMA to handle holidays in annual data. I followed the same approach and Im stil getting the same error for this line: fit <- auto.arima(y, xreg=cbind(z,holiday)),Any help is really appreciated. Thanks
Comment: There is often(always) lead effects i.e. days before the holiday and lag effects i.e days after the holiday that are important. Good software can automatically FIND this structure ...deficient software does not. Without having a good structire for important events it is difficult(impossible) to detect particular days of the month that be important AND/OR particular weeks of the month that might be important OR Fridays before a Monday Holiday OR Mondays after a FRiday hooliday ETC....
Comment: Do you mean that Auto.Arima has a hard time fitting a model due to lead and lags for holidays? Im not quite sure as looking at my data, holidays did not have a significant impact on the orders booked one day before and one day after them.
Comment: if that is so then we can put holiday effects aside and consider questions like is there a weekly effect or is there a monthly effect ?
Comment: Fourier models are a very particular deterministic effect and often lead to fitted values that don;t describe / explain the actual. Just examine the residuals from a Fourier Model and it may help decide to see whether or not randomness exists in the residuals (.....very important for tests of necessity and sufficiency ). If you want to continue this dialogue please contact me via my email address.
Comment: I already included weekly and annual seasonality. I used TBATS which gave me a good model. The predictions work fine but it does not give close predictions for weekend. I thought this might be a reason of Holidays that I did not include in my model so I decided to go for Fourier series as TBATS does not let using covariate. I thought as I included weekly and annually seasonality, it should have included different seasonality for weekend but it seems the predictions are very low from the actual values. Is it more helpful if I provide my data here?
Comment: I also wonder how we say forecasts are good. definitely we can not have a perfect model. should we look to see how off the forecasts are from the actual values and say ie. if the forecasts are 10% in average far from the actual data, then the model is a good one? is there any criteria for that?
Comment: You can post your data using dropbox https://www.dropbox.com/business/business-free-trial?_tk=sem_goog_b&_kw=dropbox|e&_net=g&_ad=35064061902|1t1&_camp=sem_google_b_dropbox_us-english&gclid=CKW_6uDG5sACFeRj7Aod3HAAjQ.  There is no hard and fast criteria JUST does your model/equation adequately describe the observed data (i.e. are the residuals free of structure ...)

No fitted ARIMA model


[CRX]: didn't allow my js file in the extension

Question: This is my application code:
The manifest.json file:
{
 "name": "YouTradeFx Debugger",
 "version": "1.0",
 "manifest_version": 2,
 "description": "This appliction allow YoutradeFX R&D team to debugging thier applications, by using few tools",
 "browser_action": {
   "default_popup": "app.html"
 }
}

The app.html file:

 <title>Source of the application</title>

   <button id="Http">Send Requests</button>
    <button id="Cookie">Add Lead Params</button>
    <button id="Crm">CRM Faliure</button>

   Please your username:
   <input type="text" id="names" name="user">

  <input type="submit" name="send" value="SEND">

The app.js file is:
$(document).ready(function(){

 var HoldUser = $("input#names").val();
 $.get("https://www.mywebsite.com/ChromeExt/crm_buffer.php?uid="+HoldUser,function(data){
   $("div#cons").html(data);
 });

});

But I got the error message "Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:"." all the time..!
Why is not working? I did something wrong?
Comment: The error message is quite obious: You're using inline code somewhere. Does app.js or crm_buffer.php contain any inline code? Eg `onclick="foo();"` or ``?
Comment: No, it just contains a string "hello world" that should be return...
Answer: You are loading HTML (I assume) from https://www.mywebsite.com/ChromeExt/crm_buffer.php?uid="+HoldUser and then inject it in your app.html page. When HTML is injected it is parsed and all mentioned resources (


Resultado query MySQL diferente localhost e produção

Question: Estou com um problema no qual a mesma query executada no servidor local e produção, retornam um resultado diferente. A versão de produção está vindo incompleta no campo AVALIACOES.
Verifiquei a versão do mysql do servidor e local e são diferentes.
Pq deve estar acontecendo este problema? Segue os dados para análise:

QUERY
SELECT A.*,
       L.nome AS localidade,
       CA.nome AS cargo,
        (
            SELECT GROUP_CONCAT( CONCAT( AT.id, '=', AT.telefone, ';', AT.observacao ) SEPARATOR '{{separador}}' )
            FROM tal_a_c_alunos_telefones AS AT
            WHERE AT.aluno_id = A.id
        ) AS telefones,
        (
            SELECT GROUP_CONCAT( T.nome SEPARATOR ', ' )
            FROM tal_a_c_turmas_alunos AS TA
            LEFT JOIN tal_a_c_turmas AS T
            ON TA.turma_id = T.id
            WHERE TA.aluno_id = A.id
        ) AS turmas,
        (
            SELECT GROUP_CONCAT( C.nome SEPARATOR ', ' )
            FROM tal_a_c_turmas_alunos AS TA
            LEFT JOIN tal_a_c_turmas AS T
            ON TA.turma_id = T.id
            LEFT JOIN tal_a_c_cursos_turmas AS CT
            ON T.id = CT.turma_id
            LEFT JOIN tal_a_c_cursos AS C
            ON CT.curso_id = C.id
            WHERE TA.aluno_id = A.id
        ) AS cursos,
        (
            SELECT GROUP_CONCAT( CONCAT( C1.nome, '{{td}}' , AV.nome, '{{td}}', AV.peso, '{{td}}', AA.nota ) SEPARATOR '{{tr}}' )
            FROM tal_a_c_alunos_avaliacoes AS AA
            LEFT JOIN tal_a_c_avaliacoes AS AV
            ON AA.avaliacao_id = AV.id
            LEFT JOIN tal_a_c_cursos AS C1
            ON AA.curso_id = C1.id
            WHERE AA.aluno_id = A.id
        ) AS avaliacoes,
        (
            SELECT COUNT(*)
            FROM tal_a_c_alunos_avaliacoes AS AA
            LEFT JOIN tal_a_c_avaliacoes AS AV
            ON AA.avaliacao_id = AV.id
            LEFT JOIN tal_a_c_cursos AS C2
            ON AA.curso_id = C2.id
            WHERE AA.aluno_id = A.id
        ) AS avaliacoes_realizadas,
        DATE_FORMAT( A.data_inicio, '%d/%m/%Y' ) AS data_inicio,
        DATE_FORMAT( A.data_conclusao, '%d/%m/%Y' )  AS data_conclusao
FROM tal_a_c_alunos AS A
LEFT JOIN tal_a_c_localidades AS L
    ON A.localidade_id = L.id
LEFT JOIN tal_a_c_cargos AS CA
    ON A.cargo_id = CA.id
ORDER BY A.nome

LOCALHOST

RESULTADO:
Sensibilização para EaD{{td}}O papel do aluno{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Chamada Virtual{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Lema do Grupo{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Quem são os meus colegas?{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Enquete{{td}}1{{td}}10{{tr}}TeleListas Site{{td}}Criando Domínios{{td}}1{{td}}6.75{{tr}}TeleListas Site{{td}}Composição Editorial{{td}}2{{td}}8{{tr}}TeleListas Site{{td}}Avaliação Final{{td}}1{{td}}8{{tr}}TeleListas Site{{td}}Por que uma empresa precisa ter um site?{{td}}2{{td}}10{{tr}}TeleListas Site{{td}}Por que as empresas não obtêm o sucesso esperado na internet?{{td}}2{{td}}10
* A parte em negrito está faltando no resultado da produção

PRODUÇÃO

RESULTADO:
Sensibilização para EaD{{td}}O papel do aluno{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Chamada Virtual{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Lema do Grupo{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Quem são os meus colegas?{{td}}1{{td}}10{{tr}}Sensibilização para EaD{{td}}Enquete{{td}}1{{td}}10{{tr}}TeleListas Site
Comment: Os dados podem estar diferentes. Por isto a Consulta retornou resultados diferentes?
Comment: Como você sabe que os dados estão iguais na base? Como você está obtendo estes dados pra comparação (formulário no aplicativo, select por linha de comando...)?
Comment: Os dados estão iguais. A única diferença é na versão do MYSQL. Acredito que esteja relacionado a algum bug do mysql ou configuração de buffer.
Comment: Eu importei os dados da produção para o localhost.
Os dados são solicitados pelo sistema por uma requisição em ajax.
Estou comparando através do sistema, console e phpmyadmin. E estão retornando o mesmo.
Comment: @RobertoPC Através do sistema, console e phpmyadmin, os dados são os mesmos. Ok. E quando não são? Através de qual método de comparação os dados não coincidem?
Comment: Então, as 3 maneiras estão retornando o problema.
No localhost está vindo completo o campo e na produção está incompleto.
O banco é o mesmo e a query tb. A única diferença ao meu ver é de versão, onde na produção está um pouco mais atualizado.
Comment: @RobertoPC Eu ia sugerir olhar o tamanho do conteúdo da coluna (select `LENGTH(AVALIACOES)` e `select CHAR_LENGTH(AVALIACOES)` mas não achei esta coluna na query. Ela é o resultado daquela subquery com `GROUP_CONCAT`? Engraçado, pelo conteúdo retornado, não parece.
Answer: Resolvi o problema adicionando a seguinte linha no início da query:
SET GLOBAL group_concat_max_len = 1024000;
Seguindo a orientação desse post: https://dba.stackexchange.com/questions/52441/selecting-multiple-columns-from-multiple-rows-in-one-column-subquery


Using the same variable as a fixed and random effect in Mixed Effect Models

Question: The experiment this data comes from an experiment where two people collaborate to put objects in a specific order. The Director has the target array on their screen, and the Matcher has a scrambled array on their screen that must be reorganized to match the Director's display. The Director is a confederate using a script. After a few rounds using the same objects in different orders, there is a critical round.
The measure of interest is the reaction time (RT) of the Matcher to look at a target object on a screen based on whether the object was referred to using a previously established label (Old Label) or a novel label (New Label) and whether the interaction partner was the same partner as before (Same Partner) or a new partner (Different Partner). Each participant experienced 8 critical rounds, such that there are 2 observations in each cell of the design per participant, with each critical round using a different target object. Thus, we have a 2 (Label) x 2 (Partner) within-subjects design. We predicted that RT would be slowest when the Same Partner used a New Label, but RT would not differ in the other three groups (i.e., an interaction effect).
This effect was borne out using ANOVA. However, I want to use a mixed effect model to capture both participant and item level variation in the same model. My current model in R is an intercepts only random model:
rm1 <- lmer(RT ~ Label*Partner + (1|Subject) + (1|Item))

However, I would like to include random slopes in the model that acknowledge the fact that participants may have had idiosyncratic differences to each cell in the design and that the RT to each item may also display idiosyncratic differences. Thus, I imagine this model  would look like:
rm2 <- lmer(RT~Label*Partner + (Label*Partner|Subject) + (Label*Partner|Item))

Yet, I'm not sure if it's appropriate to include an effect as both a fixed and random effect in my model. If I only include the Label and Partner variables as random effects then I am unable to extract coefficients from the model and thus I cannot determine significance.
Answer: Note that your model rm1 includes a factor that is used both a fixed and a random effect -- namely the intercept. So yes, it is OK to do what you propose. The only issue is that there are a whole lot more random effects to estimate. There is always a trade off between parsimony and fit, so look at the AIC and BIC statistics, among others, to make sure you're not getting too fancy. For example, you might consider at least not having the interactions in there as random effects.
Comment: the only caveat would be that the factors must vary within subjects (as they do in this example)


What is the proper abbreviation for the test statistic in Wilcoxon signed rank test?

Question: What is the APA conforming symbol for the test statistic from the Wilcoxon signed rank test?
Different statistics software outputs all kinds of letters from V to Z.
I thought it was W?
Comment: Refer to their style guide to see what they recommend, if anything.
Comment: I also thought $W$, but I'm not sure there is a 'right' answer. [Wikipedia](http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test) explains that it is sometimes called $T$, & (I just checked) my copy of Hollander & Wolfe (2e) uses $T^+$.
Answer: As a general thing (regarding your title), there's no "proper" abbreviation, as the plethora of symbols suggests.
In his 1945 paper, Wilcoxon doesn't seem to use any symbol for the signed rank statistic at all (he does at one point use $T$ for the rank-sum statistic). If he had, that would be the closest to 'proper'. Most commonly, W seems to be used, but it depends on what you read. T is also pretty common, but in any case many (most?) treatments use a different (but equivalent*) statistic to Wilcoxon's 1945 original.
* in the sense of leading to rejection of or failing to reject the same samples under the same conditions
As for the body of your post (referencing APA guidelines), short of reading the style guidelines themselves (an admittedly onerous task), one approach is to find a few papers discussing the signed rank test in a journal that follows the APA guidelines. If there is such an 'APA-conforming symbol', presumably they will all be the expected one, and if there isn't, you have at least one symbol that would seem to be acceptable.