Does this song use chromatic mediant in G major? and what other music theory concepts this song's verse utilize

Question: I'm currently learning basic music theory and along the way I review old songs on my playlist then analyze what key, chord progression and somehow discover the composer's way of creating music.
The specific song "214 by Rivermaya" is clearly written on G major with chord progression of I, vi, ii... in its intro.
What confuses me is the use of E and A major chords in the verse. I just recently explored the concept of "chromatic mediant". Based on its concept, E is the parallel key of G major's sub-median note (E minor). But the A major chord doesn't look like a chromatic mediant since it belongs to supertonic of both G major and G minor scale. What could be the explanation that describes the structure of the verse? Should I also look in the concept of modes or other music theory concepts to easily understand how songs are composed? Thanks!
Answer: Seems to me tha verse has actually gone into key E. There are A and Am, both of which are commonplace in key E, and using Bm instead of E7 is a not unusual way to get to IV, A. The Bm has B, D, F♯, so sounds somewhat like E9.
On the 2nd question - modes will and do appear in some songs, although nowhere near as common as the 'main' modes of Ionian and Aeolian, but being aware of where 'home' is - the tonic - will be the best clue as to whether a song's in a different mode.


Interface or port id to IP address in dpdk 20.11

Question: Are they any existing API's in dpdk (as of 20.11 LTS) to map IP addresses to interfaces (port-id's) or vice versa?
Comment: the answer for your query is updated based on the latest DPDK available. Please accept and/or upvote to close the questio.
Answer: As per the current available DPDK 21.05.0 release, there is no direct API that supports the mapping of IP address to port Number. This is because DPDK API does not implement IP stack.
if one needs to maintain a simple mapping of IP address to DPDK port, I heavily recommend using a simple array to do so.
uin8_t mapPortIp4[RTE_MAX_ETHPORTS][4] = {0};
uint8_t rte_ipv6_hdr mapPortIp6[RTE_MAX_ETHPORTS][16] = {0};

int updateIp4(uin8_t Ip4[4], uint16_t port)
{
  if (port >= rte_eth_dev_count_avail())
    return -1;

  mapPortIp4[port][0] = Ip4[0];
  mapPortIp4[port][1] = Ip4[1];
  mapPortIp4[port][2] = Ip4[2];
  mapPortIp4[port][3] = Ip4[3];

  return 0;
}

int updateIp6(uin8_t Ip6[16], uint16_t port)
{
  if (port >= rte_eth_dev_count_avail())
    return -1;

  mapPortIp6[port][0] = Ip6[0];
  mapPortIp6[port][1] = Ip6[1];
  mapPortIp6[port][2] = Ip6[2];
  mapPortIp6[port][3] = Ip6[3];
  mapPortIp6[port][4] = Ip6[4];
  mapPortIp6[port][5] = Ip6[5];
  mapPortIp6[port][6] = Ip6[6];
  mapPortIp6[port][7] = Ip6[7];
  mapPortIp6[port][8] = Ip6[8];
  mapPortIp6[port][9] = Ip6[9];
  mapPortIp6[port][10] = Ip6[10];
  mapPortIp6[port][11] = Ip6[11];
  mapPortIp6[port][12] = Ip6[12];
  mapPortIp6[port][13] = Ip6[13];
  mapPortIp6[port][14] = Ip6[14];
  mapPortIp6[port][15] = Ip6[15];

  return 0;
}

Comment: Thanks for your answer. I'll try to create a mapping along the lines of your suggested code. Sidenote: I suspect you meant `updateIp6` for the second function definition instead of `int updateIp4(uin8_t Ip6[16], uint16_t port)`
Comment: @Fractal updated with return value and name change, please check and accept to close the ticket.


How to Blacklist a Range of IPs in cPHulk Brute Force Attack Settings

Question: Does anyone know how to define a range of IPs to blacklist in the cPHulk Brute Force attack settings?
I am getting bombarded from IPS 103.26.193.* and 103.26.194.*
I Googled it and cannot find specific instructions or settings on IP Ranges
Step 1 - Entering a range with asterisk (*):

Step 2 - Updated the Blacklist (unsuccessfully):

Follow @rholmes answer below and use these settings to block Foreign Hackers:
22.214.171.124/8
10.0.0.0/8
18.104.22.168/8
220.127.116.11/8
188.8.131.52/8
188.8.131.52/8
188.8.131.52/8
126.96.36.199/8
184.108.40.206/8
18.104.22.168/8
220.127.116.11/8
220.127.116.11/8
18.104.22.168/8
126.96.36.199/8
18.104.22.168/8
126.96.36.199/8
184.108.40.206/8
18.104.22.168/8
126.96.36.199/8
188.8.131.52/8
184.108.40.206/8
126.96.36.199/8
22.214.171.124/8
188.8.131.52/8
22.214.171.124/8
220.127.116.11/8
18.104.22.168/8
184.108.40.206/8
18.104.22.168/8
220.127.116.11/8
22.214.171.124/8
22.214.171.124/8
188.8.131.52/8
220.127.116.11/8
18.104.22.168/8
126.96.36.199/8
18.104.22.168/8
126.96.36.199/8
188.8.131.52/8
18.104.22.168/8
22.214.171.124/8
18.104.22.168/8
220.127.116.11/8
188.8.131.52/8
184.108.40.206/8
188.8.131.52/8
220.127.116.11/8
188.8.131.52/8
22.214.171.124/8
126.96.36.199/8
184.108.40.206/8
126.96.36.199/8
188.8.131.52/8
126.96.36.199/8
184.108.40.206/8
220.127.116.11/8
18.104.22.168/8
184.108.40.206/8
126.96.36.199/8
184.108.40.206/8
188.8.131.52/8
220.127.116.11/8
220.127.116.11/8
220.127.116.11/8
184.108.40.206/8
22.214.171.124/8
220.127.116.11/8
22.214.171.124/8
220.127.116.11/8
184.108.40.206/8
184.108.40.206/8
184.108.40.206/8
188.8.131.52/8
188.8.131.52/8
22.214.171.124/8
126.96.36.199/8
18.104.22.168/8
18.104.22.168/8
188.8.131.52/8
220.127.116.11/8
184.108.40.206/8
18.104.22.168/8
126.96.36.199/8
188.8.131.52/8
188.8.131.52/8
126.96.36.199/8
188.8.131.52/8
184.108.40.206/8
18.104.22.168/8
126.96.36.199/8
184.108.40.206/8
188.8.131.52/8
188.8.131.52/8
126.96.36.199/8
188.8.131.52/8
126.96.36.199/8
22.214.171.124/8
184.108.40.206/8
18.104.22.168/8
22.214.171.124/8
22.214.171.124/8
184.108.40.206/8
220.127.116.11/8
126.96.36.199/8
22.214.171.124/8
188.8.131.52/8
18.104.22.168/8
184.108.40.206/8
184.108.40.206/8
18.104.22.168/8
184.108.40.206/8
188.8.131.52/8
22.214.171.124/8
18.104.22.168/8
18.104.22.168/8
188.8.131.52/8
126.96.36.199/8
188.8.131.52/8
188.8.131.52/8
220.127.116.11/8
126.96.36.199/8
22.214.171.124/8
184.108.40.206/8
18.104.22.168/8
220.127.116.11/8
184.108.40.206/8
188.8.131.52/8
220.127.116.11/8
22.214.171.124/8
184.108.40.206/8
184.108.40.206/8
18.104.22.168/8
126.96.36.199/8
126.96.36.199/8
22.214.171.124/8
188.8.131.52/8
188.8.131.52/8
126.96.36.199/8
126.96.36.199/8
188.8.131.52/8
22.214.171.124/8
22.214.171.124/8
220.127.116.11/8
188.8.131.52/8
18.104.22.168/8
126.96.36.199/8
184.108.40.206/8
184.108.40.206/8
220.127.116.11/8
18.104.22.168/8
188.8.131.52/8
126.96.36.199/8
188.8.131.52/8
22.214.171.124/8
22.214.171.124/8
220.127.116.11/8
184.108.40.206/8

To complete the loop on buttoning your server down, refer to my other question here --> Do cPHulk Brute Force Protection Settings Effect Hosts?
Comment: I just want to thank you, I got a new dedicated server and I wanted to kill them all before they started. I was getting maximum failed attempts by about 20 IPs per day in the only 1.5 days I have had cPanel running. So I thought, "why don't I just block ALL countries from accessing my cpanel, except my own IP"? So I googled and found your list. Should do the trick! THANK YOU! :)
Answer: In the interface for cPHulk, you can wild-card with the following IPv4 address ranges (in notation used by CIDR or Classless Inter-Domain Routing):
103.26.193.* should be specified in cPHulk as: 18.104.22.168/24
103.26.*.* should be specified in cPHulk as: 18.104.22.168/16
103.*.*.* should be specified in cPHulk as: 126.96.36.199/8

This can be done at the command line or via the WHM interface.
The notation for wild-carding the IP addresses derives from the fact that an IP address is often represented as a 32-bit unsigned integer.  For better human readability, we divide this into 4 8-bit bytes separated by dots (dot notation).
In the wild-card notation, the number following the slash indicates how many of the higher-order bits should be considered significant.  The examples above show, in order, cases where the first 24 bits (three bytes), 16 bits (2 bytes), and 8 bits (1 byte) are considered significant.
Similar wild-carding / address block notation is specified for IPv6 as well.
If cPHulk is coded correctly, we should even be able to split one of the bytes at an arbitrary bit boundary (but I haven't tested this).  The notation should support it.
For more information on the details, one can start with some of the following links:
Wikipedia: Classless Inter-Domain Routing
IPv4 Classes, Subnets, Netmasks, CIDR and NAT
Wikipedia: IP Address
Comment: This solution will work in your situation.  Hope that helps!
Comment: Hmm… It appears to work for me… Which version of WHM are you using, and how many are you trying to block?  I typically use the xxx.xxx.0.0/16 style (to avoid over-blocking) but I've taken to attempting larger ranges.  How is it that you're determining it doesn't work -- you still get failure attempts from the blocked IPs? Updated answer for clarity...
Comment: You should enter "18.104.22.168/24" instead.  That should wild-card the last digit of the IP.

To wildcard the last two, "188.8.131.52/16".
Comment: I just edited the answer to provide additional background without too much detail, I hope...
Comment: Hey @rholmes ... just had to take a moment to come back here and thank you so very much for helping me with these settings. I have gone from roughly 50 server attacks an hour (from mainly Pac Rim Countries) to ZERO / NOTHING / ZIP / NADA / ZILCH at all. It so so refreshing to know that my server is just a bit more secured. Again, thanks !
Comment: I'm really glad it helped, @H. Ferrence!  I'm curious, I've been blacklisting at the "220.127.116.11/16" form by default (since it's easier to click) and I don't want to blacklist my own IP (I use a very restricted form for US addresses, since I want to be able to admin at internet cafes, work, hotel, random ISP).  I find I regularly get a spate of attacks from different countries, but I know that IP address ranges are not particularly deterministic (e.g., 138.x.x.x may have locations in both US and Thailand…).  What's the default you're using now to reduce the attacks?
Comment: What I have done is white-listed my IP's -- work office and home office. Those are really the only 2 I connect from. As per my hosts, I require my clients to submit their IP address to me and they understand they can only FTP into the server from that address. Then what I have done, since you helped me out with the wild card-ing technique, is I monitored the hack attempts to my server. When I saw them come in via the cPhulkd reports, I simply blocked the entire IP range.
Comment: That's the way I have used it and it works perfectly for me and the handful of clients I have that require FTP access to my server.
Comment: Take a look at my related S/F question where by I really shut down an attempt relatively quickly -- maybe that will help you out in some fashion. (http://serverfault.com/questions/570416/do-cphulk-brute-force-protection-settings-effect-hosts)
Comment: Hey thanks for the info.  Left a question on the other site.  Was wondering if you're using the wildcards or just the settings mentioned in your previous post.
Comment: Thanks @rholmes...see my amended OQ where I posted screen shots. Interface is cPanel/WHM itself.
Comment: But it doesn't work, that's the reason for my posting the question.
Comment: WHM 11.42.0 (build 8). The reason I don't believe it works is that when I enter an IP in the box shown above in my OQ and click Save button, the IP shows. When I use wild cards the IP does not show. And the entry in not in the blacklist table in cphulkd in the mysql db on the server
Comment: So, are you saying that you enter 184.108.40.206/16 in the box and after saving it shows as 103.26.nnn.nnn? If the text is changing out from under you I'd suspect perhaps a browser issue.  WHM 11 seems like it's new enough.  I've used this method for a while and don't have trouble - I'm kinda stumped...
Comment: As shown in the screen shot above, I enter "103.26.193.*" in the Blocked IP's textarea box. Then I click Save button. Then nothing reappears in the Blocked IP's textarea box based on what I entered (ie, the use of the wildcard) and when I check the MySQL table there is no reference to the enter whatsoever.
Comment: Thanks @rholmes. I'll give it a try later today and report back and accept your answer if it works. Greatly appreciated. (I think I get it now)
Comment: That worked @rholmes. It retained the entry based on your answer's examples. So what does "0/24", "0/16", and "0/8" represent? I was trying to use the asterisk as the wild card.
Comment: I really want to thank you @rholmes for helping me with this. I am significantly reducing hack attempts as a result of your assistance with the proper way to enter _wild card_ IP Ranges.
Comment: Glad it helped! I use it all the tim now...


Why am i facing this and what is workflow

Question: Could anyone please help in understanding the StackOverFlowError at runtime in below code.
I am not able to understand workflow.
One of the interview Question:)
public class Interview {

    Interview i1 = new Interview();
    Interview(){
        System.out.println("Hello");

    }

    public static void main(String[] args){

        Interview i = new Interview();

    }

}

Comment: What does the word "workflow" mean to you?
Answer: Your constructor is initializing itself. This is what your constructor looks like to the JVM:
Interview i1;
Interview(){
    super();
    i1 = new Interview(); // this line calls the constructor
    System.out.println("Hello");
}

Answer: Your Interview i1 = new Interview(); says that each Interview has its own Interview object that belongs to it, and so once you call new Interview() in main, the system starts trying to create a new Interview for that one, and a new Interview for that one...
It never even makes it to the (explicit) constructor, because the system goes off on a never-ending chain of new Interviews first. You should almost certainly remove the i1 field from the Interview class.
Answer: You're creating a new Interview every time you instantiate an Interview. This leads to a never-ending cycle of constructor calls and instantiations, which eventually run out your stack space (because the function calls take stack space).
Note that if you had infinite stack space available to you, you would eventually fail from all the Interview objects being allocated on the heap.
Answer: Because once you initialize that first Interview() in main() it creates and initializes a second Interview, which creates and initializes another and so on.
Answer: All initialization you do at the fields would become the part of the parameter-less constructor(in your case).
So,your code would become
public class Interview
{

    Interview i1;
    Interview()
    {
        super();//by default calls the constructor of Object
        i1 = new Interview();//initialization becomes part of constructor
        System.out.println("Hello");
    }

}

Now this would recursively instatiate Interview causing exception


How to use Eigen::Ref with pybind11?

Question: I'm using pybind to wrap C++ code.
Given the following function, which is originally part of a library and should not be modified:
void manipulate(Eigen::MatrixXd& data) {
    data = data*2;
}

Using pybind, I can wrap it as:
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <Eigen/LU>
namespace py = pybind11;

void wrap1(Eigen::Ref<Eigen::MatrixXd> data){
    Eigen::MatrixXd mData(data);
    manipulate(mData);
    data = mData;
}

PYBIND11_PLUGIN(cod) {
    pybind11::module m("cod", "auto-compiled c++ extension");
    m.def("wrap1", &wrap1);
    return m.ptr();
}

But this creates an unnecessary copy mData.
This fails to modify the data:
void wrap2(Eigen::MatrixXd& data){
    manipulate(data);
}

And this one fails fails to compile:
void wrap3(Eigen::Ref<Eigen::MatrixXd> data){
    manipulate(data);
}

How can I avoid creating a copy of data likewise wrap2, wrap3 or an equivalent of std::swap?
Comment: `ilcavio`, did you manage to solve this in a good way? :)
Answer:
This fails to modify the data:
void wrap2(Eigen::MatrixXd& data){

Yes, this won't modify the original numpy array because pybind must first copy it into a temporary Eigen matrix to call wrap2. From the pybind Eigen docs:

One major limitation of the above is that every data conversion implicitly involves a copy, which can be both expensive (for large matrices) and disallows binding functions that change their (Matrix) arguments. Pybind11 allows you to work around this by using Eigen's Eigen::Ref class...

Therefore, we have to use Eigen::Ref.

And this one fails fails to compile:
void wrap3(Eigen::Ref<Eigen::MatrixXd> data){
    manipulate(data);
}

The solution is to define a function that accepts an Eigen::Ref:
void manipulate(Eigen::Ref<Eigen::MatrixXd> data) {
    data = data*2;
}

Another option is to make manipulate a function template. See Eigen's documentation on Writing Functions Taking Eigen Types as Parameters.
Comment: you can make a lambda function that wraps  manipulate  to take `Eigen::Ref`
Comment: The problem is that `manipulate` is part of the library that I can't modify. Thanks for the answer

How to use Eigen::Ref with pybind11?


How do we define the value of a variable expression?

Question: The essence of this question is about how we define expressions like
$x^2+2x+1$ and say, 'when $x=2$, $x^2+2x+1=9$, treating $x$ like another name for $'2'$.
When we define the value of an expression, we have lots of symbols/names for a given object, let me use numbers here for simplicity, the number $2$ has the name $1+1$ and the name $2^1$ and the name $3-1$,or the name $-(-2)$, when we solve equations and assign values we often write expressions like $x=3$ for assignment and hence can conclude that: $x^2=9$.
The question is whether we can see these as being
'replace $x$ with a name for a number and you get this value:
or instead of having a value based on a hypothetical, we use $x$ as another name for the number, so unambiguously the expression has this value in the exact same way $2+2$ has a value, as '2' specifically refers to the number, in the same way $x$ would do so.
Does the 'value' of the expression mean the hypothetical value we get when we symbolically replace each variable with an explicit referent for the number (like '$2$' or '$2+2$') or the value under assignment where $x$ can remain and the expression keep its value as '$x$' becomes another name for it's value so $x+x$ is the same as '$2+2$ as $x$ is a specific name for $2$ without any 'hypothetical' idea.
Comment: Not sure what you are asking.  $x=3$ might be a perfectly good way of referring to $3$ locally...that is, within a very specific context, but outside that context it wouldn't work.  As to "why" you might stick with a variable name...well, again, context matters. Sometimes it could be as simple as not wanting to write out a lengthy number.  Perhaps an example of a particular instance that you are interested in would clarify your question.
Comment: $x=3$ can be a way to assign to variables x a value (for example in the context of programming); not so for $x^2=9$.
Comment: Regarding [assigning values to variables](https://math.stackexchange.com/questions/2339624/connection-between-interpretation-variable-assignment-and-truth-valuation)
Comment: See also [your previous post](https://math.stackexchange.com/questions/4521898/giving-a-formula-a-truth-value)
Comment: Good question, but you'll only get sensible answers in a very precise context. If you define what logic you are using, what are variables, etc., the answer will come from the definitions. Usually we do maths with a vague/sloppy notion of what a variable is, but here we must be precise. You could look at various _formal logical systems_, _proof assistants_ (e.g. Coq), at programming languages especially the concept of _referential transparency_, etc. E.g. a large part of _lambda calculus_ (https://en.wikipedia.org/wiki/Lambda_calculus) is just about dealing with variables.
Comment: @MauroALLEGRANZA we cannot 'assign' $x^2=9$, we can say when $x^2=9$ or if $x^2=9$ and or we can say $x=3$ implies $x^2=9$, which is similar to my question, we sort of can 'assign' a value of $'9'$ to $x$ but 'assign' in the general sense is a value to a variable so we 'assign' the value to the single term $x$, so $x=3$ and hence $x^2=9$, is this what you mean?
Comment: @lulu, so to write $x^2=9$ as $x=3$ would mean the (locally) we wish '$x$' to denote '$3$''
Comment: Hard to guess what you mean, as there is no context.  On its face, $x^2=9$ would mean that $x\in \{\pm 3\}$ but other interpretations are possible.     If you were working $\pmod {35}$ the solutions would be $x\in \{3,17,18,32\}$
 Regardless of all that, I'd have said that $x^2=9$ was the declaration of a variable name, and whatever follows would be the logically forced conclusions of that declaration.
Comment: @lulu $x^2=9$ is the declaration of x or are you treating $x^2$ as it's own symbol? Sorry, I'm a bit confused when you say $ x^2=9$ is a declaration.
Comment: The declaration would be "$x$ represents an element of the domain under discussion with the property that $x^2=9$".  It would be understood that the domain was such that $x^2$ made sense, though the declaration would not be taken to indicate that there actually was such an $x$.  One could, for instance, speak of a rational $x$ such that $x^2=2$ in the course of demonstrating that no such $x$ existed.
Answer: I will seperate my answer into two diffrent perspectives:
1.Computer Science
2.Mathimatics
Computer Science

$\text{Whenever we say that $x=2$ we mean that the variable $x$ is equal to a logic value.}$
And this logic value is equal to 2.Genarly speaking when we use"$x$" its when we are  representing a parameter or mathematical/logical value.So $x+x=2+2$ $\text{if only if }$ $x=2.$

Mathimatics

$\text{When we say that $x^2=9$ with $x\epsilon [0,100]$ for instance it means that $x$  represents an element of the domain}\\
\text{with the property that $x^2=9$ as it was mentioned in the comments.}$
$\text{So we don't assign values in maths but we searching all the possible}$
$\text{values of the variable that satisfies our conditions.This conditions could be like:}$ $f(x)=x^4+4x+100$ $\text{with a domain }$ $x\epsilon R$ $\text{ or }$ $x\epsilon[1,100]$$
$$\text{In both cases of the domain the varible x works as a summary of the elements of the domain of the fuction.}$
$\text{So when we are saying $x=2$,x it's just one of the many values that $x$ can take.So i guess we can say that it's an temporary name for $x$ }$
Answer: These kinds of questions are all settled in the formal semantics of the language in question, or model theory. In particular, the interpretation function which is part of a model describes how each constituent in the syntactic structure of the expression in question is assigned a meaning or interpretation. As you will soon see, it requires an amazing amount of precision to unambiguously specify what things mean so questions like yours can be clarified.
Let's do a little example. Let's interpret the expression $\tt x+2$ which I'll write in typewriter font to make it clear that it is in the object language, or the formal language under interpretation rather than the metalanguage in which we describe the semantics of the object language.
Our model will be the standard interpretation of the natural numbers $\mathbb{N}$. Let the interpretation function be $I$. The interpretation function will contain at least the following mappings to complete the interpretation of our expression. So the numeral $\tt 2$ is mapped to the number $2$, the variable $\tt x$ is mapped to the number $4$, and the function symbol $\tt +$ is bound to the function +.
$\tt 2$ $\rightarrow$ $2$
$\tt x$ $\rightarrow$ $4$
$\tt +$ $\rightarrow$ +
So
$ I(\tt x+2) = $
$I(\tt x)$ + $I(\tt 2) =$
$4$ + $2$ $ =$
$6$
So as you can see, in the standard semantics of first-order logic and the standard interpretation of natural numbers, each variable is assigned an number in the domain by the interpretation function. Other interpretations and other functions could assign other meanings to the constant variables in the object language. Specifically, a Herbrand interpretation maps each expression to itself.
But I haven't seen your specific example of number referents like '2+2' used in first-order logic, but I can't think of anything specifically blocking it. I have, however, seen it in the context of programming languages. So, specifically, in languages like Lisp I've seen plenty of things like
(setq x '(+ 2 2))

which means to assign the unevaluated, quoted expression (+ 2 2) to the variable x.
The formal semantics looks something like section 7.2.3 of the R5RS definition of Scheme.
Comment: Is the interpretation mapping described in terms of arrows like that, or did you do that for my understanding, because 2->2 confused me a little, how would we know the meaning of '2' to map it?
Comment: I think in the case of $2+2$ it has a meaning under a particular interpretation you are working in, but we can consider $x=2+2$ means that $x->4$ as $2+2$ is just a number I think 'names' exist under a particular interpretation as you say.
Comment: @user37577: The arrows are for clarity to show that part of the interpretation function. The interpretation function, being a function, has to provide a unique value for '2'.


Ideal of Ring $R$ where $R$ is finite or countably infinite.

Question: Let $R$ be a ring with a proper ideal $I$ such that $|R|$ is finite or infinite. If $R$ is finitely generated, then there exists ideal $J$ s.t. $$ R = I\times J $$
This is right ? If not, please give me an example. Thank you in advance.
Comment: Since "such that $|R|$ is either finite or infinite" is not a very useful condition, I suspect you accidentally left something out, possibly something you mentioned in your title... do you mean "finite or countably infinite"? And, since rings with unity are finitely generated over themselves, are we to assume that this question is about rings not necessarily having identity? Or did you intend $I$ to be finitely generated?
Comment: What does "$R$ is finitely generated" mean? Usually this is a condition on modules or algebras.
Comment: If $R$ is finite or countably infinite and $R$ is finitely generated, for example ${\bf Z}\times {\bf Z}_p$, then is it possible that $I$ is not finitely generated ?
Comment: Here I mean that $R$ is abelian group under addition which is finitely generated.
Answer: Try thinking about this with $R = \mathbb{Z}$ and $I = (2)$. What would you take for $J$?
As requested, another counter-example is $\mathbb{C}[x]$. Let $I = (f(x))$ and $J=(g(x))$ be any ideals, then $I \cap J \neq 0$ since it contains $f(x)g(x)$.
Comment: Are you asking for a different counter-example? I would like to understand the purpose.
Comment: You are right. If we do not consider the case where $I$ is an ideal of ${\bf Z}\subset R$, what happen ?
Comment: Yes. I mean that I want different counterexample.


conversão de numeros indo-arabicos para numeros romanos java

Question: Boa tarde, Estou com uma certa dificuldade na programação de um conversor para numeros romanos, consegui separar as casas em milhar, centena, dezena e unidade da seguinte forma
<code> if(numericos==1000){

      while(numericos<=milhar){
      milhar = 1;

      }
     v[0]=milhar;
  }

  if(numericos>100){

      while(centenas<=numericos){
      centenas = centenas + 100;

      }
  centenas= centenas/100-1;
  numericos= numericos%100;
  v[1]=centenas;
  }

  if(numericos>10){

      while(dezenas<=numericos){
      dezenas = dezenas + 10;
      numericos=numericos%10;
      }
     dezenas = dezenas/10-1;
     v[2]=dezenas;
  }
  if(numericos>1){

      while(unidades<=numericos){
      unidades = unidades + 1;
      }
       unidades = unidades - 1;
       v[3]=unidades;
  }
</code>
mas nao consigo pensar em uma logica de conversão sem meter trocentos ifs no codigo
alguem pode me ajudar por favor?
Comment: [Aqui](https://stackoverflow.com/q/12967896) tem vários algoritmos diferentes :-)
Answer: Eu costumo usar muito essas continhas para separar as unidades, dezenas, centenas, etc.
<code>    int inteiro = 1239;
    int unidade = inteiro % 1000 % 100 % 10;
    int dezena = inteiro % 1000 % 100 / 10;
    int centena = inteiro % 1000 / 100;
    int milhar = inteiro / 1000;

    System.out.println(unidade);
    System.out.println(dezena);
    System.out.println(centena);
    System.out.println(milhar);

    //saída:
    //9
    //3
    //2
    //1
</code>


Predicting running times for track meet places

Question: Good morning all,
I'm a track/running coach in Texas. That's my gentle way of saying that I don't have a statistical background, but I'm trying to learn what I can. Forgive me if I don't use the lexicon correctly.
I have been collecting the finishing times of the top six places at a particular annual meet in 102 running events (51 each for boys and girls, considering there are multiple age groups). I have aggregated the results from the past 17 years, for a total of 10,404 entries. This is available in a Google Fusion Table here, in case anyone is interested.
My objective is to try to predict the finishing time of each of the top six places at next year's meet (2016), which means I'll be using 17 entries per prediction. This means I'll make around 555 predictions; I'm not going to make predictions for 57 other places due to gaps in the data. Additionally, I'd like to come up with a range above and below this prediction that will add reasonable certainty. Originally, I called this a "confidence interval" (I used 95%) but after further reading, "prediction interval" appears to be more correct. Then again, I get confused, because this isn't a random sampling of information.
I originally used a spreadsheet formula to derive my predictions and range, but this has sprawled out of control and I've lost track of my own thought process (reader beware: the formula for each of those cells is a mammoth, ugly beast). Although there is a correlation here (times have improved gradually over the years in almost every event, due to increased participation) it's obviously not linear, since it must even out before it reaches zero.
My questions are thus:

Is my objective feasible?
If so, what particular model should I be using to derive these predictions?
What would best facilitate this? In other words, should I keep working with a spreadsheet formula, or would this work best by using a database program like PSPP? Or perhaps I should use R? I'd have a bit of learning to do if either of those last two were necessary.
Is this a case where there should be a "prediction interval" rather than a "confidence interval"? I'd like to be able to test this, after the meet is over, to see if the model worked. Since we're talking about hundredths of a second in some cases, there has to be some kind of range to work with.

Thanks so much for your help and patience.
EDIT: As one commenter has noted, the data also includes the number of participants in each event.
Also, it has been a couple of years since I set up my initial equation, but for those of you who don't want to sort through that ugly spreadsheet formula, I believe I used this:
$$
f(y)~=~\overbrace{\underbrace{m~\cdot~\ln(x)~+~a}_\text{Time Prediction}~\mp~\underbrace{\frac{{t_{\alpha,v}\cdot SE_y}}{\sqrt{{n}}}}_{\Delta y}}^\text{Lower and Upper Confidence Limits}
$$
Again, amateur here, so forgive me if that's gibberish.
Comment: Important detail: you've recorded not only the top six finish times but also the total number of participants in each event, which is very useful information.
Answer: I upvoted you because I like this as a whole. I do wish you had more data to really demonstrate the difference in time crossing the finish line by age groups and gender under different circumstances, like the temperature of the air that day and maybe a few others. To predict the outcome of an event is difficult, but with more data, you can predict anything to a relatively high degree of accuracy. What I have done was to get the "Mean", and "Standard Deviation" and run a simulation on a possible finishing time.
<code>=NORMINV(RAND(),Mean,StandardDeviation)
</code>
Separate all the age groups and genders and calculate the Mean and Standard Deviation and drop the values into the code above, what this does is draw a random variate "RAND()" from Normal Distribution with a Mean and Standard Deviation you select.

Here is a plot of the data you provided only for the 200M Dash


Realistic jazzy sound with VST

Question: I've been quite impressed with the orchestral sound of Nina Simone's "I put a spell on you". The part which interested me can be heard at first 17 seconds. So is it possible to simulate such warm and sensual sound like I described with VST? What instruments combination is used to record this?
And how can I achieve at least a similar sound with DAW? I'm sorry for newbie questions :)
Answer: You can get close.   I'd be interested to see what you think of this.  I'm sure it could be done better, but the frightening thing is how quick and easy it was to throw together this score in Sibelius and play it (with very little tweaking) using NotePerformer - a definitely budget-priced sound set.  HERE'S the sound file.
Comment: Thanks. This is exactly what I looked for. I'll work on it :)

Realistic jazzy sound with VST


Roll two dice - probability distribution function of one even and one odd

Question: Question
Roll two six-sided fair dice.
(a) What is the probability that you roll exactly one even and one odd value?
(b) Suppose we roll the dice $n$ times. Let $X=$ the total number of rolls with one odd and one even value. What is the probability distribution function of $X$?
(c) Suppose you win one dollar when you roll one even and one odd value. You also lose one dollar when you roll two odds or two evens. Let $Y=$ the total gain for $n$ rolls. What is $E[Y]$?
I am a little stuck on parts (b) and (c), but hopefully my work isn't too far off!
My Attempt
(a) P(first odd and second even) + P(first even and second odd) = $\frac{3}{6}*\frac{3}{6} + \frac{3}{6}*\frac{3}{6} = \frac{1}{2}$
(b) I'm not positive on the random variable $X$. I have assumed it as $X=0$ where there are no evens. $X=1$ when there is one odd and one even, $X=2$ when there are two evens.
The probability distribution is as follows: $P(X=0)=\frac{1}{4}$, $P(X=1)=\frac{1}{2}$, $P(X=2)=\frac{1}{4}$.
(c) $E[Y] = \frac{1}{4}*(-1) + \frac{1}{2}*(1) + \frac{1}{4}*(-1)=0$. So the total gain for $n$ rolls is zero dollars.
Answer: (a) Okay.
(b) You roll the pair of dice $n$ times.   That is two dice on each trial.   A success on a trial is an odd and an even, occurring with the probability you calculated for $(a)$.
So, for some number $n$, you have $n$ Bernoulli trials with success rate $1/2$.   $X$ is the count of successes in these $n$ trials.
(c) As above.   Express $Y$ in terms of $X$.   Find $\mathsf E(X)$.   Then find $\mathsf E(Y)$ from that.
Tip: $Y$ is ...

 the count of successes minus the count of failures.


What can cause SQL Server Full Text Indexing automatic change tracking to stop working?

Question: On a SQL Server 2008 server, we have a full text catalog in a database. The catalog is set to "track changes: automatic".
What can cause this to not work sporadically, so the index is not updated?
Answer: Could this be it?
http://msdn.microsoft.com/en-us/library/ms188359.aspx
"SET CHANGE_TRACKING {MANUAL | AUTO | OFF}
Specifies whether changes (updates, deletes, or inserts) made to table columns that are covered by the full-text index will be propagated by SQL Server to the full-text index. Data changes through WRITETEXT and UPDATETEXT are not reflected in the full-text index, and are not picked up with change tracking."


Is the rules event "Before saving a user account" applied every time a user edits their account?

Question: I would like to apply a rule that allows existing users whose email addresses come from a certain domain to continue using their existing accounts, but to prevent the creation of future accounts from these domains.
I have configured my rule to react on the After saving a new user account event, but I'm unsure as to whether to have it react also on Before saving a user account.
Does saving here refer to only to account creation, or also to account updates such as a password change?
Answer: Before saving a user account will react before you make a change in the user account.
And After saving a new user account will react After you create the user account.
But if you have the 2 events once you create a new user account you will trigger first the Before saving a user account event and after the After saving a new user account event.
If you go to create or update a user account always you need to call the user_save() function. The difference is in the first param. See this question with an example:
Create a user programmatically and give they a role
Comment: Are you familiar with the [this](http://drupal.stackexchange.com/questions/137500/how-to-troubleshoot-rules-when-a-required-variable-for-an-event-is-not-provided/201548#201548)? Reason why I ask: the kind of questions like this one here, are not obvious to answer ... My recommendation would be "***time to turn on Rules debugging ... in your own site ... to find the real answer by asking the rules module to tell you what it's doing ...***"
Comment: @Pierre.Vriens the number 28275 is my user number, when you click in the share link in the question you will see your number at the end, you can use this link yo have access to the Announcer, Booster and Publicist badges
Comment: Aha, now that is interesting! Never knew about that, and even never understood those bizarre badges ... Merci for teaching me about it ... PS: wanna try [this link](http://drupal.stackexchange.com/q/221032/39516) ???
Comment: @Pierre.Vriens I agree with you
Comment: So for the _Before saving a user account rule_ to apply, there must be an existing using account? Does it also apply to newly created accounts?
Comment: @Tadhg Yes apply to the newly accounts because when you go to create and update a user account always you need to use the user_save(), see my edit for more information.
Comment: Hey Adrian, I noticed the URL you include ends with "q/6976/28275": the "q/6976"-part of it is clearly the question ID. But what's the purpose of that "28275" in it? As far as I can see, if you'd change it to just "q/6976" you end up at the very same spot in the linked question. Am I missing something?


Bijection between $\mathbb{Z}/ m\mathbb{Z}$ and the set of elements coprime to all divisors of $m$

Question: Let $m \in \mathbb{N}$. I want to show that there's a bijection between the sets
$$A = \{(q,a) \mid q\in \mathbb{N} \text{ divides }m, \text{ and }a\in \mathbb{Z}/q\mathbb{Z} \text{ is such that }\gcd{(a,q)}= 1\}, \text{ and}$$
$$B = \mathbb{Z}/ m\mathbb{Z}.$$
For example, when $m = 6$,
$A = \{(1,1), (2,1), (3,1), (3,2), (6,1), (6,5)\}$.
I'm having difficulty finding an appropriate map between the two sets.
Comment: Sorry about that, I hope it's clearer now.
Answer: Hint: The set $A$ has
$$
\sum_{d\mid m}\varphi(d)=m
$$
elements. For example, for $m=6$ the divisors are $d=1,2,3,6$ and we have $\varphi(1)+\varphi(2)+\varphi(3)+\phi(6)=1+1+2+2=6$.
Reference:
Summation involving totient function: $\sum_{d\mid n} \varphi(d)=n$
Answer: Let's rewrite your definition of $A$ as
$$
A=\{(q,a):q\mid m,\quad 1\le a\le q,\quad\gcd(a,q)=1\}
$$
where all variables are in $\mathbb{N}$.
Take $a$ such that $0\le a<m$ and consider $q=m/\!\gcd(a,m)$. Then $\gcd(a,q)=1$, so $(q,a)\in A$.
Conversely, if $(q,a)\in A$, you have $\gcd(a,m)=m/q$.
So the set $A$ essentially lists the integers in $[0,m)$ and the required map is $f(q,a)=am/q$.
Let's make an example with $m=6$. Then we have
$$
A=\{(1,0),(2,1),(3,1),(3,2),(6,1),(6,5)\}
$$
and we get $f(1,0)=0$, $f(2,1)=3$, $f(3,1)=2$, $f(3,2)=4$, $f(6,1)=1$, $f(6,5)=5$.


Update text of DIV with input value

Question: I'm trying to update the text of a div which has several input buttons. When an input button gets clicked, the value of the button should be passed to the div and replace the text in the div.
It's basically a drop down menu which gets closed when the user clicks on an option. For obvious reasons I'd like the name of the button to replace "Choose one" which is default.
It is structured like this:

Choose one

                        <input id="ButtonCake" class="button_vertical special_button" type="button" value="Cake" size="10px" />
                        <input id="ButtonNoCake" class="button_vertical special_button" type="button" value="No Cake" />

So when the user clicks cake I'd like "Choose one" to be changed to "Cake". I've got a looot of these fields so a really generic jQuery solution would be awesome.
Thanks for reading.
Answer: $(".button_vertical").click(function() {
   $(".button_slide").text($(this).val());
});

If you have multiple .button_slide divs, give them IDs, or better - use a parent
 and use : $(this).parent().children(".button_slide")
Comment: is the event needed? why is it better than without? :)
Answer: $('button').click(function(){
  $('.button_slide').text($(this).val());
})

Should probably do it
Comment: it's `val()` instead of `value()`
Answer: $('input').click(function() {
  var new_val = $(this).val();
  $('.button_slide').val(new_val);
});

Answer: You will need to implement the click() function and pass the value you want to the button_slide by using the text() function
$(".special_button").click(function(e) {
   $(".button_slide").text($(this).val());
});

References

http://api.jquery.com/text/
http://api.jquery.com/click/
Answer:
Choose one

Update text of DIV with input value


Modeling a time series with diminishing seasonality

Question: I have a time series data with its ACF shown below. The time unit is day(s).

What looks intriguing for me is that there seems to be a peaks at every 7 or 8 lags, and it looks like there is a seasonal trend but the trend diminishes as lags increase.  I use auto.arima() to select the best-fit ARIMA process according to information criteria, and below is an ACF of the residuals of a model with ARIMA(2,0,1) with non-zero mean:

While the pattern is weaker after ARIMA(2,0,1), it is still discernable and I wonder what would be the best way to model this trend. I have tried to  use dummies to address seasonality such as:
Week days
data$wday <- wday(dataset$time)
season <- lm(data$variable ~ factor(data$wday))
pacf(season$residuals)

Month
data$month <- month(data$time)
season <- lm(data$variable ~ factor(data$month))
pacf(season$residuals)

Quarters
data$quarter <- quarter(data$time)
season <- lm(data$variable ~ factor(data$quarter))
pacf(season$residuals)

But the pattern is still quite discernable in all cases.
For time series practitioners on the forum, are there other ways that you would use to model this data? The ARIMA(2,0,1) passes the Box.test. But I am just not feeling satisfied as it looks like something associated with time is  still going on in the residual ACF.
Attachment: here is a link to a sample csv file.
Comment: Have you specified your time series frequency as 7 before feeding it into `auto.arima`? Also, why do you say *diminishing* seasonality in the title but do not refer to that in the body?
Comment: You could also include the information in the comment as an edit of the text. That makes it easier for anyone reading it for the first time. Regarding diminishing seasonality, there is a difference between (1) ACF getting closer to zero when lag increases and (2) seasonality becoming less pronounced over time (data generating process gradually changing). I read your title as the latter, but you seem to have in mind the former. But the former is pretty natural and happens all the time.
Comment: The decreasing peaks in your ACF don't mean that the trend is decreasing over time. It means that the correlation becomes weaker as time increases, which is reasonable in the real world.
Comment: Hi Richard, thanks! I have just did the frequency = 7 specification, the `auto.arima` suggests a ARIMA(3,0,3) and `ACF()` indeed becomes flatter. Is this how you would address the pattern issue? I did not emphasize "diminishing seasonality" in the text because while I think there is indeed a clear pattern, I am not sure whether this is the right way to describe (could be just a way seasonality shows?) I have add more descriptions now.
Comment: Regarding the answer by IrishStat, we should get some facts straight: `auto.arima` does just fine in real-world applications, which is proven by its track record on, say, the M competitions data. Meanwhile, the public evidence on Autobox vs. `auto.arima` shows that Autobox does worse (see [here](http://stats.stackexchange.com/questions/32742/auto-arima-vs-autobox-do-they-differ/32764#32764)). So as someone said, "In God we trust; all else bring data".
Comment: Does the suggested seasonality from my analyses makes sense to you given the unstated nature of the data ?
Comment: if you are happy with your answers why don't you accept one and close the question
Answer: When you use a drug (or a piece of software like auto.arima you should read the warnings on the label ... for example auto.arima based upon my experience is very suspect when dealing with real world data that has outliers/anomalies or level shifts or deterministic time trends. Here is a plot of your data  . An additional warning is don't use if you have lots and lots of zeroes  . An additional warning is that it is assumed that there are no fixed effects like days-of-the-week , weeks of the month or monthly effects or Holiday Effects . Your data appears to have both monthly effects and Holiday Effects and a possibly spurious one-day-of-the-month effect .
New inexperienced time series analysts often with an econometric training usually know nothing or very little of these things (assumptions). You inadvertently are using the wrong analytical (although free) software in my opinion. Here is the model summary taking into account memory (non-existent) , monthly effects , holiday effects , one particular day of the month) and anomalies is here .
In closing one might carefully look at https://www.quora.com/What-are-some-skills-nuances-that-software-engineer-turned-data-scientists-lack-that-statisticians-ML-PHDs-possess/answer/Daniel-Tunkelang?ref=fb_page .
The whole idea here is to educate new and old users on the complexities of real-world time series analysis and to shed light on solutions that may not be general enough to be routinely used. My experience tells me (withou seeing your coefficients) that your (3,0,3) or (2,0,1) are just artifacts of fitting versus modelling and most probably has self-cancelling structure i.e. redundant ARMA structure .
In response to @Whuber's excellent question , asking for details (always a good idea !):
@whuber Identification of  daily seasonality is accomplished in two possible ways 1) by examining the ACF /PACF for significant structure (ARIMA seasonality) at lags 7.14 etc. or 2) by attempting to incorporate 6 seasonal /fixed dummies representing days-of-the-week . Neither was found to be useful /significant in this case. In terms of Monthly seasonality this was detected by simple trial and error, i.e. setting up the 11 monthly indicators and doing a step-down. The Holiday seasonal factors (lead, contemporaneous and lag) were also found via a heuristic data-based search process yielding two holiday/seasonal variables Christmas and Mardi Gras) . The day 14 effect was also found by a search/trial and error approach. Thus FOUR distinctly different "seasonal factors" were evaluated with only the ARIMA seasonality totally rejected. auto.arima in my experience only tries to find ARIMA seasonality by a list-based trial and error rather than a data-based trial and error.
Comment: With your negative emphases on "inexperienced," "nonsense," "warnings," "inadvertently," and "spurious" it seems to me that you might have crossed a line that separates offering useful advice from ranting, using language that risks gratuitously offending the OP (who has been gracious about it) and many readers.  Could you point out where you have explained how to identify seasonality in ACF plots and use that to model data?
Comment: Thanks a lot for conducting additional analysis on the data! I agree with what you said and thanks for pointing out that there might be issue when there are predominantly 0 in a time series. I think the problem is still unsolved because further guidance is needed for going beyond `(3,0,3)` and `(2,0,1)` to addressing the monthly and holiday effects you mentioned at the same time. It is not yet clear to me how to do it in `R`. Is it something only Autobox is able to do? Thanks again for the detailed response.
Comment: Sorry, I thought I had deleted the comment. I will delete it now. Please refer to my comment under the OP. On the other hand, recall that we are talking about some 3000 samples of one (for 3000 different time series), not one sample, thus we are evaluating forecasting performance on 3000 data points, which is quite a nice sample size. Also, I look forward to new public comparisons so that the old information could be replaced by new information. (I would love to see a method that works well, regardless of its name!) But so far the best we have is the old information, or is it not?
Comment: @RichardHardy Perhaps you didn't see this I believe that you were referring to a version of AUTOBOX from many, many years ago. AUTOBOX has changed signiifcantly oh these many years. If I am not wrong you only compared accuracies from 1 origin which I am sure you will agree is a sample of 1. Accuracies need to be evaluated from a number of origins. – IrishStat Jul 22 '12 at 0:58
Comment: in my opinion a one origin forecast is a sample of 1 as compared to accurracies measured for multiple origins for each data set which is far more scientific. The fact that this flawed approach of 1 origin was duplicated 3000 times doesn't make it right just deficient 300 times
Comment: I think I have clarified the approach I took in my comments to @whuber . Without wanting to be commercial ( because I have helped to develop AUTOBOX)  there is an R version available but it is not freeware. It is interesting to me for you to comment about the discovered seasonality . Does it appear to be reasonable with your knowledge of how the data was collected ?
Comment: @IrishStat, performance on a test sample size of $n$ is an unbiased and consistent estimator of forecasting performance even when $n=1$, thus I would not call the approach flawed. Would you expect that a forecast method A which did worse for $n=1$ than method B would do better than method B for $n=100$ or $n=1000$? I see no statistical foundation for such a claim. But I see a foundation for the opposite claim (due to unbiasedness and consistency as mentioned above). Regarding seasonality, I do not know how the data was collected, so I cannot comment on that.
Comment: When I said flawed I meant that it was insufficient to prove the case  (nothing whatsoever to do with unbiasedness or consistent estimators )  since it was based upon a sample of 1 forecast performance. Good practice suggests forecasting accuracy needs to be validated from a number of origins not just 1.
Comment: OK, got it. I still think 3000 different time series is a large enough sample. It is also much more informative w.r.t. the method's robustness and general applicability to take 3000 different series than 3000 forecast origins of one series, because we care how a method will work out in the wild, not on a single prespecified series.
Comment: wikopedia ..Cross Validation

training set can only include observations prior to the test set. therefore no future observations can be used in constructing the forecast.
Select the observation k + i for test set, and use the observations at times 1, 2, ..., k+i-1 to estimate the forecasting model. Compute the error on the forecast for k+i.
Repeat the step for i = 1,2,...,T-k where T is the total number of obs.
Compute forecast accuracy over all errors
.. known as a "rolling forecasting origin" because the "origin" (k+i -1) at which the forecast is based rolls forward in time[10]


Can I use SSH tunnels as a VPN substitute?

Question: I'm working at home.
I need to access machines which are in the office. The office has a private LAN (e.g. 192.168.0.0/16) with 100 machines on it. I would like to be able to access these machines from home.
We have one SSH bastion (SSH gateway) host available at gateway.example.org, and we can use this for SSH tunnels.
Here's what I want to do:

SSH from home to gateway.example.org . Somehow, I need to set up the appropriate tunnel (SSH tunnel, SOCKS proxy, etc.)
If the request is for an IP on the 192.168.0.0/16, then force it through a tunnel or a proxy.
If the requested IP does not match the 192.168.0.0/16 network, then don't use a proxy. Some people use ssh to tunnel all TCP traffic. But I only want to proxy requests to the 192.168.0.0/16 network.

Can I use SSH forwarding or a proxy to do this?
I can use a SOCKS proxy with SSH Dynamic Port Forwarding with OpenSSH on Linux/Unix (PuTTY supports similar functionality):
<code>ssh -v -D 3333  gateway.example.org.
</code>
But this just works for the webbrowser and a few other SOCKS-aware applications.
I would like to force some other traffic (VNC ports 5900/5901) through a proxy as well. In particular, I'm trying to figure out how to get Dell DRAC and the application and a Supermicro IPMI KVM-over-LAN to work over this SSH tunnel.
I am currently using a Mac (Snow Leopard) laptop, although I'm looking for a more general networking concept which will work on multiple operating systems.
Comment: Is there a reason why you can't set up a VPN or SSH at the office itself?
Comment: @John : I've simplified my example. In reality, there are a couple distinct sites where we would like this functionality. Other admins own the hardware, and installing a VPN isn't always politically desirable. However, each of these sites supports SSH, so maybe SSH tunneling is a possible alternative.
Answer: I use a combination of dynamic port forwarding and a smart proxy.
ssh -D 12345 me@work
This will set up a SOCKS proxy that listens on your local machine on port 12345, and it proxies traffic over to your work network.
Then install "FoxyProxy" on Firefox.  FoxyProxy has rules to allow it to decide whether to send an HTTP request directly to the destination, or to send it through a proxy.
You want to run vnc through the tunnel.  Some viewers like xvncviewer have a "-via" option, which will open their own SSH tunnel just for that session.  Or you could run the vnc viewer through a program like "tsocks", which will use the 12345 tunnel that we set up above.
Answer:
I'm looking for a more general networking concept which will work on multiple operating systems.

The more generic option would be just to setup a VPN.  There are many different VPN technologies.  I strongly prefer OpenVPN.
There are ways to build a VPN over SSH, but that doesn't perform that well, and most methods tend to take a lot of obscure configuration, the methods will not be cross platform.
Comment: I agree that a VPN would be much better. I am hoping to find a workable SSH alternative, for the cases where I don't control the SSH bastion host.


Probablity, rolling a dice 10 times

Question: Rolling a dice for 10 times, what is the probability of getting side with number 4, for 3 times?
To my knowledge I have to use Binomial distribution to solve the problem how ever I am not sure if the answer is just $P(x=3)$ or $P(x=0)+P(x=1)+P(x=2)+P(x=3)$? I am confused($n=10,p=1/6$).
Answer: The answer is indeed P(X=3) = binompdf(n,p,k) = binompdf(10,1/6,3).

Probablity, rolling a dice 10 times


Maximum Likelihood estimation and the Kalman filter

Question: I know the Kalman filter recursions and can derive these but what I don't really get is how to estimate the hyper parameters using maximum likelihood.
I understand that when running the Kalman filter we get the prediction error and its variance which can be used the construct the likelihood function.
What I don't really get is the order these steps are done in. Am I supposed to:
Method 1
1) Run the Kalman filter given arbitrary starting values and obtain the likelihood function.
2) Maximize the likelihood function wrt to the hyper parameters of the model.
OR
Method 2
1) Estimate the hyper-parameters of the state space model using maximum likelihood.
2) Run the Kalman filter with the hyper-parameters set at these estimates.
I found this question which answers what I need: LogLikelihood Parameter Estimation for Linear Gaussian Kalman Filter. Here the hyper parameters are estimated from the likelihood function and that is the same as the algorithm on p. 8 top in these lecture notes specifies. However, in the same notes it is written (p. 10 mid): "Given a set of optimal parameter values, $\theta_{ML}$, it is now worth to explore the paths of unobserved components...".
Is the correct way to conduct the analysis the following?
Method 3
1) Run the Kalman filter given arbitrary starting values and obtain the likelihood function.
2) Maximize the likelihood function wrt to the hyper parameters of the model.
3) Run the Kalman filter again using the ML estimates obtained in step 2). Use these state estimates in the following analysis?
Comment: I assume you are updating the parameters at each stage by means of an optimization algorithm, in that case the process seems reasonable to me.
Comment: Thanks for the comment. By hyper-parameters I mean the parameters determining the stochastic properties of the state vector and the variance parameter. I think method 3 is right (correct me if I am wrong). One sets initial values. Runs the Kalman filter and obtains a likelihood function. Uses these parameter estimates instead of the initial values and runs the Kalman filter again. This process is then continued until convergence. Is this correct?
Comment: Method 2 seems the most reasonable to me: first estimate the parameters of the model by maximum likelihood (as explained in the post that you linked); then, given the optimal set of parameters found by the optimization algorithm, run the Kalman filter or smoother to get an estimate of the state vector.
Comment: I'm not sure what you are referring with hyper-parameters. In the context of the model defined in section 2.1 of the document that you link, I would distinguish two elements: 1) the parameters to be estimated by ML, i.e., the variances ($\sigma^2_v$, $\sigma^2_w$, $\sigma^2_e$), and 2) the state vector (latent variables or unobserved components), which are the trend $n_t$, the stochastic drift $g_t$ and the cycle $x_t$. The estimates of the latter should be obtained after having estimated the variances by ML.
Answer: We need to first clarify things here. The original derivation of Kalman filter is optimal for causal predictions. That means you predict at time $t$ given observations until time $t$.
Now for the maximum likelihood (ML) inference of parameters, assuming that these parameters are shared across time, during inference of hidden state variables you need to use the non-causal version of Kalman filter, that is the forward-backward Kalman filter (RTS smoothing).
After that you carry out ML estimation as usual. This is an instance of the well-known Expectation-Maximization algorithm, applied within the context of Kalman Filtering as early as 1982! Therefore it is iterative, and you do not necessarily arrive at a global optimum. As typical with these models, starting from a sensible values of hyperparameters first and running the forward-backward algorithm thereon will give better results. This is the case with most Bayesian models that result in non-convex objective functions (EM, Variational Inference, ...).
For further reference, check Appendix A.3 of the review paper by Roweis and Ghahramani:
https://authors.library.caltech.edu/13697/1/ROWnc99.pdf
Answer: I could be wrong, but what makes sense to me is this:

define a function for the kalman filtering and prediction. Make that output the log likelihood (using v and the covariance matrix of v). The log likelihood in this case is described in the stack exchange post you refer to. Make sure Q, R, mu_0 and A are free parameters
Optimize the function with respect to those parameters by maximizing the log likelihood.

Essentially yes, the underlying optimization procedure will start with random parameter values but from there it will optimize the parameters to fit the observables. I don't see how you can estimate these parameters first and then do the kalman filter.
Source: https://faculty.washington.edu/eeholmes/Files/Intro_to_kalman.pdf


Instalação do Unity está dando erro

Question: Fui instalar o Unity para DI e pelo NuGet está dando um erro, que não entendi, parece-me que ele aponta para o NewtonSoft, veja o erro abaixo:

Install-Package : An error occurred while retrieving package metadata
  for 'Newtonsoft.Json.10.0.2' from source
  'C:\Sites\meu_projeto_webapi\packages'. At line:1 char:1
  + Install-Package Unity
  + ~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

Tentei remover assim:
PM> Unistall-Package Newtonsoft.Json RemoveDependencies e dá um erro semelhante ao de cima, mas com essa mensagem:

'RemoveDependencies' is not found.
Answer: Recentemente tive o mesmo problema com o Newtonsoft. Consegui resolver atualizando.
Update-Package Newtonsoft.Json

Comment: Já fiz isso e continuo não conseguindo instalar o Unity. Vou remover o NewtonSoft e tentar instalar o outro pacote e por último o Newtonsoft.Json.
Comment: Pós você ter atualizado o pacote, ele te retornou o mesmo erro?
Comment: Pelo NuGet não consigo remover. Fiz isso: `Uninstall-Package Newtonsoft.Json` e dá erro. Há outra forma de eu desinstalar?
Comment: Na atualização não, ele atualizou, pelo menos não deu erro algum.
Comment: Ele tem algumas dependências, você tem que desinstala-las.
Comment: Sim, fiz isso: `Uninstall-Package Newtonsoft.Json RemoveDependencies`, a menos que a linha acima esteja errada, não funcionou também
Comment: Veja se essa solução resolve o seu problema.

https://stackoverflow.com/a/32794295/4312593
Answer: Este erro não é relacionado ao Unity, exatamente. Por algum motivo, seu Visual Studio não conseguiu se conectar ao NuGet.
Experimente executar o seguinte comando antes de tentar instalar o Unity novamente, no Package Manager Console:
PM> Update-Package

Não acho uma boa ideia remover o JSON.NET, mas, de qualquer forma, o comando correto é:
PM> Unistall-Package Newtonsoft.Json -RemoveDependencies

Comment: Nem consigo desinstalar e nem instalar o Unity, agora tô na roça mesmo.
Comment: Então, já fiz isso com e sem hífen e dá o erro que coloquei no post original(Editei). Com o -force me dá esse erro: `Object reference not set to an instance of an object.`. Vou atualizar e tentar reinstalar o Unity.
Comment: Sim, mas não remova o JSON.NET. Ele é usado em todas as operações. Eu só adicionei essa parte na resposta para questão de conhecimento.
Comment: Eu sei, a intenção seria desinstalar, instalar os dois outro pacotes e depois por último instalar o Newton. Essa é a idéia, pois preciso dele para comunicação Json e etc...
Comment: Aproveitando, por que não usa o [SimpleInjector](https://www.nuget.org/packages/SimpleInjector/) ao invés do Unity?
Comment: Posso tentar, é que no exemplo o autor instalou esse pacote, mas posso substituir sim, seria um plus no curso.
Comment: Cigano, deu o mesmo erro que o Unity, ou seja, fazendo referência ao Newton.
Comment: Então não é erro do Unity ou do Simple Injector. É erro do NuGet. É possível iniciar um projeto novo?
Comment: Reiniciei o VS2015 e vou testar agora, senão inicio outro projeto pra testes e tento instalar tudo novamente.
Comment: Criei um projeto de testes WebApi, vi que a Newtonsoft.Json já estava instalada e consegui instalar a Unity nesse novo, porém no anterior, reiniciei o VS2015 e mesmo assim, não consegui instalar. Dá o mesmo erro.

Instalação do Unity está dando erro


Inversionally equivalent pc sets relation with transposition

Question: So, I'm reading Allen Forte's Structure of Atonal Music and in the sub-chapter 1.4 Inversionally equivalent pc sets he affirms:

It is important to observe that whereas transposition does not imply prior inversion, inversion always implies subsequent transposition, even if it is the trivial case t = 0

So, I don't get why inversion always implies subsequent transposition.
Any explanations?
Answer: This is kind of a weird artifact of Forte's original formulation of the operation, and is often ignored nowadays. The basic idea for him is that the transposition operation Tn is a single operation wherein all of the notes are increased by n (mod 12). The inversion operation TnI is actual a dual function wherein first the notes are inverted around C (PC 0) and then they are transposed to be the specific notes the composer wants. He could have defined an operation I that cuts out the middle man and gets the same results, and many indeed think of it that way now, but it does lead to a more complex, less intuitive idea of inversion.
Let's say we were analyzing a composition that makes use of two alternating harmonies: one is the notes D, Eb and F# and the other is F, G#, A. Both of these collections are members of the (014) set class, but we might be interested in the specific relationship between the two. In Forte's way of thinking, two things have happened. The composer didn't merely transpose the first set to get the second, the composer inverted as well. For simplicity, Forte defines inversion as mirroring around C, so the I operation of D–Eb–F# creates Bb–A–F# by definition. That's the right shape of the set for the second chord, but not the right notes, we still have to transpose the notes by 11. So the T11 is happening in addition to I, and we call it the dual operation T11I.
Again, there's no reason we could just call it I11 and define inversion slightly differently than Forte did, as many contemporary theorists do. For example, earlier editions of Straus' Introduction to Post-Tonal Theory emphasize the dual TnI operation, but the most recent edition veers much more heavily toward In. Still, Forte has a point that an inversion operation which is completely separated from transposition clarifies other aspects of the nature of the two operations.
Comment: I was hoping you'd answer!


Como criar pastas na área de trabalho em python

Question: Eu estava querendo fazer um programa em python que criasse uma pasta na área de trabalho, assim o fiz:
import subprocess
subprocess.call('mkdir Pasta_Teste', shell= True)

Mas o código criava uma pasta dentro da pasta do projeto, logo, tentei usar um comando do prompt que abria a área de trabalho, para depois criar a pasta, tentei isto:
import subprocess

subprocess.call('cd Desktop', shell= True)
subprocess.call('mkdir Pastinha', shell= True)

E recebi este erro:
O sistema n�o pode encontrar o caminho especificado.

E logo após isso ele criou a pasta, mas na pasta do projeto
Como posso fazer ele criar uma pasta na Área de trabalho?
Answer: Resumo
Trabalhar com diretórios no shell é diferente de trabalhar com diretórios de dentro de um programa - transplantar os comandos não vai funcionar.
Mesmo assim, há coisas específicas no uso de diretórios com programas que o
Python só simplificou depois da versão 3.5 - no texto completo eu explico melhor.
Mas, para o sue problema específico, você pode fazer:
from pathlib import Path

desktop = Path.home() / "Desktop"
pastinha = desktop.mkdir("Pastinha")

e, daí pra frente, para qualquer operaçao com arquivos nessa pasta - por exemplo,
criar um arquivo "dados.db" lá dentro:
arq = open(pastinha / "dados.db", "wt")

Note que não foi usado "chdir" ou equivalente - explico abaixo.
Criar um diretório em Python
Primeiro: chamar supprocess.call("mkdir pastinha") para criar uma pasta é o mesmo que telefonar para um chaveiro para abrir a porta da sua casa, quando você está com a chave na mão. Em vez de colocar a chave na porta e girar, você espera até o chaveiro vir, pegar as ferramentas dele, abrir a porta, e paga a taxa pra ele.
Isso por que desta forma o mkdir é invocado como um processo externo do sistema operacional - o sistema tem que criar um novo processo na tabela de processos, reservar os recursos para o mesmo, ler do HD o arquivo com o binário do mkdir, e encerrar o processo em seguida. Tudo isso em geral acontece muito rápido, mas usa umas mil a 10 mil vezes mais recursos computacionais do que simplesmente fazer a chamada ao sistema operacional para criar um diretório.
Essa pode ser feita diretamente do Python usando-se o módulo os: os.mkdir("Pastinha").
A partir do Python 3.5 no entanto, há uma nova API para tudo que é relacionado ao sistema de arquivos, que é a pathlib - ela tem um objeto unificado para representar nomes de arquivos ou diretórios, que já tem métodos para abrir ou ler um arquivo diretamente, ou criar um novo diretório embaixo daquele. Com a pathlib, o código completo seria:
from pathlib import Path
desktop = Path.home() / "Desktop"
desktop.mkdir("Pastinha")

(o uso de getpass.getuser para pegar o nome do usuário foi sugerido  pelodo RafaelTuber em outra resposta, eu não iria lembrar de fazer isso. Mas o Anderson lembrou (nos comentários) que existe o Path.home() que faz isso de forma mais direta, dispensando saber o nome do usuário)
Mudando de diretório
Você não muda de diretório! :-)
Aqui é que está o que faz o seu código não funcionar. A questão de "estar em um diretório" é algo relativo - o "diretório de trabalho" é uma variável de cada processo (programa) que está rodando. Antes de chamar o programa em Python, se estamos num terminal (tipo o cmd), mudamos até o diretório desejado com cd pasta/pasta<enter>. Quando o programa é chamado, o diretório de trabalho dele é esse do qual ele foi chamado "pasta/pasta" - se você usar qualquer caminho de arquivo relativo (isso é, sem começar com uma "/" ou "\" que volta à raiz do file-system, é nesse diretório que as ações acontecem). E isso acontece por que tem uma variável interna do sistema operacional, associada ao seu programa, que fala que o "diretório de trabalho corrente" (CWD) é essa "pasta/pasta".
Se o seu próprio programa faz uma chamada ao sistema operacional dizendo "estou mudando a pasta de trabalho do programa atual", ela é atualizada. Se o seu programa chamar os.chdir("../outra_pasta"),  o sistema operacional entende que o "diretório de trabalho corrente" (CWD) agora é "pasta/outra_pasta". Só que quando o seu programa acaba, e você volta para o cmd, qual é o CWD do cmd? Justamente o "pasta/pasta" - ele não se moveu só por que o processo filho, o seu programa em Python, mudou o próprio diretório.
Quando você usa um subprocesso pra chamar o "chdir" a mesma coisa acontece. O "chdir" é um comando embutido no shell. No caso do Windows o próprio "cmd". O sistema operacional então cria um novo processo, executa um novo CMD internamente, como descrevi acima, esse cmd chama o sistema operacional pra mudar o próprio diretório de trabalho para outro - -e se encerra. A execução do seu programa de Python continua no diretório de trabalho em que estava antes.
No entanto a história não acaba aí - mesmo chamando os.chdir(...), e alterando corretamente o diretório de trabalho do seu programa, essa prática não é recomendada em programas modernos. Isso por que, como o diretório de trabalho é um estado de todo o programa, qualquer função que altere o mesmo vai alterar o diretório tambemnas funções que a chamaram, e qualquer outro lugar do programa - ou seja,não é uma mudança "estanque". Se o programa for multi-thread então, a situação é pior ainda.  Em outras palavras: num programa mais complexo que use mudança de diretório, não dá uma parte do programa saber qual é o diretório atual  - outra função pode ter mudado o diretório.
A boa prática então é que toda e qualquer ação no sistema de arquivos use o caminho absoluto - começando desde o diretorio "/", ou, no caso do Windows, desde o nome do drive: "C:/". Antes da pathlib isso implicava que programas que iriam garantidamente funcionar tinham que ficar usando os.path.join o tempo todo - com a Pathlib isso fica bem mais simples.
Como proceder para realizar ações em um diretório específico
Em Python moderno então, em vez de tentar mudar o diretório, o mais correto
e mais simples é guardar o diretório onde você quer fazer as operações numa variavel, e, para qualquer operação - seja criar um arquivo, outro diretório, etc... usar o operador / (o mesmo usado para divisão de números - ele é ressignificado para objetos da Pathlib) para criar novos objetos Path:
desktop = pathlib.Path("/users/xxxx/Desktop")
minha_pasta = desktop.mkdir("Minha Pasta")
# Criar novo arquivo para scrita dentro dessa nova pasta:

with (minha_pasta / "meu_arquivo.txt").open("wt") as arq:
   # dentro deste bloco, "arq" é o arquivo
   # DEsktop/Minha Pasta/meu_arquivo.txt" aberto para escrita
   ....

Comment: Sobre chegar até a Desktop do usuário, não poderia ser `Path.home() / 'Desktop'`, que usa como base `os.path.expanduser()`?
Comment: Ah - pode também - melhor do que usar do `getpass`,  que nesse caso nem precisa ser importado
Answer: Pega do sistema o nome do usuário com getpass.

import subprocess
import getpass
usuario = getpass.getuser()
subprocess.call('mkdir C:\\Users\\' + usuario + '\\Desktop\\Pasta_Teste', shell= True)

editado removido "" por '' teste e funcionou
Comment: A ideia de pegar o nome do usuário e usar um caminho absoluto é legal. Mas a falha acontece mesmo pq. ele tenta mudar de diretório em um sub-processo.
Comment: (eu inclui a sua sugestão na minha resposta - assim ficam todas as boas práticas e um exemplo completo num lugar só)
Comment: Blz obrigado e que sou novo aqui mais a sobre a dica que eu dei eu mesmo testei aqui usando dentro do sub-processo e funcionou espero que ele tenha conseguido
Answer: Para criarmos uma pasta dentro do Desktop devemos utilizar a seguinte lógica:

Especificar o nome da pasta que desejamos criar no Desktop;
Acessar o Desktop;
Verificar se a pasta desejada já existe dentro do Desktop;
Caso a pasta desejada não exista dentro do Desktop, criar a referida pasta;
Se posicionar dentro da referida pasta.

Com esta lógica podemos implementar o seguinte código:
from os import mkdir, chdir, getcwd, path
import os.path

pas = input('Digite o nome da pasta: ')

cam = path.join(path.expanduser('~'), 'Desktop')
chdir(cam)

if os.path.isdir(pas):
    print(f'A pasta "{pas}" já existe em Desktop!')

else:
    mkdir(pas)
    cam2 = cam + '\\' + pas
    chdir(cam2)
    print(getcwd())

Observe que quando executamos o código, devemos informar o nome da pasta que desejamos criar e pressionar Enter.
A partir deste momento o código entrará no Desktop do respectivo usuário, verificará se a pasta deseja já existe em suas dependências e, caso negativo, criará a referida pasta e se posicionará dentro dela. Caso positivo, exibe uma mensagem dizendo que a referida pasta já existe.
Answer: O seu código usando subprocess.call('cd Desktop', shell= True) não funciona pois o subprocess.call() funciona como um comando único apenas, então quando voce roda ele com o cd, pode ser que ele esteja de fato indo para o diretório que você pediu, mas em seguida você roda um novo subprocess.call() para executar o mkdir, então neste momento o mkdir funciona com um novo comando, ou seja, ele não está na pasta que você espera que ele esteja.
Você pode tentar resolver com os.chdir():
os.chdir("/desktop") # lembre-se de usar o caminho absoluto para a pasta
subprocess.call('mkdir Pasta_Teste2', shell= True)

Espero ter ajudado.
Comment: Sim 0 isso vai funcionar para um script simples, mas como detalhei na minha resposta, confiar em mudança de diretório para o processo inteiro não é a solução ideal.
Answer: Passe o caminho completo para a área de trabalho... Neste caso ele está procurando a pasta: Desktop dentro da pasta do seu projeto, e como não encontra ele apresenta este erro.


How do you change the dimension of your input pictures in pytorch?

Question: i made a convolutional nuralnetwork and i want it to take input pictures and output pictures but when i turn the pictures into tensors they have the wrong dimension :
RuntimeError: Expected 4-dimensional input for 4-dimensional weight [20, 3, 5, 5], but got 3-dimensional input of size [900, 1440, 3] instead

how do i change the dimension of the pictures ? and why does it need to be changed?
and how do i make the output an picture?
i tryed to use
transform = transforms.Compose(
[transforms.ToTensor(),
 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

to normilize the img but it didnt change the dimension .
here is my nuralnet
    def __init__(self):
    super(Net, self).__init__()
    torch.nn.Module.dump_patches = True
    self.conv1 = nn.Conv2d(3, 20, 5)
    self.pool = nn.MaxPool2d(2, 2)
    self.conv2 = nn.Conv2d(20, 16, 5)
    self.fc1 = nn.Linear(16*5*5, 120)
    self.fc2 = nn.Linear(120, 84)
    self.fc3 = nn.Linear(84, 16*5*5)

def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = x.view(-1, 16 * 5 )
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)

    return x

here i get the image and put it into a list:
for i in range(4):
l.append(ImageGrab.grab())

and here is the code that turns the img into an tensor
k=torch.from_numpy(np.asarray(l[1],dtype="int32" ))

Comment: `torch.nn` only supports mini-batches. The input should be in the form (batch_size, channels, height, width). You seem to be missing the batch dimension. Add `.unsqueeze(0)` to add a fake batch dimension.
Comment: i changed that and now i got the error     `RuntimeError: Given groups=1, weight of size [20, 3, 5, 5], expected input[1, 900, 1440, 3] to have 3 channels, but got 900 channels instead`
Comment: i fixed it by transforming before unsqueezing but now i got the error    ` x = x.view(-1, 16 * 5 *5)
RuntimeError: shape '[-1, 400]' is invalid for input of size 1268064`
which i guess is an error in the convelution so thank you for helping me
Answer: In summary, according to the comments you and I posted:
The error is due to torch.nn only supports mini-batches. The input should be in the form (batch_size, channels, height, width). You seem to be missing the batch dimension. You can add .unsqueeze(0) to add a fake batch dimension in the first position.
In addition to the above, you'll also have to rearrange the dimensions of your image from [HxWxC] to [CxHxW]. This is done by .ToTensor() transformation in PyTorch.
For the size mismatch problem of your input image, you could use transformation like this:
transform = transforms.Compose(
                   [transforms.Resize((32,32)),
                    transforms.ToTensor(),
                    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

Comment: thanks it works but now i want the output in the nn to be a picture too how would i have to change the nn to accomplish that?
Comment: I didn't get your question. Do you want to show label predicted by model along-side the picture. You can check the `imshow` function from this official tutorial for this: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#visualize-a-few-images
Comment: i dont want it to predict a label but i want it to predict a picture i want the output to be like the input so i transform the input back into the image but  i dont know how to do that.
Comment: A neural network can output a label only unless you use some advance networks for image generation like GAN (generative models). As far as I could understand from your problem, neural network will give you probabilities of different classes, then you can find the class having the highest probability. Now, instead of showing the class itself, you can plot any image corresponding to that label.


How do I "ping" a different domain to check reachability (within Windows Server)?

Question: I'm troubleshooting a connectivity issue between servers on different domains.
I have a Web Service installed on DOMAIN01\SERVER1. This WebService uses Windows Authentication as its authentication mechanism.
Right now, the Web Service is setup to use DOMAIN01\SOME_USER as the only user allowed.
The clients who will connect to this Web Service are on DOMAIN02 and they've requested that the user allowed on the service should be DOMAIN02\OTHER_USER.
Whatever the user is, I need to give permission on the service's root folder to him. So, I went into the security properties of the folder and tried browsing Active Directory, but DOMAIN02 isn't listed. Hence, not allowing me to set permissions.
Given that the domain isn't listed, is it safe to assume that the domain is not accessible from that server?
Is there a way to check whether the domain is "reachable"?
And is there a way to set permissions correctly without being able to browse through active directory?
Ps.: I'm using "domain" terminology here but, to be honest, I'm not sure wheter those are actual domains os subdomains. Does it make any difference?
Comment: You need to create a Forest trust between the two domains to achieve this.
Answer: Sounds like there is no trust between Domain01 and Domain02.  To have Domain02 users available to assign rights in the file system of a server within Domain01, then you have to have Domain01 trust Domain02, one way, at minimum.  See TechNet.
Answer: Forest Trust will enable Domain02 users to access resources on Domain01.  When it comes to ping, you have to use software or hardware router.
For software router you can use RRAS (Routing and Remote Access).  RRAS is available in Windows Server 2003.  You need 2 LAN cards to establish connections between 2 domains.
Comment: Your comments regarding the network connection are valid if the domains are physically separated or not on the same physical network.  The networking gurus can set up VLANs and routing between them if they are on the same physical network.  Network gurus are the ones to help with WAN routing as well.


How to malloc a table in c?

Question: I'm new to C and am trying to wrap my head around using malloc. I get the importance of using/freeing them but I can't seem to grasp on how to allocate and access them.
Let's say I have a table containing 2 columns of strings with a max width of 10 for column 1 and 8 for column 2. And let's say the number of rows is 3 like the example below. How do I go about creating a malloc to hold the table of values and how do I access it's respective values?
["Turquoise"]["color"  ]
["Tornado"  ]["weather"]
["Triangle" ]["shape"  ]

Any help in illuminating this is much appreciated.
Answer: Preferred method:
    char ***table = malloc(rows * sizeof(char **));
    for (size_t i = 0; i < rows; i++)
        table[i] = malloc(cols * sizeof(char *));

It indexes as table[row][col]
but if cols is a compile time constant we can do better and allocate it all at once:
    char *(*table[cols]) = malloc(rows * sizeof(char *[cols]));

Technically there's a way to do this w/o cols being a compile time constant, but I strongly advise against it. Memory isn't expensive enough for it to pay off anymore.
Comment: bear with me on this :P

In the preferred method using my values, it should look something like this:

int rows = 3;
int cols = 2;
char ***table = malloc(rows * sizeof(char **));
for (size_t i = 0; i < rows; i++)
    table[i] = malloc(cols * sizeof(char *));

If that is correct, where do I specify the size of each column or don't I need to do that?
Comment: @SureshKumar: Is not `cols` the size of each column? Or do you mean the size of each string. I normally stuff strings with `strdup()`.
Comment: Thanks for explaining.. I think strdup is a little too much for me to absorb at the moment but I managed to get malloc allocations working as per your example with an added 3rd malloc for the string value and using strcpy to fill them up. This opens new questions in my quest to learn C which I'll post in a new question. :)
Answer: You may do it using malloc like this:
char **array;
int rows,cols;
array=(char **)malloc(rows*sizeof(char *));
for (int i=0;i<row;i++)
{
   array[i]=(char*)malloc(cols*sizeof(char));
}

Comment: This confuses me a little.. how do I assign & access values for row 0 column 0 and row 0 column 1 separately?
Comment: @SureshKumar Just like how to assign and access with 2D array.                       assign: array[0][0]=... array[0][1]=...   access: array[0][0] array[1][0]

How to malloc a table in c?


Como alterar a cor azul /vermelho de um campo editado

Question: Possuo a seguinte tela :
https://snag.gy/wmPBpM.jpg
Como posso alterar o campo, da lista, previsao1 de forma que fique vermelho ou azul conforme edito ele e salvo alterando seu valor.
Segue o xhtml.
<p:dataTable id="produtosTable"
                value="#{pesquisaPrevisaoBean.lazyModel}" var="produto"
                style="margin-top: 20px" emptyMessage="Nenhuma Previsão Encontrada"
                paginatorPosition="bottom" rows="5" paginator="true"
                paginatorTemplate="{RowsPerPageDropdown} {PreviousPageLink} {CurrentPageReport} {NextPageLink}"
                currentPageReportTemplate="(#{msg.pagina} {currentPage} #{msg.de} {totalPages}) - (#{msg.registro} {startRecord} #{msg.a} {endRecord}) - Total ({totalRecords} #{msg.registros})"
                styleClass="mystyle" paginatorAlwaysVisible="true"
                rowsPerPageTemplate="10, 20, 30" lazy="true">

                <f:facet id="header" name="header">
               Previsão de Vendas
            </f:facet>

                        <f:setPropertyActionListener value="#{produto}"
                            target="#{pesquisaPrevisaoBean.previsaoSelecionada}" />

                        <f:facet name="output">
                            <h:outputText value="#{produto.descricao}" />
                        </f:facet>
                        <f:facet name="input">

                        </f:facet>

                    <h:outputText value="#{produto.codigoFilial}">

                    </h:outputText>

                    <h:outputText value="#{produto.valor}">

                    </h:outputText>

                    <h:outputText value="#{produto.fatorAmortecimentoExponencial}">

                    </h:outputText>

                    <h:outputText value="#{produto.quantidadeRecente}">

                    </h:outputText>

                    <h:outputText value="#{produto.quantidadeRecente}">

                    </h:outputText>

                    <h:outputText value="#{produto.quantidadeRecente}">

                    </h:outputText>

                    <h:outputText value="#{produto.quantidadeReais}">
                        <f:convertNumber locale="pt_BR" minFractionDigits="2"
                            maxFractionDigits="2" />
                    </h:outputText>

                        <f:setPropertyActionListener
                            target="#{pesquisaPrevisaoBean.previsaoSelecionada}"
                            value="#{previsao}" />

        </h:form>

            <h:form id="userDetailForm">

                    <h:outputText value="Previsao:"></h:outputText>

                    <h:inputText
                        value="#{pesquisaPrevisaoBean.previsaoSelecionada.quantidadeRecente}" />

                    <f:facet name="footer">

                    </f:facet>

            </h:form>

Answer: Será necessário colocar uma operador ternário no Previsão1. Algo semelhante a isso:
<h:outputText value="#{produto.quantidadeRecente} style="#{produto.estoqueInsuficiente ? 'color: red' : ''}">

Considere que o estoqueInsuficiente é um método que retorna uma boolean com o estoque do produto.
Tirei esse trecho de código daqui:
https://github.com/algaworks/curso-javaee-primefaces/blob/master/AtualizandoHibernate5/src/main/webapp/WEB-INF/template/pedidos/ItensPedido.xhtml


Implement rss parser

Question: I need to develop an rss parser with a tableview as the first view and detail view as we select a row in table.
But the thing is,  i need to group the feeds in table view based on publishing date and titleForHeaderInSection as the publishing date. That is there should be many sections of rss feed based on date.
With each feed there is a publishing date
I have no idea abt adding sections in tableview.
Please help. Sorry if the information is not sufficient.
Comment: Your problem is not on the rss parser, but in the table view ? (or both ?)
Comment: not the rss parser. how group feeds based on date. and add the common date as the section header. i am using a sample from this link. http://imthi.com/blog/programming/iphone-rss-reader-application-with-source-code.php
Answer: to manage number of Sections in TableView use
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return noOfSections;
}

to calculates the number of rows in a specific section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
       // return no of rows in specific section
 }

in tableView:cellForRowAtIndexPath: method,  extract both the section and row from the index path and use that to manage your data.
for managing title For Header in Section  use
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    // return titleForHeader;
}

Comment: dat s good ... is there a need to implement below methods?
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
Comment: no - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section method is sufficient
Comment: ok. then how does corresponding rows move to their respective sections????                for eg. for 1st section there may b 5 feeds which form a single section. and 2nd sectoin there may b another no. of feeds. and so on.
Comment: - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section is there to manage no of rows in each section'
Comment: ok tank u for that.. evrythng clear. if u get the logic of how to group it using pub date pls inform me.. tank u for ur help. also tanks to Benoît
Answer: You can make a dictionary of array. The key will be the dates, and the object, an array of rss item.
Then I will sort the dictionary key to an array to have the date ordered.
In the table view source delegate:

numberOfSectionsInTableView: will be
the number of date in the sort array,
or the nomber of entry in the
dictionary
tableView:titleForHeaderInSection:
will be the date in the sort array
tableView:numberOfRowsInSection: will be the number of rss item in the dictionary for the key of the sort array item
Comment: NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"Pub date" ascending:YES];

 [root sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];

 [self.root sortUsingDescriptors:states]; is it the way?

Implement rss parser


Is there any book on Google App Engine for java?

Question: I would like to start using Google App Engine for java. But i don't know, where to start.
Is the tutorial provided by google [ http://code.google.com/appengine/docs/java/overview.html ] enough ?
Also, please mention some good books on GAE [ java ] so that i can  download those from rapidshare or torrent buy those books and start reading them.
Comment: Do you already know Java? The tutorials will not show you how to write Java, they'll only show you how to interact with App Engine from your Java code.
Answer: Have a look at "Programming Google App Engine" by Dan Sanderson (O'Reilly). That is for Python or Java.
Answer: Google GAE-Java doc/tutorial is good enough.
There's a book by Apress "Beginning Java Google App Engine" that discussed specifically Java, GWT, JDO. I skimmed over it once while I was in my local bookstore and to be honest, you'll get the same amount of exposure to that of Google's doc/tutorial with extra commentary.
I prefer the straightforward (Google's) approach than the Apress.
Few things to mention:

Google's tutorial/doc directed you to what some people might considered the "preferred" approach (using JDO instead of JPA) and explanations to why.
AFAIK, Apress book doesn't teach you how to unit-test GAE-Java app (especially code that relies on GAE services)
Sometime the Apress book would tell you to go to Google's tutorial (e.g.: how to implement paging)

Apress book is good only if you want to know how to integrate GAE project with other libraries like GWT, Spring, and Flex (not even Wicket). But these are just configuration issues that you can Google it.
Hope this help.
Ed
Answer: I'm currently reading Beginning Java Google App Engine from Apress. I think it's a good start for beginning with java on the app engine. The book also implement a project with GWT. The book give you more organized information then the getting started. Here what you'll learn:

How to get up and running with App Engine, starting with the Google Plugin for Eclipse
All about the development server for testing and developing your applications
How to develop applications using Servlets & JSPs, Spring Framework, and open source Flash - - Remoting and Messaging servers
How to leverage the datastore in your applications, including Persistence as a Service
How to use Spring as a Service for transactions, data access, and more
How to use Google Web Toolkit to create AJAX components to drive your web applications
How to send email and instant messages (XMPP) from within your application
How to increase performance of your apps by storing data in memory using the Memcache service
Comment: Thanks, i am going to start reading `Beginning Java Google App Engine from Apress`
Answer: Try to find the best price you can, or get it used.  Things are changing rapidly with GAE.
Answer: I found Dan Sanderson's book on GAE very immersive and thoughtful. His treatment of the topic is in-depth and goes beyond hello world programs. I recommend this book for all those who want to learn GAE in Java in depth.
OTOH I found Beginning Java Google App Engine from Apress disappointing. I could not find anything in this book which I could not gather from Google I/O and Google articles.
Answer: The tutorial was sufficient to get me started.  I learned App Engine via the tutorials back before there were any books out.
Comment: (And yes, I walked 20 miles to school in the snow, uphill both ways)


Passing client created object to server .net remoting

Question: How can I pass my client-side object to my server object in .net remoting?
This is how I'm doing my test.
On my class library:
public interface IServer
{
  bool SubmitMessage( ISampleClass sample );
}

[Serializable]
public Server : MarshalByRefObject , IServer
{
   Public Server()
   {
   }
   public bool SubmitMessage( ISampleClass sample )
   {
     return true;
   }
}

public interface ISampleClass
{
  string GetName();
}

[Serializable]
public class SampleClass : MarshalByRefObject , ISampleClass
{
  public SampleClass()
  {
  }
  public string GetName()
  {
    return "test";
  }
}

On my Server Application:
IChannel channel = new TcpChannel(9988);
ChannelServices.RegisterChannel(channel,false);
RemotingConfiguration.RegisteredWellKnownServiceType( typeof(Testing.Server) ,"testremote",WellKnownObjectMode.Singleton);
RemotingConfiguration.RegisterActivatedServiceType(typeof(Testing.SampleClass));
RemotingConfiguration.ApplicationName = "TestRemote";

On my Client Application:
Type type = typeof(Testing.Server);
Testing.IServer server = (Testing.IServer)Activator.GetOject(type,"tcp://localhost:9988/testremote");
RemotingConfiguration.RegisteredActivatedClientType(typeof(Testing.SampleClass), "tcp://localhost:9988/TestRemote");
Testing.SampleClass test = new Testing.SampleClass(); // proxy class
server.SubmitMessage(test); // Error here

The error I encoutered was:
    Because of security restrictions, the type System.Runtime.Remoting.ObjRef cannot be accessed.
    Inner Exception: Request Failed.
Please tell me what I'm doing wrong. Thanks!
Answer: I found out already what I'm doing wrong. The SampleClass should not have inherited the MarshalByRefObject.
May be this can be of future reference to others.