No WCF service response - C#

Question: I have added a service reference, directed to a WSDL which loaded all existing WSDLs from the location. I am trying to request data by calling one of the methods like this:
protected void Page_Load(object sender, EventArgs e)
{
    string fLastname, folder, status, header, responsible;
    int date;
    PyramidServices.ServiceSoapClient client = new PyramidServices.ServiceSoapClient();
    string activity = client.GetUserActivity("xxxx", "xxxx", out fLastname, out folder, out status, out date, out header, out responsible);
}

When debugging, the vars are all null. . I have a hard time understanding trace messages since this is not my field. I don't know what to look for, so here is pretty much all the information I get when tracing (Sorry for the Swedish version!):
Sending:

Receiving:

Answer @ Channel:

Stop:

[EDIT]
I tested the method using WCF Test Client and received following:

So it's kind of obvious that I am doing something wrong with the code when parsing the data from the response? My question is, how do I accomplish this?
Comment: Have you tried to use [WCF Test Client](https://msdn.microsoft.com/en-us/library/bb552364%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396). It allows you to easily see the request/response messages
Comment: @LukasKubis Nope :o I'll take a look at that!
Comment: @LukasKubis I used WCF Test Client and got two tabs, Formatted and XML. The formatted says "null" at all posts, just like within Visual Studio. But the XML tab got the expected envelope. How do I get this particular envelope within visual studio or simply, what am I doing wrong?
Answer: With a lot of help from @TomW, we finally found out what the problem was. The code for the WSDL is created in a system that lets me add XML nodes surrounding the data like below:
<wrap>
    <data1></data1>
    <data2></data2>
    <data3></data3>
</wrap>

instead of:
<data1></data1>
<data2></data2>
<data3></data3>

<data1></data1>
<data2></data2>
<data3></data3>

<data1></data1>
<data2></data2>
<data3></data3>

Therefor, the code generated by Visual Studio in Service Reference did not like the way I wrapped the data with unwanted tags. After removing the tag from my code in the system, I received exactly what I wanted with the code at the top.

No WCF service response - C#


git post-receive hook to trigger drush rsync without prompt or with predefined answer

Question: I have set up post-receive hook on my staging server, so whenever I push from dev server a master branch, it updates staging webroot and triggers drush rsync to update live site.
#!/bin/bash

    while read oldrev newrev ref
    do
      branch=`echo $ref | cut -d/ -f3`

      if [ "master" == "$branch" ]; then
    git --work-tree=/var/www/drupal/ checkout -f $branch
    drush rsync --delete --exclude='.htaccess' --exclude='io' --log-file=rsynclog.txt --exclude-files @stage @live

        echo 'Changes pushed live.'
      fi

      if [ "dev" == "$branch" ]; then
        git --work-tree=/var/www/drupal/ checkout -f $branch
        echo 'Changes pushed to staging.'
      fi
    done

Or i hoped to do so :) I have ssh keys in place and that is not the problem, what i can see is that it hangs on destroy yes no question. Output after git push origin from dev machine:

Counting objects: 15, done.
Delta compression using up to 4 threads. Compressing objects: 100%
  (8/8), done. Writing objects: 100% (8/8), 762 bytes, done. Total 8
  (delta 5), reused 0 (delta 0)
remote: Already on 'master'
remote: You will destroy data from mydomain.com:/var/www/drupal/ and
  replace with data from /var/www/drupal// remote: Do you really want
  to continue? (y/n): Aborting. [cancel]
remote: Changes pushed live. To root@dev:/git/drupal 65abd19..7205946
  master -> master

So I would need somehow to tell script that answer is y, or I need a way to  avoid that question at all.
Also, I am not pro bash scripter ;) , are those commands being excecuted in line,  like in php, so one is not executed before other finishes ? (to make sure changes are propagated on staging webroot first, then rsynced all to live).
Answer: Add the --yes option to your Drush command.  This assuredly will work if you place it before the rsync directive.
For example:
drush --yes rsync @dev @live

Drush rsync is different than most Drush commands in that it uses strict option handling.  Commands that work with strict options pass all extra flags that appear after the Drush command name on to the tool that is being invoked.  Thus, drush rsync --yes @dev @live will fail, because the --yes will be ignored by Drush and passed on to rsync.
For more information, see:
drush topic docs-strict-options
Comment: Thank heavens for the maintainers. :) Thanks Greg. +1
Comment: I had not chance to test this yet, but I bet it works as described here. I am lucky to receive an answer from a authentic Drupal Overlord :)


using dojo with phonegap application in android

Question: I created an application using phonegap for android.I want to use dojo with phonegap application to make interface effective and userfriendly.I am new to dojo.I am not understanding where to start.Please can any one guide me how to start with dojo and create applications in android.
Thanks in advance,
K.Himabindu
Comment: this link and all it's series very helpful just follow it http://www.ibm.com/developerworks/web/library/wa-mobappdev1/index.html?ca=drs-
Answer: There are only few resources about Dojo Mobile.
There's a good tutorial thats walks through the complete development of an app:
http://dojotoolkit.org/documentation/tutorials/1.6/mobile/tweetview/getting_started/
The best way to learn is probably to take some time and play with the tests/demos.
If you're completely new to dojo you might want to look at a more basic tutorial.  Can't really recommend something here. Maybe this?: http://docs.dojocampus.org/quickstart/dojo-basics
Comment: ok..Thank you.I saw those links.But i didn't find how to integrate dojo into an application.For example when i developed phonegap app i included .jar file and .js file into my app and then used html,css to create app.Like that to make use of dojo script i copied .js files (dojo.xd.js,dojo.js) and created a simple html using code provided in http://dojotoolkit.org/documentation/tutorials/1.6/mobile/tweetview/getting_started/, android.css.But it did'nt work for me.Please help me how to set up dojo framework for android application.
Comment: Did you do the steps in this tutorial? http://dojotoolkit.org/documentation/tutorials/1.6/hello_dojo/
Comment: I saw that application it is working in android...Hello is displaying,alert with version is displaying,but sliding is not working.when i use dojo.require(dojo.fx) in code even alert also not displaying.What may be the problem??I copied dojo.xd.js into my application.Is that correct way of doing?or i need to set up anything?
Comment: and when i am using the android.css,even hello is not displaying in emulator.
Answer: I had a similar problem.  It turns out that when the APK gets created any files that start with underscores don't get copied and dojo has many files that start with an underscore.  Until this is fixed I am doing the following

During development use externally referenced dojo

For the production application I will create a dojo layer file that contains all the objects I use so there will be no need for dojo to require any additional files.
Comment: this is [the android bug](http://code.google.com/p/android/issues/detail?id=5343)
Answer: Eclipse Method
Maqetta Method
Comment: Aside: When you complete your dojox.mobile app, you'll notice that the whole dojo family of libraries is in your mobile bundle. There are some experimental tools for stripping out unneeded dependencies, but the issue is still mostly manually addressed. Still, I personally prefer dojox.mobile over JQueryMobile. Finally, since a given appstore can reject an app for any reason, profitability and/or audience impact is really the most important focus (so perhaps worrying about bundle size is not so important).
Answer: Refer to the Mobile tutorial at Dojo documentation site:
http://dojotoolkit.org/documentation/tutorials/1.9/mobile/tweetview/getting_started/
Next, get a copy of the Dojo boilerplate so you have the project structure pre-configured.
https://github.com/csnover/dojo-boilerplate
Finally, go to the Dojo Mobile demo site to see what is possible with Dojo Mobile and then pick and choose the controls you want to use from there.
http://demos.dojotoolkit.org/demos/mobileGallery/demo.html
Answer: If you are a beginner, you can learn dojo from
http://www.roseindia.net/dojo/

if you start learning from roseindia you feel like dojo is very simple.
but once after you get confidence, you can try example code from other tutorial site bcz some example from roseindia wont execute successfully


Linked lists deleting

Question: When moving through a linked list, and creating a temp pointer to move through it, do we have to delete the tmp pointer or does it delete automatically. I understand for allocating new memory, with the new operator we need to delete the memory allocated for the pointer, and than set the pointer to null, but if we just have a pointer, i.e
Node*follow=head; //where head is a pointer to a linked list

at the end do we need to delete follow? even if it's not allocating new memory I'm just using it to move through the list?
int countNum (Node *head, int key)
{
    int count=0;

    if (head == nullptr)
        return 0;

    Node *follow=head;

    while (follow != nullptr)
    {
        if(follow->val == key)
            count++;

        follow=follow->next;
    }

    cout << count;
    return count;
}

int main()
{
    Node *head = (1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));

    int counts=0;

    counts= countNum(head,2);

    cout<< counts<< head;
    return 0;
}

I tried to complie this but it crashes and says the int counts=0; is a thread breakpoint? and that my Node*head=(1,cons(2,cons(2,(cons(4,(cons(5,nullptr))))))); is being unused..
Comment: Please do summat with the indentation
Answer: You don't need to delete "the pointer" (and in fact shouldn't), because deletion is for allocated memory. Pointers are just a way to refer to parts of allocated memory.
This code...
delete ptr;

...doesn't delete the pointer named ptr - rather, it deletes the allocated memory pointed to by ptr. In fact, its effect is identical to this code:
ptr2 = ptr;
delete ptr2;

Because again, it's deleteing the same allocated memory, since ptr and ptr2 are made to point to the same place. The names/locations of the pointers themselves are irrelevant; it's where they're pointing that matters.
Answer: Declaring a pointer is like declaring any (int,double etc.) variable. when you delete on a pointer, you delete the memory which the pointer is pointing to and not the pointer itself.

Linked lists deleting


Union with simply connected set

Question: Let $U$ and $V$ be open and path-connected sets in $X$ such that $U$ is simply connected and $U \cap V \neq \emptyset$ is path-connected. Is it true that $\pi_1(U \cup V) = \pi_1(V)$? If not, is there a condition under which this is true? (I believe this would follow from Van-Kampen, but not sure)
Comment: Let $X=\mathbb R^2.$ $U$ be an open disk $\{z\in\mathbb R^2\mid |z|<2\}$ and $V=\{z\mid 1<|z|<3\}.$
Comment: @ThomasAndrews Thanks! So is $\pi_1(U \cup V)$ a quotient group of $\pi_1(V)$? What is it a quotient by?
Answer: The theorem of Seifert - van Kampen says that
$$\pi_1(U \cup V) \approx (\pi_1(U) * \pi_1(V))/N$$
where $*$ denotes the free product and $N$ is the normal subgroup generated by all elements of the form
$$(i_U)_*(g)^{-1}(i_V)_*(g)$$
where $g \in \pi_1(U \cap V)$ and $i_U : U \cap V \to U$ and $i_V : U \cap V \to V$ are the inclusion maps. Note that $(i_U)_*(g)^{-1}(i_V)_*(g)$ is a word with $(i_U)_*(g) \in \pi_1(U)$ and $(i_V)_*(g) \in \pi_1(V)$.
We have $\pi_1(U) = 0$, thus

$\pi_1(U) * \pi_1(V) = \pi_1(V)$
$N$ is the normal subgroup generated by the image of $(i_V)_*$.

Union with simply connected set


Taking the (n+1)st power

Question: I've got trouble to find a rule that enables me to take the (n+1)st. power. If this rule exists can I use it in general?
This is my example, I was looking at the e-number proof and one of the steps says this:
$$
e^{1/(n+1)}\leq 1+ \frac{1}{n}
$$
Now, the author of the article allows us to take the (n+1)st power and the equation will look like this
$$
e\leq (1/n+1)^{n+1}
$$
Why this is allowed?
Comment: Because for all $a,b\in\mathbb{R}_{\ge0}$ and $n\in\mathbb{N}$ we have$$a\le b\iff a^{n+1}\le b^{n+1}$$
Comment: The idea here is that
$$
0 < a\leq b \qquad \Rightarrow \qquad a^k \leq b^k
$$
for $k>1$.
Comment: Thank you very much :)
Comment: In the initial (pre-edited) version of the question, $1/n+1$ was meant as $1/(n+1)$ in the exponent (of $e$) and elsewhere meant as $(1/n)+1$.  It helps to be aware that parentheses are sometimes necessary!
Answer: The function $$x^{n}$$ is monotonic for $x\ge 0.$ Thus, if you have two nonnegative numbers $a$ and $b$ with $$a\le b,$$ it follows that $$a^n \le b^n.$$
Answer: Look for a graph of $f(x)=x^{n+1}$. You will see that, since the function is always increasing in value as $x$ gets bigger, for any $a,b>0$, $a<b$ and $a^{n+1} \leq b^{n+1}$ are equivalent (either both true or both false)
Because of this, the first inequality being true implies the second inequality being true as well (and vice-versa)
Also note that $(e^\frac{1}{n+1})^{n+1} = e$
Answer: This results from very basic properties of inequalities:

If $a<b$ and $c>0$, then $ac<bc$. If $c<0$, then $ac>bc$.

It follows by a trivial induction the following rule:

If $\;0\le a <b$, then for any $n>0$, $0\le a^n<b^n$.
If $\;a <b\le 0$ and $n>0$, then

If $n$ is odd, $\;a^n<b^n\le 0$.

If $n$ is even, $\;a^n>b^n\ge 0$.

Taking the (n+1)st power


Catching Terminal Output in Python

Question: I want to do something similar to the second answer here (but not quite similar): Simulate Ctrl-C keyboard interrupt in Python while working in Linux
It's much simpler and I think I'm just missing something. Say, from a python script, I just want to call 'ping' and terminate it after the 10th time. I'm trying to do it like from the link above:
p = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE)
for line in p.stdout:
  print line
  if re.search('10', line):
    break
os.kill(p.pid, signal.SIGINT)

But it doesn't work.
And I also want the regular output of 'ping' to be displayed. How do I do this?
EDIT: It's not actually a 'ping' that I want to do. I'm just using it as an example of a command with continuous output, which in time, I would like to terminate.
More specifically, I'm running an old version of BitTorrent (v5.0.9 from the 3rd answer here: Where to find BitTorrent source code?) and I'm calling it via python script. The bittorrent-console.py is a simple terminal version, hence 'console'. It outputs multiple lines periodically. Something like:
saving:       filename
file size:    blah
percent done: 100.0
blah:         blahblah

I'm actually calling it by:
subprocess.call(['./bittorrent-console.py', 'something.torrent'])

I want to terminate it automatically when I see it's 100.0 in 'percent done:'.
EDIT: I'm running on CentOS, Python 2.6.
Comment: note also that `10` might be part of the IP address
Comment: Yep, I realized that, but assume there's no 10 in the address or the time. But again, just an example. It could've been `if re.search('icmp_seq=10'`.
Comment: Note that `subprocess.Popen` and `subprocess.call` differ in one *very* important detail. The former is asynchronous, the latter is syncrhonous. In the latter case, by the time you call `os.kill()`, the app is already dead and `os.kill()` has no effect whatsoever.
Comment: Ah. Yes. That is indeed true. I want to keep on using `call` though, because there's no lag in output like when I tried the answer below. It simply has just called bittorrent-console and left it running. I don't know how to terminate it when the download's done except by Keyboard Interrupt.
Comment: Would you happen to know if inside the script, after `call`, there's a way to get the process id of what I just called?
Comment: BTW, you can share a specific answer just by using its `share` link. That's how we can look at the same answer while having different sort options (active/oldest/votes).
Answer: Firstly, you want to use p.stdout.readline. I'm not sure why, but for line in p.stdout doesn't seem to flush. Perhaps it's buffered.
Secondly, you should use sys.stdout.write(line), because print always appends something. In Python 3 you can use print(line, end=""), though.
Also, you should prefer p.kill to os.kill. I'm not sure why you're using os.kill.
import os
import signal
import subprocess
import sys

p = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE)
while True:
    line = p.stdout.readline()

    sys.stdout.write(line)
    sys.stdout.flush()
    if '10' in line:
        break

p.kill()

Comment: I think this will do the trick. Worked for the `ping` example. I'll try it later on what I'm really working on.
Comment: This doesn't output very well. It takes time to write and flush per line since bittorrent-console prints out multiples lines at a time. Is there any way that I could just use subprocess.call, catch the '100.0' and terminate bittorrent-console?
Comment: No, there is not. You can pass `bufsize=0` to `subprocess.Popen` but there is nothing more that you can do (parsing sub-lines could help if lines are given out incrementally, but I doubt it).
Comment: Well, your answer did solve my question. I don't want the slow update on terminal output though. I need it to still look real-time. I guess I'll have to find another way.
Answer: This does exactly what you want and works perfectly on my OS X machine:
import subprocess
import re

def get_output(cmd, until):
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    ret = []
    while True:
        line = p.stdout.readline()
        ret.append(line)
        if re.search(until, line):
            break
    p.kill()
    return ret

 print ''.join(get_output(['ping', 'google.com'], until='10'))

Comment: I thought you meant "after 10 lines of output". In any case, I've updated my answer accordingly.
Comment: Again, `10` and `ping` were just examples.
Comment: I don't see how this answer doesn't answer your question.
Comment: Sure, it does. But you iterated over a range. I wanted to terminate when I see a pattern '10'.

Catching Terminal Output in Python


Extended functions continuous at $z=(0,0)$

Question: There are 4 functions:
$$\frac{Re(z)}{|z|},\frac{z}{|z|},\frac{Re(z^2)}{|z|^2},\frac{zRe(z)}{|z|}$$
I need to determine which of these functions can be defined at $z=0$ in such a way that the extended functions are continuous at $z=0$.
I know that if the extended functions are to be continuous at $z=0$, then $\displaystyle \lim_{z\to 0}f(z)$ must exist. However, I am having some difficulty determining the limits of these functions as $z$ approaches $0$. I can't figure out how to manipulate the current form of these functions so that they are not indeterminate.
I've tried substituting $z=x+iy$ into the expressions but with no avail.
I've also tried changing everything into the polar form, which leads to a lot of possible manipulations, but I'm not sure if I can define a $\theta$ when $z=(0,0)$.
I'd appreciate any guidance! I'm just not sure where to go from here.
Answer: Try with $z=x$ or with $z=iy$ with $x,y$ real. This will find the cases when you cannot extend the functions. In the last case you should take the modulus of the function and see that it goes to zero.
Comment: That makes sense.

To prove that $\displaystyle \lim _{z \to 0}f(z)=0$, should I use the definition of a limit?

If so, I need to show that $\forall \epsilon, \exists \delta >0 \ni |z|<\delta \Rightarrow |\frac{zRe(z)}{|z|}|<\epsilon$. How would I manipulate that last portion so that I can find a suitable value for $\delta$?
Comment: $\lim_{z\to 0} f(z) = 0$ is equivalent to $\lim_{z\to 0} \lvert f(z) \rvert = 0$.
Comment: Use $\lvert zw \rvert = \lvert z\rvert \cdot \lvert w \rvert$ and $\lvert Re(z)\rvert \le \lvert z\rvert$.
Comment: I forgot that $|Re(z)|\le|z|$. Thank you so much for your help!


Pandas Dataframe from Python nested dictionary

Question: I'm trying to create a Pandas dataframe from a python nested dictionary that looks like this:
dictionary = {'user1' : {'a': np.array([1,2,3,4]),
                         'b': np.array([6,7,8,9])},

              'user2' : {'a': np.array([2,3,4,5]),
                         'b': np.array([7,8,9,1])}}

I'd like the data frame to look like this:
      a_w a_x a_y a_z b_w b_x b_y b_z
user1  1   2   3   4   6   7   8   9
user2  2   3   4   5   7   8   9   1

EDIT: (where w,x,y,z are markers that tell what the value in the array represent)
I've tried to modify the solution in these question:
Nested dictionary to multiindex dataframe where dictionary keys are column labels
Construct pandas DataFrame from items in nested dictionary
but cannot get the correct form.
Any help would be great, thank you.
Comment: not sure why you would like to have dataframe with duplicated headers...
Comment: See updated reply.
Comment: Is there any specific reason to use numpy arrays? Is it allowed to use plain lists instead to answer your question?
Comment: @amanb Yes, the data are large 3d numpy arrays.
Answer: You can do the entire thing with a dictionary comprehension, and use enumerate to track the index of each element, giving you some semblance of ordering.
d = {
  k: {f'{ik}_{idx}': el for ik, iv in v.items() for idx, el in enumerate(iv)}
  for k, v in dictionary.items()
}

pd.DataFrame.from_dict(d, orient='index')

       a_0  a_1  a_2  a_3  b_0  b_1  b_2  b_3
user1    1    2    3    4    6    7    8    9
user2    2    3    4    5    7    8    9    1

Answer: Having duplicated column names is rarely a good idea.. but here you go,
Update 2
result = pd.concat({key:pd.DataFrame(val,index=['w','x','y','z']) for key,val in dictionary.items()})
           .unstack(-1)

You know what, I'm gonna leave the multiindex in the column rather than having _ concatenation. It's often more flexible to leave it this way.
Update 1
result = (pd.concat({key:pd.DataFrame(val) for key,val in dictionary.items()})
            .unstack(-1).droplevel(1,axis=1)

Original
result = (pd.concat({key:pd.DataFrame(val) for key,val in dictionary.items()})
            .unstack(-1).T
            .reset_index(level=1,drop=True).T)

result
        a   a   a   a   b   b   b   b
user1   1   2   3   4   6   7   8   9
user2   2   3   4   5   7   8   9   1

Comment: Nice! Btw. you can avoid the transpose operations (which could be expencsive and can spoil your column types). You can do that by using `result.columns.droplevel(1)` instead of `reset_index`.
Comment: Thanks a lot, for the answer. Indeed, you're right about the column names. I made a typo and the column names should be indexed by one of 4 letters: a_w, a_x, a_y, a_z, b_w, b_x, b_y, b_z. I've updated the question. Is it an easy modification of your answer? Thanks again.
Comment: @jottbe haha correct!  I totally forgot that! Actually, since 24, you could apply droplevel on dataframe and control axis. See modified answer.


Linear transformation between infinite dimensional vector space

Question: So the question asks:

Let $\Bbb R^{\Bbb R}$ be the vector space of all functions $f : \Bbb R\to \Bbb R$, and let $\Bbb R^{\Bbb N}$ be the vector space of all infinite sequences, or tuples, $(x_1, x_2,\ldots , x_n,\ldots)$ of real numbers.
(a) Show that both $\Bbb R^{\Bbb R}$ and $\Bbb R^{\Bbb N}$ are infinite-dimensional.
(b) Prove that the function $T : \Bbb R^{\Bbb R}\to\Bbb R^{\Bbb N}$ given by $T(f) = (f(1), f(2),\ldots)$ is a linear transformation.Why doesn't it make sense to talk about the matrix of the linear transformation T?

So so far I have:
For (a) ,
Since the functions from $\Bbb R$ to $\Bbb R$ are polynomial, trigonometric, exponential and etc., by Taylor series expansion, every function has a polynomial representation of either finite degree or infinite degree.
So, the set of all functions over real numbers can be written as
$\Bbb R^{\Bbb R} = \{a_0+ a_1x + a_2x_2+\ldots+ a_nx_n +\ldots\mid a_i\in\Bbb R\}$
So, each function can be written as n-tuples where n is finite or infinite as
$a_0+ a_1x + a_2x_2+\ldots+ a_nx_nn+\ldots=(a_1, a_2,\ldots, a_n, \ldots)$
So, $\Bbb R^{\Bbb R}=\{(a_1, a_2,\ldots, a_n,\ldots)\mid a_i\in\Bbb R)\}$
This forms a vector space under addition of $n$- tuples and scalar multiplication.
Therefore, the function from $\Bbb R$ to $\Bbb R$ forms an infinite dimensional vector space $\Bbb R^{\Bbb R}$.
The space of all infinite sequences of real numbers can be written as
$\Bbb R^{\Bbb N}=\{(a_1, a_2,\ldots, a_n,\ldots)\mid a_i\in\Bbb R\}$.
Each sequence can be written as a linear combination of
$S = \{(1,0,0,\ldots,0,\ldots),(0,1,0,\ldots,0,\ldots),(0,0,1,0,\ldots,0,\ldots),\ldots\}$
So there are infinite vectors in $S$ which span $\Bbb R^{\Bbb N}$
Therefore, $\Bbb R^{\Bbb N}$ is an infinite dimensional vector space.
For (b),
I know to prove a transformation is linear, it has to satisfy:

$T(v_1+v_2)=T(v_1)+T(v_2)\forall v_1, v_2\in V$, and

$T(kv)=kT(v)$ for any scalar $k$.

So, I need to prove that

$T(f_1) +T(f_2) = T(f_1+f_2)$

$T(k\cdot f_1) = k T(f1)$

But, how am I supposed to do this? And the question asks why it makes no sense to talk about the matrix of $T$, is it because the transformation is from an infinite-dimensional vector space to the another infinite-dimensional vector space, and the matrix is abstract which has infinite basis?
Comment: "By Taylor series expansion, every function has a polynomial representation of either finite degree or infinite degree". This is not true.
Comment: You're argument for infinite dimension is wrong. Also, linear combinations have only finitely many terms. You can't do series in plain linear spaces without topology.
Answer: First, not all functions from the reals to the reals are "polynomial, triginometric, exponential". These form in fact a very tiny subset of all functions. A function is not a formula. It's just that for every $x \in \mathbb{R}$ there exists a unique value $f(x) \in \mathbb{R}$. The unicity is what makes it a function. The asignment of $f(x)$ to $x$ is completely arbitrary, e.g. I could take the 7-th digit in the decimal (infinite) representation of $x$ for all $x > \sqrt{17}$, the 5-th digit of that representation for all $x < \sqrt{17}$ and $f(\sqrt{17}) = \pi$. And this is even relatively nice, because I can write a program for it, but this need not be the case in general. A truly "random" function would just be an infinite list of values, one for each real, assigned all independently of each other. So there is no hope for Taylor expansions etc. Realise that $\mathbb{R}^\mathbb{R}$ is truly a huge set.
The operations on $\mathbb{R}^\mathbb{R}$ are pointwise, so if we have two such functions $f,g$ then we define $f+g$ as a new function, by telling what its value on an arbitrary $x \in \mathbb{R}$ is: $(f+g)(x) = f(x) + g(x)$, i.e. we just add the values of $f$ and $g$ at $x$. Similarly for a scalar $c \in \mathbb{R}$, we define $(c\cdot f)(x) = cf(x)$ for all $x \in \mathbb{R}$, where the latter is just standard multiplication in $\mathbb{R}$. The $0$ is just the function where all values are equal to $0$.
Both have infinite sets of linearly independent elements (or vectors, as elements of a vector space are called, even though they are not "vectors" in the old fashioned sense, like the functions in $\mathbb{R}^\mathbb{R}$): take the functions $f_p$, defined for a fixed $p \in \mathbb{R}$: $f_p(x) = 1$ if $x = p$, and $f_p(x) = 0$ if $x \neq p$. So all $0$ except for a spike at $p$.
Why are the $f_p$ linearly independent? By definition, we need to consider a finite linear combination of distinct $f_{p_i}$: $c_{p_1} \cdot f_{p_1} + \ldots + c_{p_n} \cdot f_{p_n} = 0$ (equality as functions, which means just that they have the same values for all $x$), and we need to show that then all $c_{p_i}$ are $0 \in \mathbb{R}$. Because the equality holds for all $x$, we can use $x = p_1$ in particular. Then $$(c_{p_1} \cdot f_{p_1} + \ldots + c_{p_n} \cdot f_{p_n})(p_1) = c_{p_1}f_{p_1}(p_1) + \ldots + c_{p_n} f_{p_n}(p_1) = 0$$ As $f_{p_2}(p_1) = 0$, as $p_2 \neq p_1$, and so on, but $f_{p_1}(p_1) = 1$ this comes down to $c_{p_1} = 0$. The same idea works for all other coefficients as well. So the set of $f_p$ is linearly independent.
The same idea works in $\mathbb{R}^\mathbb{N}$, the set of sequences, which look more like normal vectors, but of infinite length. We just see this as the set of functions from $\mathbb{N}$ to $\mathbb{R}$ and the same operations and independent functions apply. So both spaces are infinite-dimensional.
If we see  $\mathbb{R}^\mathbb{N}$ as a set of functions (as we should) then the function $T$ is just the restriction of $f$ to $\mathbb{N}$. To see that this is linear, take $f,g \in \mathbb{R}^\mathbb{R}$. Then $T(f+g)$ is defined for all $n$ as $(f+g)(n)$, which is in turn defined as $f(n) + g(n)$, and this equals $T(f)(n) + T(g)(n)$, as $T$ does "nothing", it's just the restriction of a function to a smaller domain. The latter sum is just by definition $(T(f) + T(g))(n)$, and as this holds for all $n$ we have equality of functions (or sequences, because we index by $\mathbb{N}$) and $T(f+g) = T(f) + T(g)$. The same can be done for scalars as well.
A matrix for a linear map $T$ is formed by choosing bases for both spaces and computing the base expansion for every $T(b)$ for all basis elements in the domain (as the columns). But here a base for $\mathbb{R}^\mathbb{R}$ is uncountable, so we cannot write it down as a matrix: these can be at most countably infinite in both dimensions.
Answer: Since by (usual, standard) definition
$$\;(f_1+f_2)(x):=f_1(x)+f_2(x)\ \ ,\ \ \ (kf)(x):=k\cdot f(x)\ ,\ \ k,\,x\in\Bbb R$$
we then get
$$T(f_1+f_2)=\left(f_1(1)+f_2(1),\,f_1(2)+f_2(2),\,\ldots\right)=$$
$$=(f_1(1),f_1(2),\ldots)+(f_2(1),\,f_2(2),\,\ldots)=T(f_1)+T(f_2)$$
andalso
$$T(Kf):=\left(kf(1),\,kf(2),\,\ldots\right)=k\cdot(f(1),f(2),\ldots)=kT(f)$$
and thus $\ T\ $ is a linear map.
As you said: since both linear spaces are infinite-dimensional it'd be impossible to write down its matrix with respect to any basis of both spaces (though I've read sometimes about matrices of infinite degree but this seems to be more a way to try to imagine this abstract).
Comment: Why is it down voted?
Comment: @user251257 I have no idea. I think the above is completely accurate, but apparently someone didn't like something and he (or she) didn't write anything.


What has triggered the evolution of 6-0 formation in volleyball?

Question: I have been playing volleyball since childhood. I started off with a 4-2 formation (2 defenders and 4 attackers). Then we moved on to 5-1. (i.e. 5 attackers and 1 defender) But nowadays, I have seen a few teams playing 6-0 as it gives them the advantage of having 3 attackers all the time.
What are the pros and cons of this formation? Will teams be shifting to 6-1 from 5-1, like the earlier trend of 4-2 to 5-1?
Comment: I've changed "offenders" to "offensive players" since "offenders" is not actually the opposite of "defenders" (it means "ones who have committed an offense"). I'm not familiar with volleyball terminology; is a more specific term available?
Comment: I think Spike or spiker would be better!! or rather attackers!!
Comment: "Attackers" would probably be the best term - it _is_ used in sports universally.  "Offensive players" can still be taken as players who often commit offensive acts.
Answer: I found a great post here: http://home.earthlink.net/~tfakehany/system.html

Volleyball systems are referenced numerically. When describing a Volleyball system with numbers, the first number indicates the number of players who are primarily hitters and the second number indicates the number of players who are primarily setters, example: in a "4-2" offense, four of the players on the court are primarily spikers and the other two are primarily setters. The setter in the front row is the active setter, while the remaining setter plays defense and/or sets broken plays. There are three main systems used in Volleyball.
The first is the "4-2" as described above. This is very popular for lower level teams because it is simple, and the active setter usually doesn't have to worry about anything except setting the ball. Few teams above the high school level use the "4-2", although the USSR women's team ran a "4-2" in 1989 against the USA team, so anything is possible. The weakness in this system is that there are only two primary spikers in the front row and the opposition has three blockers, thus there is a major advantage for the defense.
What most teams want is a three hitter versus three blocker alignment. The "6-2" is able to provide this. We all know that the rules won't allow for eight players on the court. So properly, in the "6-2" system two of the hitters double as setters. In the "6-2" the active setter is in the back row. This allows the setter who is in the front row to concentrate on hitting. This is in contract to the "4-2" system where the active setter is n the front row.
When the ball is passed, the back row setter runs to the net to set (in a movement called a penetration) before returning to the back row to play defense. When the ball is passed, the setter in the back row will run to the net and set while the other setter is getting ready to hit. One setter is always in the front row and the other is always in the back row. They should never be in the front or back together.
Most teams use a "5-1" system which is a combination of the "6-2" and the "4-2" systems. With the complexity of today's game, most of the collegiate and international offenses teams have found it difficult to find two setters who are great at both setting and hitting. Furthermore, when you have two setters it can be difficult to switch between the rhythm of one setter and the other setter every three rotations. The Cuban National team and a few top college teams are the only teams who use the "6-2" at a high competitive level. A greater number of middle and lower competitive teams and most recreational teams use the "6-2" system. In the Eastern United States, a "6-2" is frequently called a "6-0". The minor difference between a "6-2" and a "6-0" is that the setter and opposite are substituted as they change rows. When the setter goes to the front row, instead of becoming a hitter, a new hitter substitutes in. This is a "6-2" because you are using eight players (6 2). In the "6-0" there is no substitution and you use six players (6 0).
Comment: Can you summarize the article instead? Copying 80% of it seems a bit much.
Comment: I can, but this is a summary already. And I didn't know if the link would be valid in a few years, that's why I copied the summary.


C# unit test assert datetime

Question: I have a unit test on TimeSpan, and I don't know if I'm doing it right.
TEST CASE:
    ///
    /// Wrapper around TimeSpan.TryParse that avoids out parameters.
    /// Tries to parse a string as a TimeSpan and returns the parsed value as a TimeSpan or null if parsing failed.
    ///
    /// <param name="toParse">A string containing a value to convert</param>
    /// <param name="formatProvider">An object that provides culture-specific formatting information</param>
    /// <returns>The value parsed as a TimeSpan or null if parsing failed</returns>
        public static TimeSpan? ParseTimeSpan(this string toParse, IFormatProvider formatProvider)
    {
        TimeSpan value;
        if (TimeSpan.TryParse(toParse, formatProvider, out value))
        {
            return value;
        }
        return null;
    }

UNIT TEST:
        [TestMethod()]
    public void ParseTimeSpanTest()
    {
        Assert.AreEqual(ParseTime("5:33 pm"), "5:33".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(ParseTime("9:22 AM"), "9:22 AM".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(ParseTime("8:22 pm"), "8:22 pm".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(ParseTime("7:22:44 AM"), "7:22:44 AM".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(ParseTime("9:22:44 pm"), "9:22:44 pm".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(ParseTime("13:22:14"), "13:22:14".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(ParseTime("23:59:00"), "23:59:00".ParseTimeSpan(CultureInfo.InvariantCulture));

        Assert.AreEqual(null, "25:59:00".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(null, "23:70:00 ".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(null, "23:59:75".ParseTimeSpan(CultureInfo.InvariantCulture));
        Assert.AreEqual(null, "five thirty".ParseTimeSpan(CultureInfo.InvariantCulture));

    }

    private static DateTime ParseTime(string time)
    {
        return DateTime.Parse(time, System.Globalization.CultureInfo.InvariantCulture);
    }

Comment: Does it do what you think it should be doing?  It's not really possible for us to know what you expect, and therefore whether it's giving you your expected result.
Comment: I don't get the reason why you need a UnitTest there. Your method basically does the same as TryParse.
Comment: You appear to be asserting that a nullable timespan is equal to a datetime. This will never be true.
Comment: My first time writing unit test, so im expexting it should do what explain above "tries to parse a string as a timespan and returns the parsed value as a timespan or a null if fail"
Comment: And i dont think what im doing is right for Timespan test
Comment: The TryParse function you are wrapping was designed to avoid the implementation you are building here.  You are essentially forcing null propagation rather than using the very correct and convenient TryParse method.  Re-evaluate your design because I think you may have made a wrong turn somewhere.
Answer: There could be a misconception between the types DateTime and TimeSpan.  DateTime is a datatype meant to represent a point in time, e.g. July 4, 1776 at 12 pm.  TimeSpan is meant to represent elapsed time/duration, i.e. the race lasted 12 hours and 36 minutes.
You can take the difference of two DateTimes to produce a TimeSpan.  Trying to parse a time into a timespan is difficult to do.  For instance, how does one convert 9:30 AM into a TimeSpan?
If you are looking for how to test TimeSpan, perhaps the below will help.
 public static TimeSpan? ParseTimeSpan(this string toParse, IFormatProvider formatProvider)
    {
        TimeSpan value;
        if (TimeSpan.TryParse(toParse, formatProvider, out value))
        {
            return value;
        }
        return null;
    }

[TestMethod()]
public void ParseTimeSpanTest()
{
    Assert.AreEqual(ParseTime("5:33"), "5:33".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(ParseTime("9:22"), "9:22".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(ParseTime("8:22"), "8:22".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(ParseTime("7:22:44"), "7:22:44".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(ParseTime("9:22:44"), "9:22:44".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(ParseTime("13:22:14"), "13:22:14".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(ParseTime("23:59:00"), "23:59:00".ParseTimeSpan(CultureInfo.InvariantCulture));

    Assert.AreEqual(null, "22:59:00 AM".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(null, "23:70:00 PM".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(null, "23:59:75 AM".ParseTimeSpan(CultureInfo.InvariantCulture));
    Assert.AreEqual(null, "five thirty PM".ParseTimeSpan(CultureInfo.InvariantCulture));

    var dt = DateTime.Now;
    Assert.AreEqual(dt.AddHours(1) - dt, "1:00".ParseTimeSpan(CultureInfo.InvariantCulture));
}

private static TimeSpan ParseTime(string time)
{
    return TimeSpan.Parse(time, CultureInfo.InvariantCulture);
}

Comment: Thanks, i niw understand what timespan is. And I already did a test for datetime so I won't be doing another one. What i wanted to know is how i could test timespan. Thanks again
Comment: I've updated the answer above with examples of how to test timespan. Note the last test where I'm taking the difference of two DateTime's and comparing it to the result of the ParseTimeSpan Method.
Comment: That's exactly what I'm looking for. Thanks

C# unit test assert datetime


Erro em atributo DateTime no C# gravando no MySQL

Question: Estou tentando inserir no Banco de dados MySQL a data de nascimento do usuário, no C# o atributo data_nascimento é do tipo DateTime e no MySQL o atributo data_nascimento é do tipo Date, para inserir C# estou fazendo fazendo assim:
DateTime nascimento = Convert.ToDateTime(txNascimento.Text);
bDep.Data_nascimento = nascimento;

Obs:. bDep é a classe básica do dependente
E na classe de dados do dependente estou inserindo assim:
public void insertDependente (BDependente bDep) {
      string sql = "INSERT INTO dependente(id_funcionario, nome, grau_parentesco, data_nascimento) ";
             sql += "VALUES ("+bDep.Funcionario.Id_funcionario+", '"+bDep.Nome+"', '"+bDep.Grau_parentesco+"', '"+bDep.Data_nascimento+"')";
            conn.update(sql);
        }

estou selecionando assim:
string sql = "SELECT id_dependente, id_funcionario, nome, grau_parentesco, data_nascimento ";
       sql += "FROM dependente";
                while (mdr.Read()) {
                    BDependente bDepe = new BDependente();
                    bDepe.Id_dependente      = mdr.GetInt16("id_dependente");
                    bDepe.Funcionario.Id_funcionario = mdr.GetInt16("id_funcionario");
                    bDepe.Nome               = mdr.GetString("nome");
                    bDepe.Grau_parentesco    = mdr.GetString("grau_parentesco");
                    bDepe.Data_nascimento    = mdr.GetDateTime("data_nascimento");
                    lDep.Add(bDepe);
                }

Sempre que eu cadastro um novo dependente no banco aparece assim:

O primeiro registro foi feito no próprio MySQL, e mesmo assim quando eu procuro no C# ele traz o horário e quando eu procuro no C# o outro dependente, aparece esse outro erro:
Comment: O erro só ocorre quando a data está gravada errada ou acontece em qualquer linha que tem data?
Comment: O Erro acontece na hora de gravar ! E na hora que eu faço um `SELECT` no banco
Comment: Não foi o que eu perguntei.
Answer: O problema começa na gravação. Não é assim que se faz. Tem um enorme problema de segurança em fazer isso além de gerar este tipo de problema.
Pelo que entendi o erro na leitura ocorre porque a gravação falhou.
Teria que mudar para algo mais ou menos assim:
var sqlInsert = new SqlCommand(@"Insert into dependente (id_funcionario, nome, grau_parentesco, data_nascimento)
                    VALUES (@id_funcionario, @nome, @grau_parentesco, @data_nascimento)", conn);
sqlInsert.Parameters.AddWithValue("@id_funcionario", bDep.Funcionario.Id_funcionario);
sqlInsert.Parameters.AddWithValue("@nome", bDep.Nome);
sqlInsert.Parameters.AddWithValue("@grau_parentesco", bDep.Grau_parentesco);
sqlInsert.Parameters.AddWithValue("@data_nascimento", bDep.Data_nascimento.ToShortDateString());
sqlInsert.ExecuteNonQuery();

Coloquei no GitHub para referência futura.
Aí você vai adaptar para sua necessidade. E por favor, nunca mais tente gravar desta maneira.
O ideal seria não usar variáveis com notação húngara também.

ToShortDateString()
SqlCommand

Não sou fá do termo atributo, prefiro campo.
Comment: @IkaroSales a linha `sqlInsert.Parameters.AddWithValue("@data_nascimento", bDep.Data_nascimento.ToShortDateString());` da resposta está errada, pois ela depende da cultura corrente, cujo formato pode ser diferente do aceito pelo MySql. O correto é `sqlInsert.Parameters.AddWithValue("@data_nascimento", bDep.Data_nascimento);`, sem o *ToShortDateString*. Isso fará com que o parâmetro data seja informado como tipo data de fato (sendo convertido internamente pelo driver para o formato data do banco de dados) e resolverá o seu problema.
Comment: Queria saber como vou fazer isso usando uma classe de conexão:
Comment: public void connecting()    {
            string url = "server=localhost; database=atvfuncionario; uid=root; password=''; convert zero datetime=True";
            conn = new MySqlConnection(url);
            conn.Open();
        }
        public void disconnecting() {
            conn.Dispose();
            conn.Close();
        }
Comment: Isto já é outro problema e só com estas informações eu não saberia dizer. Me parece que nem precisa mudar nada com relação a isto. Claro que o que esta classe parece ser um código errado, mas como eu disse, é outro problema.
Comment: A Inserção continua com erro ! ele inseri a data `0000-00-00`
Comment: É assim que se faz, não sei se tem algum outro problema.
Comment: `bDep.Data_nascimento = Convert.ToDateTime(txNascimento.Text);` É dessa forma que faz pra inserir ?
Comment: olha esse comentário acima !
Comment: Eu acho que você está com outro problema e pelo que está na pergunta não tem como saber. Quando é assim precisa fornecer um [mcve]. Mas provavelmente isto já seria outra pergunta.
Comment: Ajudou bastante ! :/


Drupal 7 Form AJAX button to return javascript script

Question: I am trying to create a form that allows a user to type in an address and click submit. In return the button makes an AJAX callback that builds the javascript link for a user to copy and paste into their site. Once a user inserts the javascript into their site it will display a map from my site. The problem I am having is when the user creates their custom map using my form I want to return a sample map of what it should look like. I need this javascript to be printed to the browser.

But when it is returned nothing is displayed. Here is my form & callback function.
function d3vo_widget_builder_form($form, &$form_state) {
    $form['city'] = array(
      '#title' =>   t('City'),
      '#type' =>    'textfield',
      '#required' => TRUE,
      '#description' => t('Find your city'),
    );

    $form['height'] = array(
      '#title' =>   t('Widget Height'),
      '#type' =>    'textfield',
      '#size' => 5,
      '#description' => t('Set the widget height'),
      '#element_validate' => array('_validate_field_is_numeric'),
    );

    $form['map-area'] = array(
      '#type' => 'markup',
      '#prefix' => '
',
      '#suffix' => '
',
      );

    $form['submit'] = array(
      '#type' =>    'button',
      '#value' =>   'Get Widget',
      '#ajax' => array(
        'callback' => 'd3vo_widget_map_ajax_callback',
        'wrapper' => 'mapsample-div',
        'method' => 'html',
        'effect' => 'fade',
        //'progress' => array('type' => 'none'),
    ),
    );

    return $form;

function d3vo_widget_map_ajax_callback($form, $form_state){
       $point = geocoder('google',$form_state['values']['city']);
       $lng = $point->coords[0];
       $lat = $point->coords[1];
       if($form_state['values']['height'] == NULL){
           $height = 500;
       } else {
       $height = $form_state['values']['height'];
       }
       $widgetScript = '';

        $form['script'] = array(
         '#value' => $widgetScript,
         '#type' => 'textfield',
         '#attributes' => array('readonly' => 'readonly'),
         );

        $form['map'] = array(
          '#type' => 'markup',
          '#markup' => $widgetScript,
        );

        return array($form['script'], $form['map']);
    }

Im not very familiar with using Javascript in Drupal. I have searched and tried many different ways but I can not get the map area to show. Any help would be greatly appreciated.
Answer: The AJAX callback is only used to tell Drupal's AJAX engine what part of form to update. All actual work of building the form elements is supposed to happen in form's hook, in code wrapped in a control statement like the following.
if (!empty($form_state['values'])) {
  // ...
}

Comment: This is exactly correct. Most users get confused by this, and return the wrong value from the AJAX callback.


Binding a context menu header to the selected item of a ListView

Question: I am trying to bind the header of the context menu to a property of the selected item of the respective ListView. The objects of the ItemsSource have an IsDuplicate property. Any idea what is wrong?
<ListView x:Name="AthletesListView" ItemsSource="{Binding FoundAthletes}">
   <ListView.ContextMenu>
      <ContextMenu>
         <MenuItem Name="AddorEditAthleteMenuItem"
                   Header="{Binding SelectedItem.IsDuplicate,
                          ElementName=AthletesListView,
                          Converter={StaticResource FoundAthletesAddEditMenuItemConverter}}"
                   Click="AddAthleteMenuItem_Click"/>
      </ContextMenu>
   </ListView.ContextMenu>

Below the error message:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=AthletesListView'. BindingExpression:Path=SelectedItem; DataItem=null; target element is 'MenuItem' (Name='AddorEditAthleteMenuItem'); target property is 'Header' (type 'Object')
Answer: The ContextMenu is not part of the same visual tree as the associated ListView, because it is displayed in a different window. Consequently, relative source and element name bindings don't work.
Instead, you can use the PlacementTarget of the ContextMenu, which is the ListView.
<MenuItem Name="AddorEditAthleteMenuItem"
          Header="{Binding PlacementTarget.SelectedItem.IsDuplicate, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Converter={StaticResource FoundAthletesAddEditMenuItemConverter}}"
          Click="AddAthleteMenuItem_Click"/>

Comment: Many thanks - will check tomorrow if it works for me. Indeed I also tried Relative source which did not work either...


Identity concerning product of matrices

Question: Suppose ${\bf{x}}$ is a vector with, say, $n$ components, which is represented as a $n\times 1$ matrix. Let $A$ and $B$ be $n \times n$ matrices. I will denote by $(A{\bf{x}})_{i}$ the $i$-th entry of the vector $A{\bf{x}}$, the product of $A$ and ${\bf{x}}$. I have the following object:
$$\sum_{i,j=1}^{n}(A{\bf{x}})_{i}B_{ij}(A{\bf{x}})_{j}$$
I came to the conclusion that:
$$\sum_{i,j=1}^{n}(A{\bf{x}})_{i}B_{ij}(A{\bf{x}})_{j} = {\bf{x}}^{T}A^{T}BA^{T}{\bf{x}}$$
Is this identity true?
Answer: That quantity is $(Ax)^TB(Ax)=x^TA^TBAx$.

Identity concerning product of matrices


Used P2V to reduce size opf LVM VHDX - Issues with grub and booting now

Question: Hi All hoping for some Linux genius advice
I inherited a VMWare VM cluster with a few production VM's
they were all way over provisioned and all have 1tb Thick drives
But are only using 100gb odd each
I want to reduce the size of the VHDX but with it being lvm it is proving tricky
I have used P2V to "move" a test vm on the same host but with a smaller vhdx,
The process went fine until +-97% (which i have read is common)
but now my vm doesn't boot is says
Error Loading operating system.
Below are screenshots of the blkid and fstab and the grug.cfg of the mounted partitions on the broken VM
Here is the grub.cfg file - https://justpaste.it/9ks66
fstab of mounted vm drive - https://i.stack.imgur.com/IKmWF.jpg
blkid - https://i.stack.imgur.com/UgS08.jpg
I know i need to update fstab with the new uuid's but i just don't know which one to use.
Also how do I recreate grub?
Can i use somethign like supergrub2 or do i have to go through grub file and manually change uudi?
Any advice or assistance would be greatly appreciated
Comment: restore the latest version of the vm from the backup
Comment: Did you shrink the partitions and file systems on the original VM before trying to P2V? You do not need UUID's in fstab to mount the partitions. If you know the device names (/dev/sda1 or /dev/mapper/vg0-root) you can mount using them. Finally, did you try booting from a live cd to see if your partitions and data are present and complete?
Comment: Hi, I did not manually shrink the partitions
i left all that to P2V
I have mounted both the /dev/sda and the dev/mapper partitions from a live cd and the data is present
all seems to be there except it doesn't boot
Answer: I figured it out
This solution is only valid for LVM systems

carry out the clone operation and let it fail at 97%
boot failed clone to live cd
mount file system
run in terminal pvdisplay & vgdisplay & lvdisplay & blkid to get the new UUID of your system
edit fstab and boot.cfg and replace the current UUID with the new ones you got in the previous step ( i ran the same commands on the old system for cross reference)
boot new system with supergrub2 iso this should get you into your "new" VM
run sudo grub-install /dev/dsa
run sudo update-grub

System should now boot without issue
Comment: What does "complete failed clone" mean in step 1?
Comment: When using VMware convertor, the conversion process will get to 97% and fail,  stating some sort Grub failure. all has been cloned and is accessible but there is a broken grub boot loader

the following steps are to fix that.


DataTables (AJAX+PHP), Search, Sorting e Pagination não funcionam (Congelamento da tabela)

Question: O DataTables está funcionando, todos os Buttons funcionam e chamam a tabela, estou utilizando load para abrir a tabela por ajax, faz o reload normalmente, porém as demais ações não, como:

Paginação, clica na página 2, muda as descrições abaixo e o número da página, mas não muda as linhas;
Buscar, não funciona, porém utilizando uma busca externa com myFunction de uma coluna, funciona;
Ordenar, não funciona, o ícone até muda para baixo ou para cima...

O que estou entendendo que os valores puxados pelo Ajax da lista gerado pelo PHP estão estáticas e nada muda.
Quando utilizava o foreach dentro da página e listava tudo, funciona corretamente... Estava querendo separar para poder trabalhar com reload e colocar inserir e editar com modais sem precisar atualizar a página.
equipAll.php

<?php

include '../datasourceGestao.php';

$datasource = new datasource();

$result = $datasource->getAllEquip();

$row = array();

foreach ($result as $array) {
    $row[] = array('admin_id' => $array['admin_id'],
     'first_name' => $array['first_name'],
     'last_name' => $array['last_name'],
     'email' => $array['email'],
     'gender' => $array['gender'],
     'birth_date' => $datasource->invertDate($array['birth_date']),
     'telephone' => $array['telephone'],
     'mobile' => $array['mobile'],
     'nivel' => $array['nivel'],
     'status' => $array['status']
    );
}

$output = array(
 "draw"       =>  intval($_POST["draw"]),
 "iTotalRecords" => count($row),
 "iTotalDisplayRecords" => count($row),
 "aaData" => $row
);

$response = json_encode($output);
echo $response;

?>

$(document).ready(function () {

  var table = $('#myTable').DataTable( {
        dom: 'Bfrtip',
        processing:true,
        serverSide:true,
        ajax:{
          "url": "php_action/equipAll.php",
          "type":"POST"
        },
        autoWidth: false,
        responsive: true,
        orderCellsTop: true,
        bFilter: true,
        fixedHeader: false,
        deferRender: true,
        pagingType: "full_numbers",
        lengthMenu: [
            [ 10, 25, 50, -1 ],
            [ '10 linhas', '25 linhas', '50 linhas', 'Todos' ]
        ],
        searching: true,
        select: true,
        select: {
            style: 'multi+shift',
        },
        columns: [
          { data: 'admin_id' },
          { data: 'action' },
          { data: 'first_name'},
          { data: 'last_name' },
          { data: 'email' },
          { data: 'gender',
              "defaultContent": "",
              "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                if("1"==sData){
                  $(nTd).html("");
                }
                else if("2"==sData){
                  $(nTd).html("");
                }
                else{
                  $(nTd).html("");
                }
              }
            },
            { data: 'birth_date' },
            { data: 'telephone' },
            { data: 'mobile' },
            { data: 'nivel',
                "defaultContent": "",
                "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                  if("1"==sData){
                    $(nTd).html("");
                  }
                  else{
                    $(nTd).html("");
                  }
                }
            },
            { data: 'status',
                "defaultContent": "",
                "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                  if("2"==sData){
                    $(nTd).html("");
                  }
                  else{
                    $(nTd).html("");
                  }
                }
            }
        ],
        columnDefs: [
            {
                "targets": [ 0 ],
                "visible": true,
                "searchable": true,
                "data": "admin_id"
            },
            {
                "targets": [ 1 ],
                "data": null,
                "defaultContent": "

<button id='btnGroupDrop1' type='button' class='btn btn-secondary dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'></button>
<button type='button' class='btn btn-link' id='Detail' name='Detail'></button><button type='button' class='btn btn-link' id='Edit' name='Edit'></button><button type='button' class='btn btn-link' id='confirmDelete' name='confirmDelete'></button><button type='submit' class='btn btn-link' id ='confirmStatus' name='confirmStatus'></button>

 "
            },
            {
                "targets": [ 2 ],
                "visible": true,
                "searchable": true,
                "data": "first_name"
            },
            {
                "targets": [ 3 ],
                "visible": true,
                "searchable": true,
                "data": "last_name"
            },
            {
                "targets": [ 4 ],
                "visible": true,
                "searchable": true,
                "data": "email"
            },
            {
                "targets": [ 5 ],
                "visible": false,
                "searchable": true,
                "data": "gender",
            },
            {
                "targets": [ 6 ],
                "visible": false,
                "searchable": true,
                "data": "birth_date"
            },
            {
                "targets": [ 7 ],
                "visible": false,
                "searchable": true,
                "data": "telephone"
            },
            {
                "targets": [ 8 ],
                "visible": false,
                "searchable": true,
                "data": "mobile"
            },
            {
                "targets": [ 9 ],
                "visible": false,
                "searchable": true,
                "data": "nivel"
            },
            {
                "targets": [ 10 ],
                "visible": false,
                "searchable": false,
                "data": "status"
            }
        ],
        buttons: [
            {
              extend:    '',
              text:      '',
              titleAttr: 'Novo Registro',
              action: function (e, node, config){
                $('#myModalInsert').modal('show')
              }
            },
            {
              extend:    'pageLength',
              text:      '',
              titleAttr: 'Mostrar',
            },
            {
              extend:    'copyHtml5',
              text:      '',
              titleAttr: 'Copiar',
              key: {
                key: 'c',
                altKey: true
              },
              exportOptions: {
                modifier: {
                  page: 'current',
                  columns: ':visible'
                }
              }
            },
            {
             extend:    'excelHtml5',
              text:      '',
              titleAttr: 'Excel',
              exportOptions: {
               modifier: {
                 page: 'current',
                  columns: ':visible'
               }
             }
            },
            {
              extend:    'pdfHtml5',
              text:      '',
              titleAttr: 'PDF',
              orientation: 'A4', //portrait or landscape
              alignment: 'center',
              pageSize:  'LEGAL',
              exportOptions: {
                  columns: ':visible'
              }
            },
            {
              extend:    'print',
              text:      '',
              titleAttr: 'Print',
              exportOptions: {
                columns: ':visible'
              }
            },
            {
              extend:    'colvis',
              text:      '',
              titleAttr: 'Alterar Colunas Visiveis',
              "columns": ':not(.noVis)'
           },
            {
              extend:    'selectNone',
              text:      '',
              titleAttr: 'Remover todos os selecionados'
            },
            {
              extend:    'selectRows' ,
              text:      '',
              titleAttr: 'Selecionar linha(s)'
            },           {
              extend:    'selectColumns',
              text:      '',
              titleAttr: 'Selecionar coluna(s)'
            },
            {
              extend:    'selectCells',
              text:      '',
              titleAttr: 'Selecionar celula(s)'
            }
        ],
        language: {
          "decimal":        "",
          "emptyTable":     "Não avaliação deste registro",
          "info":           "Mostrar de _START_ a _END_ de _TOTAL_ registros",
          "infoEmpty":      "Mostrar 0 de 0 de 0 registros",
          "infoFiltered":   "(Total de _MAX_ registros de entradas)",
          "infoPostFix":    "",
          "thousands":      ",",
          "lengthMenu":     "Mostrar _MENU_ registros",
          "loadingRecords": "Carregando...",
          "processing":     "Processando...",
          "search":         "Buscar:",
          "zeroRecords":    "Não há registros",
          "paginate": {
              "first":      "<<",
              "last":       ">>",
              "next":       ">",
              "previous":   "<"
          },
          "loadingRecords": ' ',
          "processing": 'Processando...',
          "aria": {
            "sortAscending":  ": Coluna ativa em ordem ascendente",
            "sortDescending": ": Coluna ativa em ordem descendente"
          },
          "select": {
              "rows": {
                "_": "(Selecionado %d linhas)",
                "0": "(Nenhuma linha selecionada)",
                "1": "(Selecionado 1 linha)"
              },
              "columns": {
                "_": "(Selecionado %d colunas)",
                "0": "(Nenhuma coluna selecionada)",
                "1": "(Selecionado 1 coluna)"
              }
          },
          "buttons": {
              "copy": "Copiar para a área de transferência",
              "copyTitle": "Cópia bem sucedida",
              "copySuccess": {
                  "1": "Uma linha copiada com sucesso",
                  "_": "%d linhas copiadas com sucesso"
              }
          }
        }

  });

    ID
    Opções
    Nome
    Sobrenome
    E-mail
    Gênero
    Dt Nasc.
    Telefone
    Mobile
    Nivel
    Status

<?php
    if (count($result) == 0) {
?>
      Não há Membros Cadastrados
<?php
    }
    else {

 foreach ($result as $array) {
?>

      <?php echo utf8_encode($array['admin_id']); ?>

      <?php echo utf8_encode($array['first_name']); ?>

    <?php echo utf8_encode($array['last_name']); ?>
    <?php echo utf8_encode($array['email']); ?>
    <?php echo ($array['gender'] == 1 ? "Masculino" : "Feminino"); ?>
    <?php echo utf8_encode($array['birth_date']); ?>
    <?php echo utf8_encode($array['telephone']); ?>
    <?php echo utf8_encode($array['mobile']); ?>
    <?php echo utf8_encode($array['nivel']); ?>
    <?php echo utf8_encode($array['status']); ?>

  <?php }
  } ?>

    ID
    Opções
    Nome
    Sobrenome
    E-mail
    Gênero
    Dt Nasc.
    Telefone
    Mobile
    Nivel
    Status

Answer: A página precisa ser trabalhada no PHP, para que filtre, busque e ordene...
Segue o código feito e funcionando:
    <?php

include '../datasourceGestao.php';

$datasource = new datasource();

## Recebendo os $_POST

$draw = $_POST['draw'];

$row = $_POST['start'];

$row_per_page = $_POST['length']; // Linha por página

$column_index = $_POST['order'][0]['column']; // Column index

$column_name = $_POST['columns'][$column_index]['data']; // Column name

if($column_name=="admin_id" or $column_name=="action"){ $column_name = "first_name"; }

$column_sort_order = $_POST['order'][0]['dir']; // asc or desc

$search_value = $_POST['search']['value']; // Search value

## Resultados

if(!empty($column_index)){ $order = $column_name ." " . $column_sort_order . " "; }
else{ $order = "first_name ASC "; }

if($row_per_page != -1){ $pages = $row . ", " . $row_per_page; }
else{ $pages = "1, 10";  }

if(!empty($search_value)){

    $result = $datasource->getAllEquipSearch($search_value,$order,$pages);
}
else{

    $result = $datasource->getAllEquip($order,$pages);
}

$data = array();

foreach ($result[0] as $array) {
    $data[] = array('admin_id' => $array['admin_id'],
        'first_name' => $array['first_name'],
        'last_name' => $array['last_name'],
        'email' => $array['email'],
        'gender' => $array['gender'],
        'birth_date' => $datasource->invertDate($array['birth_date']),
        'telephone' => $array['telephone'],
        'mobile' => $array['mobile'],
        'nivel' => $array['nivel'],
        'status' => $array['status']
    );
}

$output = array(
    "draw"       =>  intval($_POST["draw"]),
    "iTotalRecords" => $result[1],
    "iTotalDisplayRecords" => count($result[0]), // Total de Filtrados
    "aaData" => $data
);

echo json_encode($output);

?>

Como utilizo o datasource.php para os envios, segue:
public function getAllEquip($order,$pages) {
        try {
            $stmt = $this->conn->prepare("SELECT admin_id, first_name, last_name, email,
                                            gender, birth_date, telephone, mobile, nivel, status
                                            FROM tbl_admins
                                            ORDER BY $order
                                            LIMIT $pages");
            $stmt->execute();

            $stmt2 = $this->conn->prepare("SELECT admin_id, first_name, last_name, email,
                                            gender, birth_date, telephone, mobile, nivel, status
                                            FROM tbl_admins");
            $stmt2->execute();

            if ($stmt->rowCount() > 0) {
                $result = array (
                    $stmt->fetchAll(),
                    $stmt2->rowCount(),
                );
                return $result;
            }
        }
        catch(PDOExeption $e) {
            http_response_code(500);
            sql_error("MYSQL ERROR: " . $e->getMessage() . "
");
        }
    }

    public function getAllEquipSearch($search_value,$order,$pages) {
        try {
            $stmt = $this->conn->prepare("SELECT admin_id, first_name, last_name, email,
                                            gender, birth_date, telephone, mobile, nivel, status
                                            FROM tbl_admins
                                            WHERE first_name LIKE '%$search_value%'
                                            OR last_name LIKE '%$search_value%'
                                            OR email LIKE '%$search_value%'
                                            OR telephone LIKE '%$search_value%'
                                            OR mobile LIKE '%$search_value%'
                                            ORDER BY $order
                                            LIMIT $pages");
            $stmt->execute();

            $stmt2 = $this->conn->prepare("SELECT admin_id, first_name, last_name, email,
                                            gender, birth_date, telephone, mobile, nivel, status
                                            FROM tbl_admins
                                            WHERE first_name LIKE '%$search_value%'
                                            OR last_name LIKE '%$search_value%'
                                            OR email LIKE '%$search_value%'
                                            OR telephone LIKE '%$search_value%'
                                            OR mobile LIKE '%$search_value%'");
            $stmt2->execute();

            if ($stmt->rowCount() > 0) {
                $result = array (
                    $stmt->fetchAll(),
                    $stmt2->rowCount(),
                );
                return $result;
            }
          }
        catch(PDOExeption $e) {
            http_response_code(500);
            sql_error("MYSQL ERROR: " . $e->getMessage() . "
");
        }
    }

Comment: Só estou tentando descobrir porque não abri a segunda página em diante de registros...


Show $Y_n = f(X_n) \stackrel{P}{\rightarrow} Y=f(0)=1$

Question: Problem
Let $X_n \stackrel{P}{\rightarrow}0,$ where $(X_n)_{n\geq 1}$ is a sequence of real-valued random variables, such that
$$P(X_n \neq 0) \rightarrow 0 \: for \: n\rightarrow \infty$$
and let
$$f:\mathbb{R} \rightarrow \mathbb{R}$$
such that
$$f(x)=\mathbb{1}_{\{0\}}(x)$$
Show $Y_n = f(X_n) \stackrel{P}{\rightarrow} Y=f(0)=1$
Attempt:
Using the definition:
$$\lim_{n\rightarrow \infty}P(|X_n-X|>\epsilon)=0$$
$$\lim_{n\rightarrow \infty}P(|Y_n-Y|>\epsilon)=\lim_{n\rightarrow \infty}P(|f(X_n)-f(0)|>\epsilon)=\lim_{n\rightarrow \infty}P(|f(X_n)-1|>\epsilon)=\lim_{n\rightarrow \infty}P(|f(X_n)|>\epsilon+1)=\lim_{n\rightarrow \infty}P(|X_n - 0|>f^{-1}(\epsilon+1))=0$$
I don't know if i'm in deep waters with the last equal sign...
Am i on the right track?
Comment: Use `\text{for}` to get the right font and spacing for normal text within equations.
Answer: Notice that $Y_n$ takes the values $1$ and $0$, more precisely, $Y_n(\omega)=1$ if $X_n(\omega)\neq 0$ and $Y_n(\omega)=0$ if $X_n(\omega)= 0$. Therefore, for $0\lt\varepsilon\lt 1$,
\begin{align}
\mathbb P(\lvert Y_n-1\rvert>\varepsilon)&=\mathbb P\left(\{\lvert Y_n-1\rvert>\varepsilon\}\cap \{X_n=0\}\right)+\mathbb P\left(\{\lvert Y_n-1\rvert>\varepsilon\}\cap \{X_n\neq 0\}\right)&\mbox{ using }\mathbb P(A)=\mathbb P(A\cap B)+\mathbb P(A\cap B^c)\\
&=\mathbb P\left(\{\lvert Y_n-1\rvert>\varepsilon\}\cap \{X_n\neq 0\}\right)\\
&=\mathbb P(X_n\neq 0),
\end{align}
where the second equality follows from the fact that if $X_n= 0$, then $Y_n=1$ hence the events $\{\lvert Y_n-1\rvert>\varepsilon\}$ and $\{X_n=0\}$ are disjoint. The last equality follows from the fact that since $\varepsilon<1$, the event $\{X_n\neq 0\}$ is contained in $\{\lvert Y_n-1\rvert>\varepsilon\}$.
Comment: @Flems I have edited.
Comment: If you would, please eleborate on the first equal sign and why this concludes

$$Y_n \stackrel{P}{\rightarrow}1$$

I understand this like $P(|Y_n - 0|>\epsilon)=... \rightarrow 0,$ which conclude that $Y_n \stackrel{P}{\rightarrow}0$


Google CSE autocomplete setup

Question: I'm new to using Google search on local website installations.
I have successfully installed the Google-CSE module and upon searching, results are successfully displayed from Google.
However, my problem is there are no auto-suggestions when a user begins typing content into the search textfield.
Can anyone tell me how to configure my Drupal textfield to show auto-suggestions when input is typed, please?
PS:
My Google site index has autocomplete enabled.
Answer: The solution I used was to copy the scripts/autocomplete.js folder from Googles' GSS module into a custom module, include the autocomplete.js in mymodule.info and imitate the few lines of code in GSS.module which implements the autocomplete functionality.
If you ask me, Google left the CSE unfinished.

Google CSE autocomplete setup


Como faço para limpar dados que peguei em uma busca no banco de dados usando ajax?

Question: Como faço para limpar dados que peguei em uma busca no banco de dados usando ajax? Pois quando eu faço uma segunda busca ele mescla os dados pesquisados.
var nuevos_marcadores = [];
var marcadores_bd= [];
var mapa = null;
function limpiar_marcadores(lista)
{
  for(i in lista)
  {
    lista[i].setMap(null);
  }
}
var formulario = $("#form1");
var punto = new google.maps.LatLng(-3.0774376970512085,-59.997711181640625);
var config = {
  zoom:11,
  center:punto,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapa = new google.maps.Map( $("#mapa")[0], config );

$("#btn_buscar").on("click", function(){
  var passar = $("#genero").val();
  $.ajax({
    type:"POST",
    url:"iajax.php",
    dataType:"JSON",
    data:"palabra_buscar="+passar+"&tipo=buscar",
    success:function(data){
      if(data.estado=="ok")
      {
        $.each(data.mensaje, function(i, item){
          var posi = new google.maps.LatLng(item.latitude, item.longitude);//bien
          var marca = new google.maps.Marker({
            position:posi,
            icon:item.marcador,
            titulo: item.nome_celula,
            endereco: item.endereco,
            cx:item.latitude,
            cy:item.longitude
          });

          google.maps.event.addListener(marca, "click", function(){
            var contentString = '
Celula: ' + marca.titulo + '

Endereço: '+ marca.endereco + '
';
            var infowindow = new google.maps.InfoWindow({
              content: contentString
            });
            marca.addListener('click', function() {
              infowindow.open(mapa, marca);
            });
          });
          marcadores_bd.push(marca);
          marca.setMap(mapa);
        });
      }
      else
      {
        alert("Não tem Celulas Cadastradas");
      }
    },
    beforeSend:function(){

    },
    complete:function(){

    },
  });
});

Answer: Provavelmente você está enfrentando um problema de cache AJAX.
Você pode desabilitar o mesmo de maneira global com o seguinte comando:
$.ajaxSetup({ cache: false })
O que o jQuery faz é adicionar um parâmetro &_=<time stamp> para toda nova url criada. Isso faz com que não existam duas urls iguais e o cache de servidor não tenha efeito.
Comment: mas, reparando bem no seu código, pode ser que você precise limpar a array `marcadores_bd` antes de iniciar a requisição.


SSH into a jail takes so long

Question: I have only one ip address and so I get to my jail through NAT.
SSH to the host is lightning-fast but SSH to the jail is awfully long... Like 20 seconds between ssh command and prompt for public key password :-s
In pf.conf :
rdr pass log (all) on $ext_if proto tcp to port $jail_ssh -> $jail_ip port ssh

pass log (all) quick on $ext_if proto tcp to port $host_ssh

Tcp dumps are the same except the 20 seconds time gap...
sshd configs are equal..!
Comment: Did you disable DNS in the sshd_config for the jail?
Answer: Yeay! Good point, Andrew! The jail couldn't resolve anything since I forgot to nat jail traffic! nat pass on $ext_if from $jail_network -> ($ext_if) was missing in pf.conf :-s

SSH into a jail takes so long


PHP socket connection to TCP Server

Question: I have the following scenario:
I have a given program which provides a JSON interface to which I can connect using a socket connection. Since I want to integrate that interface into my web-application, I'm trying to use the PHP sockets for the communication between server and client. The communication is bidirectional, which means my PHP client is sending requests to the server and the server is also sending requests to my PHP "client". I have no problems with the connection between my PHP and the JSON interface. The only problem is, since I have to wait for requests on the PHP side, I have to run it in an infinity loop. I want to 'echo' some responses and requests i get somewhere into my web-application without having that infinity loop.
My question is, is there a good way to create one php file which can:

create an own socket server so I can send stuff to it from my web application without being stuck in an infinity loop
the stuff I sent to it can be redirected to the JSON server
the response I get from my JSON server redirecting to my web application

Use case I have a solution for: I have a NFC card reader which provides me the functions and informations of a card (uniqueid) and it's connected to my network.
The JSON server sends me a request on "card detected" and I respond with "allowed" or "not allowed". (There the infinity loop doesn't matter)
Use case I don't have a solution for: I have my web application open and I want to write the "uniqueid" parameter into an input field to assign that card to a person. I want to do it this way:
- Click a button "assign card"
- Hold card over the card reader
- Write uniqueid into input field
I don't want to make a direct connection from the web application to the JSON server. I want to make a temporary connection from the web application to the PHP server which has a permanent connection to the JSON server.
I hope this is understandable.
Comment: Have you looked at websockets ? This would allow you to maintain continious bidirectional socket from your browser to web server.
Comment: I was just about to say the same as @insanebits. You might want to checkout this [tutorial](http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket) for more details
Comment: oh wonderful! that will probably help! i will check it out. thanks!
Comment: Wait, I have tried to use this before. But it doesn't support tcp sockets. So do you mean I can use it like this: webapp <-> php socket <-> tcp socket (json interface) ?
Answer: Yes you can. Look into using Ratchet in your application. It seems to fit your requirements. It has bi-directional communication via Websockets.
Your browser will connect to a Ratchet based application in your server listening in a certain port and you will be able to send and receive messages using that connection.
The alternative is long-polling. You can learn more in this StackOverflow answer (which also features Websockets).

PHP socket connection to TCP Server


How to get the values from a formatted field in inc file

Question: I have a description field with a CK editor enabled. And when I get the data from it as node->get('fieldname')->getString() it outputs the content as below.

The contents that I have entered in the Ck editor
, basic_html

I can resolve this in the twig file by getting this as {{fieldname| raw}}. But I need to get this in a php file. How do I get the value without that , basic html part?
Answer:
How do I get the value without that , basic html part?

$node->field_name->value; should do the trick.

I can resolve this in the twig file by getting this as {{fieldname|raw}}.

Using | raw filter in twig is bad security practice, see How do I get the raw field value in a twig template? for a safe solution.


Delphi 2010 Search Wrap Around

Question: Is there any way to switch off the 'Wrapped around' functionality of Delphi 2010's search?
I understand lots of developers have issues with the new search function but it works well for me except when the search wraps around and goes to the first result again.
I also know that you can flag the Search selection box but this will not work for me. I miss the part of the search functionality that would let you search from cursor or scope and tell you when there are no more results.
An example of where this is messing me around. I have a tree view where lots of nodes are being accessed by level indexes (i.e. Item.Level = 1) and I need to add a new node at level 0 and thus all of the indexes needs to shift to Level + 1. I have wasted plenty of time now reassigning these indexes a second and even third time because the search function wraps (I cannot use the Replace for what I am doing).
It's a pain to watch the code scroll bar every time I change something and .Level = 0 has become .Level = 1, .Level = 2, etc.
Answer: The default behavior in Delphi XE is a dialog box that asks to Restart search from the beginning of the file, including an (unchecked) checkbox to Wrap around without asking.
This behavior is configurable in Tools -> Options -> Editor Options -> Auto search wrap around.
I don't have Delphi 2010 running to verify but with any luck, this could be all it takes.
Comment: Thank you, exactly the same for Delphi 2010. Somehow I missed it when going through the options. Thank you again
Comment: XE3 is still the same too
Comment: I accidentally checked the option in the dialog and it has driven me to insanity. Thanks for saving my programming live ;) (working in Delphi 10.1 Berlin as well)

Delphi 2010 Search Wrap Around


Como armazenar as Strings retornadas do método split() em variáveis diferentes?

Question: Possuo o seguinte problema: cadastro uma pessoa informando o Nome e CPF, neste formato "João Medeiros - 123456789-00", e armazeno numa variável do tipo String. Utilizei o método split() para "separar" o Nome e o CPF.
Como faço para armazenar o Nome na variável String nome, e o CPF na variável String CPF?
Answer: Ao usar o método split sua string vira um array, depois é só criar as variáveis e setar qual posição do array você atribui de valor para aquela variável.
String frase = "João Medeiros - 123456789-00";
String array[] = frase.split(" - ");
String Name = array[0]; //Aqui vem o nome como primeira posição
String CPF = array[1]; //Aqui vem o CPF como segunda posição

Comment: Deu certo sua solução!!!


mediation vs interaction - R application

Question: I am struggling to understand how/if the interaction is connected to mediation.
I understand that the interaction in a regression indicates that a variable Z influences the effect of a variable X on the outcome (Y). I am also aware that the variable X can influence Y through another variable, a mediator, in this case, we call it M. This mediation can be either complete or partial, meaning that X can influence Y directly and through M.
However, what I do not quite understand is how these two aspects are related.
I guess I am wrong in assuming that if X interacts with Z, I can decompose the influence of Z on the effect of X on Y using mediation analysis.
What I would like to do is to identify all the variables (Y and Z) that have a combined effect on Y. I then want to decompose the effect of X and Z on Y in:

interaction (X*Z->Y)
direct effect (X->Y)
mediated effect (X->Z(M)->Y)

Are these simply different problems that require independent regression and mediation analyses, or there is a way to explore the above simultaneously? Is there an R package that does that?
Thank you very much!
Answer: Interaction and mediation are different things.
In mediation, we have a causal pathway where one variable causes the mediator and the mediator causes the outcome.
In interaction, we have a joint action, where two variables are associated with an outcome, but the "effect" of one variable depends on the value of the other variable.
Clearly these are different things. If we were to do a simple simulation, we might proceed as follows, in R.
First we simulate for an interaction:
set.seed(1)
X <- rnorm(500)
Z <- rnorm(500)
Y <- X + Z + X*Z + rnorm(500)
lm(Y ~ X * Z)

And we find:
## Coefficients:
## (Intercept)            X            Z          X:Z
##   -0.006785     0.967882     0.927355     0.973669

as expected. In particular, we see that the interaction has an estimate close to 1.
Now, for mediation:
set.seed(1)
X <- rnorm(500)
M <- X + rnom(500)
Y <- X + M + rnorm(500)

Now some care is needed. If we fit the model lm(Y ~ X + M) we obtain:
## Coefficients:
## (Intercept)            X            M
##   -0.005709     1.043180     0.925210

So, here the estimate for X, 1.04 is the direct effect of X on Y, and 0.92 is the indirect (mediated) effect. Typically in inference we would like to total effect, which should obviously be close to 2, and we can obtain that with:
lm(Y ~ X)
## Coefficients:
## (Intercept)            X
##    -0.04731      1.92853

as expected.
Comment: I would recommend reading [this answer](https://stats.stackexchange.com/questions/445578/how-do-dags-help-to-reduce-bias-in-causal-inference/445606#445606) which you may find useful.
Comment: Thank you very much. I think what I do not quite get is whether these concepts are mutually exclusive. In other words, I can have a variable X that influences Y, influences (partially) M and then Y, and also affects Y by its interaction with M. Am I seeing this completely wrong or there is a way to tease this apart? In mediation, do we assume that M is completely caused by X? Thank you
Comment: You're welcome. Yes, we can tease it apart as I showed in the simulations (I showed the direct, indirect and total effects, plus an example of interaction). No we don't assume complete mediation - in that case we would expect a near-zero direct effect instead of 1.04 in the simulation above, and no, we don't have to assume that M is completely caused by X.  And yes, these concepts are mutially exclusive. Interactions are also known as *moderation*, and we can have mediated moderation, and moderated mediation (they are not the same).
Comment: Great, the answer linked is a great explanation. Thank you! So basically if I conduct an explorative analysis and I do not know whether Z interacts with X or it is its mediator I would need to run independent regressions to understand that. In both cases, if I do not include the Z variables (either as interaction or as mediator) in an initial model, I will be in both cases able to capture a smaller fraction of Y variance. So adding them either as Y:X or as M will help me to "model" Y better. Do I understand this correctly?
Comment: Yes, although I would strongly recommend that you choose variables based on some theoretically driven considerations - that is, you ought to know whether mediation and/or moderation is likely.


does wso2 esb xml transform support grovvy

Question: I know that I can use xslt to transform xml, but it costs a lot.
I would like to know whether it is possible using grovvy or not.
Assume I have two xml schema, and transfer them into java file, build to class and deploy to esb.
And I transfer xml via groovy so that I can dynamically change the mapping without deployment java code.
Answer: WSO2 ESB supports Mediators implemented in a variety of scripting languages such as JavaScript, Groovy. (https://docs.wso2.org/display/ESB481/Script+Mediator)
To execute a Groovy script using the WSO2 ESB's script mediator follow below tutorial
http://heshans.blogspot.com/2011/05/executing-groovy-scripts-using-wso2-esb.html
Comment: looks cool, is it just supported in esb4.8.1? when I am reviewing the sample of 4.8, I didn't find the sample of groovy.
Answer: This is a Groovy sample I wrote using WSO2 ESB Script mediator. This is for Json payload. However you can do the same for XML. Get payload using mc.getPayloadXML() method and use Groovy XmlSlurper class to parse xml to Groovy objects.
Comment: This is a sample for xml payload https://udaraliyanage.wordpress.com/2016/08/14/executing-groovy-in-wso2-script-mediator-part-2-xml/


Tem como desativar a animação do de um gráfico Charts.js?

Question:
tem como desativar uma animação de um gráfico Charts.js?
  Estou montando um gráfico que atualiza a cada 300 milissegundos via ajax, porém a animação do gráfico Charts.js atrapalha a visualização.

o código da montagem do gráfico:
function montaGrafico(report_one, report_two, report_three, report_four, datas) {
var ctx = document.getElementById('myChart2').getContext('2d');
var chart = new Chart(ctx, {
    type: 'line',
    // The data for our dataset
    data: {
        labels: [datas[4], datas[3], datas[2], datas[1], datas[0]],
        datasets: [
            {
                label: "Linha 1",
                backgroundColor: 'rgba(0, 140, 204, 0.5)',
                borderColor: 'rgba(0, 140, 204, 0.6)',
                borderWidth: 2,
                data: [report_one[4], report_one[3], report_one[2], report_one[1], report_one[0]]
            },
            {
                label: "Linha 2",
                backgroundColor: 'rgba(255, 150, 102, 0.5)',
                borderColor: 'rgba(255, 150, 102, 0.6)',
                borderWidth: 2,
                data: [report_two[4], report_two[3], report_two[2], report_two[1], report_two[0]]
            },
            {
                label: "Linha 3",
                backgroundColor: 'rgba(248, 255, 33, 0.5)',
                borderColor: 'rgba(248, 255, 33, 0.6)',
                borderWidth: 2,
                data: [report_three[4], report_three[3], report_three[2], report_three[1], report_three[0]]
            },
            {
                label: "Linha 4",
                backgroundColor: 'rgba(112, 204, 124, 0.5)',
                borderColor: 'rgba(112, 204, 124, 0.6)',
                borderWidth: 2,
                data: [report_four[4], report_four[3], report_four[2], report_four[2], report_four[0]]
            }
        ]
    },
    // Configuration options go here
    options: {}
});

}
Answer: Para desabilitar as animações passe no options a seguinte configuração:
options: {
   animation: false
}