How can I restrict Hierarchical Select to specific terms?

Question: I have the below vocabulary in Drupal 7

tags
  -location
  --uk
  ---londin
  ---manchester
  ---liverpol
  --france
  ---paris
  --germany
  ---kolhn
  ---munich
  -skills
  --sport
  ---football
  ---pingpong
  ---tenis

I want have a hierarchical select that only uses my selected term and subterms of it.  For example - if I want location, the user only has first level sub term of location in the list, and in level 2 have the subterms of location.
Is there any way I can accomplish this?
Comment: I'm voting to close this question as off-topic because it is about a bug in the HS module that has been fixed.
Answer: You should create separate vocabularies. That's the clean & easy solution.
Note that you can move terms from one vocabulary to another so migrating it is not even that big an obstacle.
If you really want all terms to be in one big, semantically incorrect vocabulary, then you can. But you'll have to write your own HS API implementation (see the API.txt file in the Hierarchical Select module). Start from the hs_taxonomy implementation in D7, look at the hs_content_taxonomy implementation for D6 to see how it was done there (that implementation did support what you need).
Comment: I told you how you can do it. You'll have to do some programming, but you *can* do it. You cannot reasonably expect every open source project maintainer to just implement everything you need for you.
Comment: tnx for you reply but, my politic is impelement all in one big vocabulary, i see the api.txt but not found my solution ,can u tell me exactly how do it?
Comment: wim leers you as hs developer tell me about how i can do it witout seprate vocabularies,?
Comment: tnx for you reply, finally i wrote a module to handle this work with more feature, a cck widget handler. tnx wim.
Answer: this is a bug in hierarcical select module,and with spend some our about it finally found the solution.
correct patch is here
 this issue in drupal
it's is worked for me.


Tensor Contraction producing a trace.

Question: I was reading a meta-paper and came across this notation.
Given $V$ as a vector space, then there exists a dual space $V^*$. $V^*\otimes V$ is isomorphic to the set of linear transformation that map $V$ into $V$, which is the set of $n$ by $n$ matrices with entries in the scalar field, where $n$ is the dimension of $V$. Then there is a mapping from $V^*\otimes V$ into a scalar field which takes a decomposable element $f\otimes v$ to $f(v)$. This is the mapping that sends a matrix to the trace of that matrix.
I think I've found my answer in this article: The Duality Functor in Linear Algebra
So, this is a tensor contraction. How, in this case, does this tensor contraction produce a trace? I am not sure about that. Good books on tensors might be helpful since I'm having trouble with this. Thanks.
Comment: Note that $V^*\otimes V$ is only isomorphic to the space of linear transformations $V\to V$ if $V$ is finite-dimensional.
Comment: Noted. Thanks. The author didn't mention whether V was finite-dimensional. It is a meta-paper about his work, not the work itself. (He's applying this idea from linear algebra to tensor products of locally free groups, and I got somewhat lost.)
Answer: If $V$ is $n$-dimensional, then let $\mathbf e_1, \mathbf e_2, \ldots, \mathbf e_n$ be a basis for $V$, and let $\pi_1,\pi_2,\ldots,\pi_n$ be a basis for $V^*$, defined by
$$\pi_i(\mathbf e_j) = \begin{cases} 1 & \text{if }i=j \\ 0 & \text{otherwise} \end{cases}$$
$V^*\otimes V$ has a basis consisting of all elements of the form $\pi_i\otimes \mathbf e_j$, so every element of $V^*\otimes V$ is a linear combination of such things. The way it can be interpreted as a linear mapping is by the rule
$$ (\pi_i\otimes \mathbf e_j)(v) = (\pi_i(v))\mathbf e_j $$
and extend to the full $V^*\otimes V$ by linearity.
The matrix corresponding to $F\in V^*\otimes V$ this mapping is the one whose element at position $j,i$ is the coefficient of $\pi_i\otimes \mathbf e_j$ when $F$ is written in this basis. In other words, $\pi_i\otimes \mathbf e_j$ corresponds to a matrix with $1$ at index $j,i$ and zeroes everywhere else, and these matrices combine linearly.
Now contraction in $V^*\otimes V$ is defined by the rule $v^*\otimes v \mapsto v^*(v)$, which means that its effect on basis elements is
$$ \pi_i\otimes\mathbf e_j \mapsto \pi_i(\mathbf e_j) = \begin{cases} 1 & \text{if }i=j \\ 0 & \text{otherwise} \end{cases} $$
So when we write some $F\in V^*\otimes V$ as a linear combination of $(\pi_i\otimes \mathbf e_j)$s, all of the ones with $i\ne j$ drop out when we contract, and the coefficients of $\pi_i\otimes \mathbf e_i$ are all just added. But these coefficients are just the elements on position $i,i$ in the matrix representation, and their sum is the trace of the matrix!
Comment: Ah ha. Oh, so it's the tensor contraction V*⊗V that is like, I'm not sure how to say this properly. using a (diagonal) basis. So, the coefficients are then added together as part of the contraction?  You mean the coefficients are just the elements in the i=j position in the matrix representation?. And of course the sum is the trace of the matrix. Ah, that's the part I was missing how we got the the tensor contraction in V∗⊗V act like a (diagonal) basis. (That's not quite the right term.)
Comment: Thanks. Your explanation was so clear and my restating was so awkward, that I wanted to give it another try to do justice to your explanation. (I haven't felt this dense since grad school.) Here goes: You're applying a basis that basically puts zeros everywhere except the diagonal, that is, where i=j. So when the tensor multiplication is applied, only the diagonal has values other than 0. (Unless zeros were there to begin with.) Then tensor contraction drops out all the zeros and the diagonal is summed, producing the trace. This is akin to creating a determinant. Right?
Comment: @MarkLaPolla: Note that I had a horrible typo in my last equation, fixed now. I don't think "applying a basis that basically puts zeros everywhere except the diagonal" is an entirely correct way of saying it; I would prefer: Contraction is a _linear mapping_ that ignores basis elements outside the diagonal.
Comment: Noted and thanks. Much better. Yes. I like your way of putting it. Thanks again. It's very clear now. I finished the reading the paper. This was very helpful. I am, for now, out of the woods. I appreciate the help.

Tensor Contraction producing a trace.


Modes, Scales, Getting The Tonality/Color Of Said Modes, Etc

Question: I just need some clarification at the moment. So I know a bit about modes, and their relation to a parent scale. What I'm failing to understand is how exactly to play in a modal way on guitar. I remember reading somewhere that what you do is basically transpose a mode's patterns onto the parent scale's key.
For example, say we're dealing with C Major, and we want to go to a D Dorian, what I understand is that to play D Dorian, you would move it from D to a C, and then play a Dorian pattern starting from C. Is this a correct way to go about playing in a modal sense? If so, then I'm also failing how to bring out the flavor of each mode, like in the sense of doing backing rhythm sections. To some degree, I understand that you should start playing, using the above example, a Dm and establish D as the tonal center.
For full disclosure, to aid my learning, I'm trying to use the scale finder on all-guitar-chords, and to say the least, it's all very confusing to me: all that I said above seems to work fine if I take a major scale and look at the major modes, but it all falls apart if I try to apply this same logic to any of the minor modes, which I fail to understand at all. From what I've been learning, all the modes should work under a parent scale, but from what I'm seeing, that's not the case, indicating a flaw in what I've been learning.
To sum it all up: how would you bring out a mode's flavor and establish that mode's mood for a section of music, in both a lead and rhythm sense and how exactly do you use the all-guitar-chords site to show modes in what would be considered a correct way?
Answer: If I understand your wording in the question, there's confusion over terminology. D Dorian is the Dorian mode centered around and rooted on D. It contains all of the notes from its parent scale of C major. The Dorian of C is another, less common, way of naming it. Subtle difference in name, but using different notes! D Dorian -  D E F G A B C, Dorian OF D - E F# G A B C# D.
"Play a Dorian pattern starting from C" will give C Dorian, with Bb and Eb as 'accidentals'. Not fitting too well into a D minor type of tune.
Whilst D Dorian is in essence a minor mode, with D minor being a good start/finish chord, it doesn't follow a normal minor geography. In Dm proper, G minor and probably A (7) will appear. These are not featured in D Dorian, as the Gm is G and A is Am. So the transition from one to another is not like it would be in D minor. In fact, aurally, the pull is more towards C, not surprising, as it's the parent.
Listen to some old Celtic music, as well as old folk songs, which tended towards modal music. Also some of the religious songs from long ago.
Comment: Very interesting, and thank you for your response! I guess all-in-all, you are correct: I don't fully understand all the terminology. Music theory is one of those areas I've only recently delved into, despite playing instruments for probably eight or nine years now (that probably seems odd, and it seems odd even to me!)
So let me see if I understand you correctly: to play a modal backing track, I would need to find chords that fit in said mode? Sorry, I don't quite follow you 100%, is all. Like I said, music theory and I aren't on good terms yet.
Comment: The simple triads that fit into a key are - I,ii,iii,IV,V,vi and viio. That's code for  - capitals=major, lower case=minor. Those chords will work in the parent key. Say C. So, in key C, the chords will be C,Dm, Em, F,G,Am and Bo. So, in D Dorian, the same set of chords work, because the same notes are being used, just centering on D rather that C. Other chords can come into play, just as they may in any song, but those are the mainstay. How's that?


Lp norm attains its minimum

Question: Suppose $\Omega$ is an open set in $\mathbb{R}^n$, and $f\in L^p(\Omega)$, $1\leq p<\infty$. Define $$\|f\|_{min}=\inf\{\|f-a\|_{L^p(\Omega)}:a\in\mathbb{R}\}.$$
Prove that there exists $a\in\mathbb{R}$ such that $\|f\|_{min}=\|f-a\|_{L^p(\Omega)}$.
Thanks for any help.

My attempt: I managed to prove for the case of $f$ a simple function, and perhaps one could use the fact that simple functions are dense in $L^p$ to finish it off?
Suppose $f=\sum_{k=1}^na_k\chi_{E_k}$ where $E_k$ are measureable and disjoint, and $a_k>0$. Since $f\in L^p(\Omega)$, $|E_k|<\infty$ for each $k$.
Then
\begin{align*}
\|f-a\|_{L^p(\Omega)}&=\left(\int_\Omega\left|\sum_{k=1}^n a_k\chi_{E_k}-a\right|^p\,dx\right)^{1/p}\\
&=\left(\sum_{k=1}^n\int_{E_k}|a_k-a|^p\,dx\right)^{1/p}\\
&=\left(\sum_{k=1}^n|a_k-a|^p|E_k|\right)^{1/p}.
\end{align*}
Clearly, $h(a)=\|f-a\|_{L^p(\Omega)}$ is a continuous non-negative function of $a$, and $h(a)\to\infty$ as $a\to\pm\infty$. Hence, the infimum of $h(a)$ must occur when $a$ lies in some compact subset $[-R,R]$. By Extreme Value Theorem, $h(a)$ attains its minimum on $[-R,R]$, that is, there exists $a\in\mathbb{R}$ such that $\|f\|_{min}=\|f-a\|_{L^p(\Omega)}$.
I am kind of stuck here. I know for any $f\in L^p$, there exists simple function $g$ such that $\|f-g\|_{L^p(\Omega)}<\epsilon$, but so far I am not able to use it to finish up the proof. Also, it may be possible that I am on the wrong track entirely and simple functions is not the way to go.
Answer: In what follows $|\Omega|$ denotes the Lebesgue measure of $\Omega$.
If $|\Omega|=\infty$ then, for $f\in L^p(\Omega)$, we have that
$\| f-a\|_{L^p(\Omega)}=\infty$ for any $a\neq 0$ so clearly the infimum is attained at $a=0$.
If $|\Omega|<\infty$ then we use the reverse triangle inequality to get, if $h(a)=\| f-a\|_{L^p(\Omega)}$,
$$
|h(a)-h(b)|\leq \| a-b\|_{L^p(\Omega)} = |\Omega|^{1/p}|a-b|.
$$
This proves the continuity of $h$ and your argument goes through.
Comment: @yoyostein: Yes, or the usual triangle inequality: $$a|\Omega|^{1/p}= \| a \|_{L^p(\Omega)} \leq \| a-f \|_{L^p(\Omega)} + \| f\|_{L^p(\Omega)}.$$
Comment: Nice. How do we see that $\|f-a\|_{L^p(\Omega)}=\infty$ for any $a\neq 0$? Is it also by reverse triangle inequality $\|f-a\|_{L^p(\Omega)}\geq\left|\|f\|-\|a\|\right|=\infty$?

Lp norm attains its minimum


How to calculate $\int_{0}^{\pi/4} \frac{\sin x}{\sin x + \cos x} \, dx$

Question: Can somebody give mi idea, how to solve this integral?
$$\int_{0}^{\pi/4} \frac{\sin x}{\sin x + \cos x} \, dx$$
Comment: add $\cos(x)-\cos(x)=0$ in the numerator and split the integral in two parts..cool eh?
Comment: @tired , right, but I have an exam soon about complex analysis, so that's all I see when I look at integrals lol
Comment: complex analysis
Comment: @Euler_Salter not necessary at all
Comment: use the $\tan$ half angle substitution
Answer: Define $I$ = $\int_{0}^{\pi/4} \frac{\sin x}{\sin x + \cos x} \, dx$ and $J$ = $\int_{0}^{\pi/4} \frac{\cos x}{\sin x + \cos x} \, dx$
Now, what about $J$ + $I$ and $J$ - $I$ ?
Can you get it from here?
Comment: Very fine solution!
Answer: Writting $\sin x+\cos x = \sqrt{2}\sin \left(\frac{\pi}{4}+x\right)$, the integral can be written as
$$\frac{1}{\sqrt 2}\int_{0}^{\pi/4}\frac{\sin x}{\sin(\pi/4+x)}\,\mathrm{d}x=\frac{1}{\sqrt 2}\int_{\pi/2}^{\pi/4}\frac{\sin(\pi/4-u)}{\sin u}\,\mathrm{d}u=\frac{1}{2}\int_{\pi/2}^{\pi/4}\frac{1}{\tan u}\,\mathrm{d}u+\frac{\pi}{8},$$
where we used $\sin(\pi/4-u) = \frac{\sqrt{2}}{2}(\cos u - \sin u)$ in the last equality.
Comment: how does this help? ^^
Answer: Hint:
$$\frac{\sin x}{\sin x + \cos x}=\frac{1}{2}(\tan 2x - \sec 2x+1)$$
Proof:
$$\frac{\sin x}{\sin x + \cos x}=\frac{\sin x(\cos x-\sin x)}{\cos 2x}=\frac{1}{2}\frac{\sin 2x+\cos 2x -1}{\cos 2x}=\frac{1}{2}(\tan 2x - \sec 2x+1)$$
Now integrate $\tan 2x$, $\sec 2x$ and $1$.


send variable with ajax when load page

Question: try setting my code for send variable from view to controller,but my code is not run and show error

Uncaught ReferenceError: $ is not defined

view

controller
function cek(){
     echo $st;
}

Comment: Have you included `jquery` js file
Comment: Possible duplicate of [JQuery - $ is not defined](https://stackoverflow.com/questions/2194992/jquery-is-not-defined)
Answer: Looks like either you have not included jQuery plugin or added after your JavaScript code. $ is alias to jQuery.
In your view before script tag, include this

send variable with ajax when load page


Bulgarian Solitaire: Number of root loops and which numbers have multiple root loops

Question: For an explanation of what Bulgarian Solitaire is, look here.
I have worked out the full graphs for $1 \leq \text{number of cards} \leq 13$ in the past, and all of them had just one root loop...except for $8$ cards. In that case, there are two root loops, one of which is $(4,2,2) \to (3,3,1,1)$ (which is also the entire subgraph for that loop). So, here we have a loop of size $2$ and a loop of size $4$. Unlike my previous question, I have no good intuition as to why this is the case.
<code>Which numbers have multiple root loops? How many do they have?
</code>
Answer: In Jyrki's notation that's the cycle from $(4,3^*,2,1^*) = (4,2,2)$ to $(4^*,3,2^*,1) = (3,3,1,1)$ and back. Here $n = 8 = T_4 - 2$, and the decrement $2$ divides $4$. In general, suppose that $n = T_k - m$, where $0<m<k$, and suppose that $m|k$. If $p=k/m$, you'll have a cycle of length $p$ starting with $$\left(k^*,k-1,k-2,\dots,((m-1)p)^*,(m-1)p-1,\dots,p^*,p-1,\dots,2,1\right),$$ the position in which each of the $m$ multiples of $p$ is starred. The next two values of $n$ for which you'll get a second cycle are $18 = T_6 - 3$ and $19 = T_6 - 2$; the 'extra' cycles for these $n$ are
$$(6^*,5,4^*,3,2^*,1) = (5,5,3,3,1,1)$$
$$(6,5^*,4,3^*,2,1^*) = (6,4,4,2,2)$$ and $$(6^*,5,4,3^*,2,1) = (5,5,4,2,2,1)$$
$$(6,5^*,4,3,2^*,1) = (6,4,4,3,1,1)$$
$$(6,5,4^*,3,2,1^*) = (6,5,3,3,2)$$ respectively.
Answer: The Bulgarian Solitaire state diagram for $S$ has a single cycle (or fixed point) if and only if $S$ is within 1 of a triangular number.  In addition to 18 & 19 mentioned before, the diagram for 17 has two components.
The number of components was given by Brandt in 1982, the first English language publication on the topic (although it does not mention the name, which was popularized by Martin Gardner).  Using his notation, write $S = \binom{n+1}{2} - a$ with $0 \leq a \leq n-1$.  The number of cycles for Bulgarian Solitaire on $S$ is
$$ \frac{1}{n} \sum_{d|(n,a)} \varphi(d) \binom{n/d}{a/d}$$
where $(n,a)$ denotes the greatest common divisor and $\varphi(d)$ is the Euler totient function.  The length of the cycle for each $d$ is $(n+1)/d$.
Some articles on this are freely available, for instance in the Electronic Journal of Combinatorics.  If you have access to the College Mathematics Journal (perhaps through JSTOR), there was a survey article in March 2012.


How do I access a .NET GUI application through a Web Service?

Question: I've been searching for a while for an answer to my problem but so far have found no reliable links. What I'm trying to do is this: I've built a Windows .NET GUI application. I'd like to be able to access the functionality of the Form Controls through a Web Service. Are there any good links on how to do this?
Thanks for your help.
Answer: You can easily host a Windows Communication Foundation Web service in your WinForms application.  See the MSDN article on How to Host a WCF Service in a Managed Application.
Note that if you want your service operations to interact with the UI controls (which I assume is the purpose of having the service in the app -- otherwise it's better to create a normal, non-visual service and host it in IIS or a Windows service) then you will need to use Control.Invoke or Control.BeginInvoke because service operations run on a background thread.
Answer: This is a pretty good example of hosting a service from a Winforms application.
http://www.codeproject.com/KB/WCF/WCFexample.aspx
You could also do something simple like this in your main method:
<code>    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        ServiceHost host = new ServiceHost(typeof(TestService));
        NetNamedPipeBinding namedPipe = new NetNamedPipeBinding();
        host.AddServiceEndpoint(typeof(ITest), namedPipe, "net.pipe://localhost/test");

        host.Open();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new AutoDeployApp());
    }
</code>
Then, use this type of thing inside the service to get at the running form:
<code>        MyForm form = Application.OpenForms["MyForm"] as MyForm ;
</code>


Can I set a single .NET MVC bundle to always be bundled (even in debug mode)?

Question: I am using .LESS variables in my files. I have a LessTransform in my Bundler, which allows all my .less to see the variables. But when I turn bundling off, obviously it no longer works!
Can I see just a single bundle to always be bundled? (even when compilation debug=true)
Answer: Unfortunately it's an all or nothing setup (determined very early on by AssetManager.DeterminePathsToRender which, based on EnableOptimizations, either emits a bundle URL or individual script paths).
You could look into using the WebEssentials extension which handles .less (as well as other) files natively. At least then you'll be able to include the compiled version and let you move onto more important matters. Once you've finalized, you can bring bundling back into the equation.
I do not work on/for WebEssentials, I just find the extension very helpful
Answer: In the main application that I work with, we use the DotLess compiler directly to serve our stylesheets.
We store custom .LESS variables in the database and combine them with the .less file on the fly.
using System.Web.Mvc;

using dotless.Core;

using System.Web.Helpers;

public class SkinController : Controller
{
   private const int TwentyMinutes = 1200;

   [OutputCache(Duration = TwentyMinutes, VaryByParam = "*", VaryByContentEncoding = "gzip;deflate", VaryByCustom = "Scheme")]
   public ActionResult Index()
   {
       string variablesFromDatabase = "these came from the database";

       string lessFileContents = "this was read from the disk";

       string content = Less.Parse(string.Concat(variablesFromDatabase, lessFileContents));

       SetEtag(content);

       return Content(content, "text/css");
   }

   private void SetEtag(string content)
   {
       string acceptEncoding = Request.Headers["Accept-Encoding"];

       string value = string.Concat(content, acceptEncoding);

       Response.AppendHeader("etag", string.Format("\"{0}\"", Crypto.Hash(value, "md5")));
   }
}


Correct procedures to detect and correct outliers for aggregated/SKU time series

Question: Background
I am currently working with sets of product sales time series at SKU-level for a FMCG company. Data are available in a weekly format for multiple years and sales data for hundreds of products are available at any single point of time. Products are very similar in nature. They are seasonal with moving seasonal components (easter etc.) and generally have a product life of less than 2-3 years. However, not all products share the same sales pattern, some even have intermittent demand. There are almost no labels (or additional information) apart from the original time series.
Purpose
The mission is to develop a methodology to remove promotional effect and real outliers of historic data at SKU-level to create baseline sales history for other purposes.
Concerns
Without much industrial experience I am struggling to figure out a good way to tackle - nor did I manage to find literatures that specifically address this issue. I am not even quite sure about where it should start - should the first steps be looking at SKU sales or the aggregated sales?
Products are launched consistently throughout the year and their life time are so short that there is almost always not enough historical data for a single product. In the light of this and due to lack of information, the current methodology aims to identify, and correct the outliers based on a single aggregated time series and corrects time series at SKU-level based on results from that. The first part is done in an interesting fashion that I am not sure whether the results are actually statistically valid and I believe it is unlikely to be better than simply using regression to estimate the parameters. However, how are we going to adjust the data at SKU-level based on the corrected data at aggregated-level?
I would like to kindly enquire what kind of procedures do businesses / would you take and reasonings behind it. Furthermore, are there any literatures that might be useful for this? Please advice me if there is anything else that you need to know or would like to be clarified.
Thank you.
Comment: Thank you for going to the effort of crafting a readable, informative question. Welcome to our site!
Comment: I can not imagine how adjustments/price promotion/outliers  developed on an aggregate could be efficiently applied to the dis-aggregates. My experience tells me that adjustments can be made at both levels prior to reconciliation. Reconciliation is normally done in either a top-down or a bottoms-up approach using forecasting accuracy to determine/suggest which gambit us best.
Comment: Very well developed question. What you are after is called top-down or bottom up forecasting. There is a nice introductory textbook on this topic by Hyndman et al. - Forecasting principle and practice. [This](https://www.otexts.org/fpp/9/4) covers this topic. With regards to outlier correction and promotion response, there are few specialist in this website, I hope they see your question and respond. I have added few tags that might get their attention.
Comment: I must admit that I feel a bit overwhelmed to see three regulars commenting in my every first post - It's a great pleasure to meet you all and @whuber , thank you so much for your warm welcome.
Comment: @IrishStat For the first part - If starting from (a huge set of) dis-aggregates of unique products in different stages of life cycles, what would be a good approach to identify the outliers? Would you suggest having a look at techniques such as pooling? (I've also started investigating automated packages in R). Thank you for sharing your great thoughts!
Comment: @forecaster Thank you for the introduction to the concept and editing! I actually had the book on my browser but never really started reading. I reckon now would be a good time!
Answer: I don't recommend pooling as there is no information suggesting a common model across the dis-aggregates. I would attempt to form a separate model for each dis-aggregate that incorporated seasonal effects and memory. Seasonal effects can be either based upon memory (ARIMA) or dummy seasonal factors. There may be level shifts or time trends in the data and/or some unusual data points due to anomalies or price/promotion effects. Weekly data can be effected by what day of the week holidays fall and the holidays themselves. Non-causal i.e. purely ARIMA approaches often fail to deal with weekly data because what we did last year at week i is different than what is done this year at week i. Each series (dis-aggregate) will have it's own story/pattern and one has to approach the problem with a many-faceted solution tool that can distinguish data generating functions and not simply fit a pre-specified model. I have been busy these many years (nearly 50) in trying to develop ever-better procedures. The way one approaches the identification of each model incorporating memory,dummies and user-specified causals can be (is) critical. I would suggest that you actually investigate both free procedures and commercial procedures to effectively solve this.
Comment: Thank you for your elaborative response. To examine and support issues you mentioned I think I will (learn and) use DTW to perform clustering for set of time series that the company thinks behave in a similar fashion.
Comment: That could be useful in segmenting the time series into similar groupings prior to performing the magic that I detailed above.


Php xmlrcp client get rtorrent info

Question: I need to create simple php script for getting some information of my rtorrent instance ...
i try a lot of code but i never give a responce ...
this is my last test
<code>ini_set('display_errors', 1);
error_reporting(E_ALL);

function do_call($host, $port, $request) {

    $url = "http://$host:$port";
    $header[] = "Content-type: text/xml";
    $header[] = "Content-length: ".strlen($request);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
        return $data;
    }
}

$host = '127.0.0.1';
$port = 10001;
$request = xmlrpc_encode_request("system.listMethods()", null);
$response = do_call($host, $port, $request);
var_dump($response);
</code>
Do you have simple working test code ?
Answer: This is a bug within PHP-XMLRPC.
However you can replace your line:
<code>$data = curl_exec($ch);
</code>
With:
<code>$data = xmlrpc_decode(str_replace('i8>', 'i4>', curl_exec($ch)));
</code>
This should work as expected.

Php xmlrcp client get rtorrent info


How call UINavigationControllerDelegate delegate method for rootViewController

Question: I am using below delegate method to show animation in my app.
func navigationController(_ navigationController: UINavigationController,
            animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController,
            to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?

But, above method is not getting call for rootViewController of navigationController.
Thanks for help in advance.
Comment: What is FromVC and toVC. Can you explain here? From what view to what view you want to navigate?
Comment: I am navigating from my loginVC/RegisterVC to myOneTimeVC. I am presenting MyOneTimeVC on LoginVC/RegisterVC. I want navigation transition called for MyOneTimeVC
Comment: Where are you implementing this method?  Are you properly setting the delegate for the UINavigationController?  How are you displaying MyOneTimeVC?
Comment: @ChrisAllwein I am presenting MyOnetimeVC. I am implementing this method in UINavigationControllerDelegate extension.
Answer: The method you're referring to is called to set up the transition animation.  However, the rootViewController is added to the navigationController without any animation since there is no previous view controller to transition from.  As a result, the delegate method is not invoked.
This is true even if you don't use the convenience initializer that specifies the rootViewController and instead push the rootViewController manually, specifying true for the animated: parameter.  You'll notice that even in this case, the navigationController pushes the rootViewController without animation (as evidenced from the navigationController(:,willShow:,animated:) call having the animated parameter set to false.
AFAIK, it is not possible to transition-animate the rootViewController.
An alternative solution might be to implement navigationController(:, willShow:, animated:), do a check to see if self.viewControllers.first == viewController and then manually animate the viewController.view.


Como enviar SMS gratuitamente utilizando PHP?

Question: Gostaria de saber se existe alguma forma de enviar SMS gratuitamente para celulares do Brasil.
Já vi alguns sistemas PHP com esta função, e gostaria de ter esta função no meu sistema também.
Comment: Há diversas soluções pra isso, desde pagas até gratuitas, por isso a pergunta é 'ampla demais'.
Comment: Ano que vem (2014) nas eleições, vai ter muita gente procurando essa resposta.
Comment: é simples: precisa dum serviço externo para fazer isso. talvez limite a pergunta para saber quais serviços existem, ou escolhe um serviço e pergunte como usar?
Answer: Antigamente dava pra mandar usando o Google Agenda, porém sempre para o mesmo número verificado, usei por um tempo pra sistema de alertas.
Se precisar realmente enviar SMS a partir do seu sistema, existem duas alternativas, ambas pagas:
1) Usar um serviço de mensageria que irá te cobrar por mensagem. Existem vários, no Brasil conheço apenas o zenvia.com.br (não é marketing, não tenho relação com a marca).

Nessa caso, você faria a integracão com o sistema da empresa e enviaria as mensagens via Internet (API). Eles tem módulos para vários sistemas, e bibliotecas prontas para várias linguagens, devidamente documentadas.

2) Usar um modem acoplado ao servidor

Solução apenas quando existe servidor local, eu uso e sai muito barato. Usando um modem 3G, para instalar no Linux geralmente é complexo. Depois de tudo configurado, chamo via CLI, usando
<code>echo '$mensagem' | sudo gammu sendsms TEXT $numero -unicode
</code>
Comment: Fiz uma busca rápida aqui, e você pode usar o aplicativo [SMS Gateway](https://play.google.com/store/apps/details?id=eu.apksoft.android.smsgateway&hl=en) em um smartphone Android. Ele expõe uma API HTTP que você pode chamar para mandar os alertas. Aí seria só uma questão de deixar o telefone constantemente ligado, e expor ele através do seu roteador, possivelmente usando um serviço de DNS dinâmico. Essa é uma opção bem *low budget*, e não sei quanto a confiabilidade.
Comment: No Caso do Zenvia, eles tem módulos para vários sistemas, e bibliotecas prontas para várias linguagens, devidamente documentadas.
Usando um modem 3G, pra instalar no linux geralmente é complexo, depois de tudo configurado, chamo via CLI, usando

echo '$mensagem' | sudo gammu sendsms TEXT $numero -unicode
Comment: Interessantes estas opções. De acordo com minhas pesquisas existe um forma de utilizar o Google Voice. Conheçe algo sobre ele?
Comment: Achei bastante interessante a sua ideia. Já que disse que utiliza dessa forma poderia nos mostrar como em mais detalhes?
Comment: Muito bom @MarcoAurélio, vou pesquisar a respeito. Muito obrigado.
Answer: Para enviar SMS via código o que acontece basicamente é que você usa uma API de alguma operadora que ao enviar sua solicitação para a mesma ela vai acionar um aparelho celular que vai enviar seu SMS.
Não conheço nenhum serviço desse tipo nacional gratuito, somente pagas basta entrar em contato com uma operadora de sua preferência que eles vão liberar uma documentação para você começar usar(pagando o devido custo claro).
Caso queira serviços internacionais é possível encontrar alguns gratuitos, basta perguntar pro nosso amigo google.
Comment: Só eu acha que mandar buscar no google sem citar exemplos não responde a questão?
Comment: Você pode tentar o http://www.twilio.com/ . Da última vez que verifiquei eles mandavam mensagens para o Brasil.
Comment: Dataol, atualmente o Google Voice não está permitindo esse envio de sms via API. E como você falou nacional imaginei que ele não serviria. Ate onde eu sei nacional e gratuito não existe =/
Comment: Prezado Guerra. De acordo com minhas pesquisas existe um forma de utilizar o Google Voice. Conheçe algo sobre ele?
Comment: Ok @MarcoAurélio vou verificar
Comment: Traquilo @ViníciusFrança, obrigado pelo comentário


Additive Mixed Models: residual check for count response variable

Question:
Hi,
The response variable is the count of daily number of physician visits of one specific disease.(y usually has the value for example of 4,5,6,10...,26).
A standardized residual plot is produced from:
> plot(fit$lme)

My model :
model <- gam(sum ~ s(Time,k=20) + s(RSK,k=10) + as.factor(DOW)
         data = mydata,family = quasipoisson, method ="REMl")

The plot shows the standardized residuals versus fitted values for the fit of my additive mixed model. It seems that it is not reasonable accordance with the model assumptions? But I don't know how to avoid this pattern for the count data.
The QQplot see also below.
############## UPDATES######
############################
Follwing the advices from @Gavin Rootograms: a new way to assess count models, I checked the Rootgram.

It seems that the issue here is not to choose beween Negative Binomial or Poisson. While the Rootgram from both distribution looks alike.  Both over predicts und under predicts among particular y-value.
The response actually only concretely take several certain values. see the plot of ECDF.

So my question would be should another model here be adopted like multi-categorial.
if only a small number of response values 1,...,4,5,6,...15... is observed, should we consider model for multi-categorial data (see Tutz, 2000)
Any help would be much appreciated!
Answer: If you mean the lines of points, you can't avoid these kinds of patterns; they are due to the integer nature of the response. You could use PIT residuals, but I haven't implemented them {gratia} and which aren't available in {mgcv} either.
As another diagnostic plot, consider the rootogram, which is available in the {countreg} package (on R-Forge) with a rudimentary implementation also available in the development version of {gratia} on GitHub (though you'll likely have to refit using gam() as I haven't written methods for gamm() fits yet. I would strongly advise you to refit this using gam() anyway, to avoid having to fit the model via PQL, which removes many options for model comparison and may not be as robust as using gam() and method = "REML").
Comment: Hi Gavin, thanks a lot for the advices! I applyed the Rootogram like you suggested, which bring me another issue: the response only take severval certain values. As I read several books and come across this multi-categorial model als alternative for possion count data, which confused me a lot. Based on this  invariably  patterns and the discrete nature of the response, should I be caucious and take totally different model assumption for the count data?


Prove $\frac{n}{n+1}<\frac{n+1}{n+2}$

Question: How can we prove the following inequality: $$\frac{n}{n+1} < \frac{n+1}{n+2}$$
I understand how to do proof by inductions and contradictions, but I am getting stuck on this question.
My proof would start out with its base case.
$n= 0$;
$0/1 < 1/2$ holds true;
I.H.: this following equality holds true for a natural number $n$.
We must now show that it also holds true for $n+1$:
$$\frac{n+1}{n+2} < \frac{n+2}{n+3}$$
From here I am stuck. We know the first term is greater than $n/n+1$ from our IH, but it gives no evidence that $\frac{n+2}{n+3}$ is greater than $\frac{n+1}{n+2}$
I see no correlation on how to prove this using the IH. Am I missing something?
Comment: By the way, the induction hypothesis does **not** say "Assume that the [property] holds for **all** natural numbers $n$"; it says "Assume that it holds for some $n \in \mathbb{N}$". There is a subtle but important difference.
Comment: Very true. Thank you.
Answer: Replace n+1 with m. Then it boils down to showing
$$\frac{m-1}{m} < \frac{m}{m+1} \to m^2 - 1 < m^2$$
QED
Answer: As an alternative to induction, note that
$$
\frac{n}{n+1}=1-\frac{1}{n+1}<1-\frac{1}{n+2}=\frac{n+1}{n+2}.
$$
Answer: Note that for $n\ge 0$
$$\frac{n+1}{n+2}-\frac{n}{n+1}=\frac{(n+1)^2-n(n+2)}{(n+2)(n+1)}=\frac{1}{(n+2)(n+1)}\gt 0.$$
Answer: Another proof "without induction":
$$ n(n + 2) = n^2 + 2n < n^2 + 2n + 1 = (n+1)^2.$$
Divide both sides by $(n + 1)(n + 2)$:
$$ \frac{n}{n + 1} < \frac{n+1}{n+2}.$$
If you want to be a stickler for detail,
you could use induction to prove the first inequality.

Prove $\frac{n}{n+1}<\frac{n+1}{n+2}$


Is $\lim_{x\to 0}\dfrac{\ln(x+a)}{x}$ a notable limit?

Question: I'm trying to solve this limit:
$\displaystyle\lim_{x\to0} \dfrac{2e^x - \log_3(x+3) -2}{x} $
rearrangement leave us to:
$\displaystyle\lim_{x\to0} 2 \cdot\dfrac{(e^x -1)}{x} - \lim_{x\to0}\dfrac{\ln(x+3)}{\ln 3 \cdot x}$
$\displaystyle2 - \dfrac{1}{\ln 3}\cdot \lim_{x\to0}\dfrac{\ln(x+3)}{x}$
is the $\displaystyle\lim_{x\to0}\dfrac{\ln(x+3)}{x} = 1$ ?
I know that  $\displaystyle\lim_{x\to0}\dfrac{\ln(x+1)}{x} = 1$ is a notable limit, but I'm not sure about  $\displaystyle\lim_{x\to0}\dfrac{\ln(x+a)}{x} = 1$
Comment: "Notable limits" are whatever your textbook says. This one poses no problem: $\lim_{x\to0}\frac{\log(x+a)}{x}$ doesn't exist for every $a>0$ *except* for $a=1$. Why doesn't it exist? Because the numerator goes to $\log a\ne0$ and the denominator goes to $0$. The limit is either $\infty$ or $-\infty$ when going to $0$ from the left or from the right.
Comment: Well, $\lim_{x \to 0} \ln(x+a) = \ln a$...
Comment: Yes I understand that. It is one more wrong solution in my exercises book where the solution for limit submitted in the question is $2 - \dfrac{1}{ln 3}$.
Comment: @Jorge There's probably a typo and it should have been $\log_3(x+1)$.
Comment: I think the same. Thanks.
Answer: using  L'Hospital rule $\lim_{x\to 0}\dfrac{\ln (x+1)}{x} =1$ because if $x=0$ , it is in undetermined form i.e. $(0/0)$ form but $\lim_{x\to 0}\dfrac{\ln (x+a)}{x}$ is not in $(0/0 )$  form so it doesn't exist


condition for a set to be finite given a map between this set and a finite set

Question: Suppose $X$ is a finite set. Consider the set $Y$. If we find a surjection $f: X \to Y $, does it follow that $Y$ is also a finite set ?
Comment: Yes. You may want to use the "finite" choice (can be proved by induction) to prove "surjective implies right-invertible" in the finite case. In the end you get an injection from $Y$ to $X$ whose range is finite (since it's a subset of finite set, namely $X$)
Answer: Yes it does.
 By definition of function for each $x\in X$ there is only one $y\in Y$ such that $y=f(x)$. so the number of elements of $Y$ is less than or equal to the number of elements of $X$. (because of surjection).
Comment: Great! I am trying to show that if $G$ is a finite group, then $G/H $ must be finite two, where $G/H$ is the set of cosets of $H$: If I define a map $f: G \to G/H $ by $f(g) = gH $, then is $f$ surjective ?
Comment: yes it is surjective
Comment: G/H must be finite *too*
Comment: because $f$ is surjective, then $G/H$ must be finite correct?
Answer: Yes. As $f$ is a surjection, for every $y\in Y$ there is a $x\in X$ with $f(x)=y$. Hence, $|Y|\leq|X|$ and $Y$ is finite.
Answer: Hint: If $X$ is finite and $f:X\to Y$ is surjective, then show that $|X|\ge |Y|$.


Attribute Error at / 'tuple' object has no attribute 'get' in Django

Question: I add my index.html file to templates directory and then change all the src and etc but I receive this error what should I do for it:
D:\Django\2\blog_project\venv\Lib\site-packages\django\core\handlers\exception.py, line 55, in inner
                response = get_response(request)
                               ^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Django\2\blog_project\venv\Lib\site-packages\django\utils\deprecation.py, line 136, in __call__
            response = self.process_response(request, response)
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ …
Local vars
D:\Django\2\blog_project\venv\Lib\site-packages\django\middleware\clickjacking.py, line 27, in process_response
        if response.get("X-Frame-Options") is not None:
               ^^^^^^^^^^^^ …
Local vars

I try to run a html page in my django project but i receive an error
Comment: Share the corresponding view.
Answer: It appears that you return a tuple in your view, so likely something like:
def my_view(request):
    #                                        trailing comma 🖟
    return render(request, 'name-of-some-template.html', {}),
you should remove the trailing comma.


MobileFirst and Ionic Push notification callback

Question: I have an Ionic project and I added a push notification callback handler as explained in official documentation (my expectation is to have some alert when inside the app and a notification arrive), but it is never invoked.
<code>  WL.Client.Push.registerEventSourceCallback(
            "myPush",
            "PushAdapter",
            "PushEventSource",
            pushNotificationReceived);
</code>
Here the question is where I have to place the pushNotificationReceived function to be called ? I try in index.js and inside the controller as a function, but I do not have success.
Thank for help
Comment: The callback should be defined within the js where you register the callback .Are you receiving push notifications in your device ? Is it that , the notification is not being displayed within the callback?
Comment: Is this really different than your existing question? http://stackoverflow.com/questions/35549330/mobilefirst-push-notification-doesnt-work-if-app-removed-from-recent-list
Comment: Yes, the other question is about the recent list cleaning, this one is when the app is opened and in foreground.
Answer: Have you reviewed the sample application for push notifications?.
The sample demonstrates implementation of push notifications APIs. https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/notifications/push-notifications-overview/push-notifications-in-hybrid-applications/event-source-notifications-in-hybrid-applications/
See the supplied main.js file: https://github.com/MobileFirst-Platform-Developer-Center/EventSourceNotifications/blob/release71/apps/HybridEventSource/common/js/main.js
Comment: Hi Idan, the answer is yes, and the sample is working as expected, but I'm not able to replicate it with Ionic framework. The callback function is not called.
Answer: You have to include callback function in ionic inside the app.js file after "Successfully connected with mobile first server".
<code>     WLAuthorizationManager.obtainAccessToken().then(
            function (response) {
              //alert("successfully obtained a token from the server");
                MFPPush.initialize (
                   function(successResponse) {
                       //alert("Successfully intialized");
                        MFPPush.registerNotificationsCallback(notificationReceived);
                   },
                   function(failureResponse) {
                        console.log("Failed to initialize");
                   }
                );
                MFPPush.isPushSupported (
                    function(successResponse) {
                       //alert("Push Supported: " + successResponse);
                    },
                    function(failureResponse) {
                        console.log("Failed to get push support status");
                    }
                );
                MFPPush.registerDevice(
                    function(successResponse) {
                        //alert("Successfully registered");
                    },
                    function(failureResponse) {
                        console.log("Failed to register");
                    }
                );
                function notificationReceived(message) {
                    alert(JSON.stringify(message.alert));
                }
         },
         function(response) {
            //alert("res"+JSON.stringify(response));
            console.log("Unable to obtain a token from the server: " +            JSON.stringify(response));
            if(JSON.stringify(response.status) ==  403){
                 console.log("The Application is disabled on this Device");
                 ionic.Platform.exitApp();
            }
        }
     );
</code>


Removing the icon from a WPF window when running outside of Visual Studio

Question: I've used the code in Removing Icon from a WPF window to remove the icon from the window of an application (using the attached property answer) and this has worked a treat, when run via Visual Studio 2010. When the application is run normally, the icon still appears.
The window has no icon assigned to its Icon property, the application does, however, have an icon defined in its properties (Application > Resources > Icon) which is the one that's being shown as the window icon.
How can I resolve this difference in behaviour so that the icon isn't shown when the application runs outside of Visual Studio 2010?
Comment: I used the code from the referenced answer in a small WPF application's MainWindow to remove the Icon. It works in Visual Studio and when run from my project's Bin\Debug folder. Is there some other small detail that could affect this?
Answer: I did a bit of digging; there's a StackOverflow question that addresses your issue. Ironically, this fix only works outside of Visual Studio.
Relevant Parts of the Answer (by Zach Johnson):
It appears that WS_EX_DLGMODALFRAME only removes the icon when the WPF window's native Win32 window does not have an icon associated with it.  WPF (conveniently) uses the application's icon as the default icon for all windows without an explicitly set icon.  Normally, that doesn't cause any problems and saves us the trouble of manually setting the application's icon on each window; however, it causes a problem for us when we try to remove the icon.
Since the problem is that WPF automatically sets the window's icon for us, we can send WM_SETICON to the Win32 window to reset its icon when we are applying WS_EX_DLGMODALFRAME.
const int WM_SETICON = 0x0080;
const int ICON_SMALL = 0;
const int ICON_BIG = 1;

[DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr SendMessage(
    IntPtr hWnd,
    int msg,
    IntPtr wParam,
    IntPtr lParam);

Code to remove the icon:
IntPtr hWnd = new WindowInteropHelper(window).Handle;
int currentStyle = NativeMethods.GetWindowLongPtr(hWnd, GWL_EXSTYLE);

SetWindowLongPtr(
    hWnd,
    GWL_EXSTYLE,
    currentStyle | WS_EX_DLGMODALFRAME);

// reset the icon, both calls important
SendMessage(hWnd, WM_SETICON, (IntPtr)ICON_SMALL, IntPtr.Zero);
SendMessage(hWnd, WM_SETICON, (IntPtr)ICON_BIG, IntPtr.Zero);

SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0,
    SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);

It works only when the app is run outside of Visual Studio.
Comment: Assuming you  replace GetWindowLongPtr and SetWIndowLongPtr with `GetWindowLong` and `SetWindowLong` (ORing an IntPtr and an int, as done with `currentStyle | WS_EX_DLGMODALFRAME` **does not work**. Unfortunately this code doesn't work for me. Did you test it prior to placing the answer? (Also, it won't compile as it stands, there's no code in either this, or the referenced answer, for `NativeMethods.GetWindowLongPtr`)
Answer: Maybe the Shell integration library is an option for you? It contains this WindowChrome class to customize the non-client area, allowing you to leave out the icon.


How to lock UITextField input to accept only ONE letter from A to Z on SWIFT

Question: I have an UITextField named "TextField" and I want to get only one letter form A to Z. User will not enter more than 1 letter on this TextField. How can I do this?
Comment: Please tell us what you have you tried.
Answer: In order to control user input into a UITextField, you must implement the UITextFieldDelegate protocol in your controller.
UITextFieldDelegate Documentation
In particular, look into textField(_:shouldChangeCharactersInRange:replacementString:) and return a Bool value that allows the character or not.


Calling a Web API to get particular information using DeserializineAsync (JSON/ C#)

Question: I'm trying to call a web API (JSON/Csharp Console application) I did the same steps in the dotnet : https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient
However, when I'm trying to get only the property "NAME1", an error came up : The JSON value could not be converted to System.Collections.Generic.List. I could get all the json information but when Deserializing the result for getting only particular data such as NAME1 it doesn't work.
public partial class Result
    {
        public List<GAZETTEER_ENTRY> GAZETTEER_ENTRY { get; set; }
    }
    public partial class GAZETTEER_ENTRY
    {
        public string ID { get; set; }
        public string NAME1 { get; set; }
    }
class Program
    {

        private static readonly HttpClient client = new HttpClient();

        static async Task Main(string[] args)
        {
            await RunAsync();
        }
        private static async Task RunAsync()
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
   new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("key", "xxxxxx");
            var streamTask = client.GetStreamAsync("https://api.os.uk/search/names/v1/find?query=coventry&fq=LOCAL_TYPE:Hospital");
            var data = await JsonSerializer.DeserializeAsync<List<GAZETTEER_ENTRY>>(await streamTask);

            foreach (var item in data)
            {
                Console.WriteLine(item.NAME1);
            }

This is the JSON data:
  "header" : {
    "uri" : "https://api.os.uk/search/names/v1/find?query=coventry",
    "query" : "coventry",
    "format" : "JSON",
    "maxresults" : 100,
    "offset" : 0,
    "totalresults" : 4134
  },
  "results" : [ {
    "GAZETTEER_ENTRY" : {
      "ID" : "osgb4000000074568994",
      "NAMES_URI" : "http://data.ordnancesurvey.co.uk/id/4000000074568994",
      "NAME1" : "Coventry",
      "TYPE" : "populatedPlace",
      "LOCAL_TYPE" : "City",
      "COUNTRY" : "England",

    }
  }, {
    "GAZETTEER_ENTRY" : {
      "ID" : "osgb4000000019401618",
      "NAMES_URI" : "http://data.ordnancesurvey.co.uk/id/4000000019401618",
      "NAME1" : "Coventry Street",
      "TYPE" : "transportNetwork",
      "LOCAL_TYPE" : "Named Road",
      "COUNTRY" : "England",

    }
  }, {
    "GAZETTEER_ENTRY" : {
      "ID" : "osgb4000000073321650",
      "NAMES_URI" : "http://data.ordnancesurvey.co.uk/id/4000000073321650",
      "NAME1" : "Coventry",
      "TYPE" : "transportNetwork",
      "LOCAL_TYPE" : "Railway Station",
      "COUNTRY" : "England",

    }

Answer: Your response classes should be like
public class SearchResult
{
    public Header header { get; set; }
    public List<Result> results { get; set; }
}

public class Header
{
    public string uri { get; set; }
    public string query { get; set; }
    public string format { get; set; }
    public int maxresults { get; set; }
    public int offset { get; set; }
    public int totalresults { get; set; }
}

public class Result
{
    public GAZETTEER_ENTRY GAZETTEER_ENTRY { get; set; }
}

public class GAZETTEER_ENTRY
{
    public string ID { get; set; }
    public System.Uri NAMES_URI { get; set; }
    public string NAME1 { get; set; }
    public string TYPE { get; set; }
    public string LOCAL_TYPE { get; set; }
    public string COUNTRY { get; set; }
}

and the deserialize should be
var data = await JsonSerializer.DeserializeAsync<SearchResult>(await streamTask);

and access NAME1 of nth result
data.results[0].GAZETTEER_ENTRY.NAME1

if you find difficulty in comparing classes and json response, You can simply copy the json response and goto VS -> edit-> paste special -> paste json as classes. VS will auto generate classes for you.
Comment: Thank you. This solution works pretty well!
Answer: Try deserializing the json using this RootObject model:
public class RootObject
{
   public ResultObject[] results { get; set; }
}

public class ResultObject
{
   public GazetteerEntryObject GAZETTEER_ENTRY { get; set; }
}

public class GazetteerEntryObject
{
   public string NAME1 { get; set; }
}

Do it this way
var data = await JsonSerializer.DeserializeAsync<RootObject>(await streamTask);

To retrieve the names, do it like this:
var names = data.results.Select(x => x.GAZETTEER_ENTRY.NAME1);

Comment: the "names" is still null


How to show event title and time in calendar block?

Question: I have create a view based on the template. The events are shown up properly as a link in the calendar block:

How to I add also the event name and time (similar to the month page)? i.e.:
Answer: Do you mean you would like to add the event name and time to the calendar you have provided on the top? If that's what you're asking, I don't think you can, and that is what the month page is there for. In Views, can you make the month page a block instead and place that wherever you need it?
Comment: Go to Structure -> Views -> Calendar and then click on the tab at the top under "Displays" that says "Month." Next, click the "+Add" tab and select Block. This should create a block that is a copy of the Month page, and then you can put this block in whatever region you'd like.
Comment: Ah, then I'm _guessing_ it's not being styled then, and you would maybe have to manually style it (or check the various settings of the other one and the new block to see if there are any custom CSS selectors you should add. Otherwise, you _may_ be able to style it yourself. Unfortunately I don't have access to a site at the moment where I can play around and experiment with Calendar, or I'd look into it further.
Comment: How can I _"make the month page a block"_?
Comment: Tried. The newly created block shows nothing in preview.
Answer: Go to Structure -> Views -> Calendar View and then under Displays click Block. Next, under heading Format click Settings next to Format: Calendar and choose No for Display as mini calendar


Existe alguma forma de fazer @bind-... a uma propriedade readonly em blazor?

Question: Existe alguma forma de fazer @bind-... a uma propriedade readonly em blazor?
<MyComponent @bind-Property="@ReadOnlyProperty"  />

@code{

 public readonly bool ReadOnlyProperty= true;
}

Severity  Code    Description Project File    Line    Suppression State
  Error CS0191  A readonly field cannot be assigned to (except in a
  constructor or a variable initializer)
Answer: Como você mesmo disse, está usando uma propriedade readonly, que sua principal característica é ser imutável. No blazor o @bind serve justamente para alterar uma propriedade, esta é sua principal caraterística. Sem criar uma propriedade adicional que não seja somente leitura, eu não vejo forma de conseguir o que você deseja. Espero ter ajudado.


Arrow functions bound at definition time

Question: I'm learning es6 arrow functions, how I can get this test to pass?
describe('arrow functions have lexical `this`, no dynamic `this`', () => {

it('bound at definition time, use `=>` ', function() {
    var bound = new LexicallyBound();
    var fn = () => getFunction();

    assert.strictEqual(fn(), bound);
});

Comment: What's `LexicallyBound`? What's `getFunction`?
Comment: `class LexicallyBound {

    getFunction() {
        return () => {
           return new LexicallyBound();
        }
    }

     getArgumentsFunction() {
            return function() {return arguments}
         }

    }`
Comment: Use "edit" to improve the question, not comments. And based on that definition, you should be getting a `ReferenceError` in your code when you try to call `getFunction` without `bound.` in front of it.
Comment: Thanks i tried edit - it wouldnt let me - too much code
Comment: That doesn't mean you should post it as a comment. It means you should provide more context and explanation.
Comment: Im not sure of the context or explanation, thats why i posted my question in the first place.
Answer: Since the function returned by getFunction doesn't do anything to demonstrate that it closes over this, I don't think it's of any use to use you here.
If the goal is to prove that arrow functions are lexically bound (that is, that they close over this), then:
it('is lexically bound', function() {
    const obj = {
        arrow: () => {
            return this;
        }
    };
    assert.strictEqual(obj.arrow(), this);
});

If arrow didn't close over this, it would return obj, not the current value of this in that callback.
Example:

function it(label, test) {
  try {
    test();
    console.log(label, "OK");
  } catch (e) {
    console.log(label, "FAILED", e.message);
  }
}
const assert = {
  strictEqual(a, b) {
    if (a !== b) {
      throw new Error("a == b was false");
    }
  }
};

it('Arrow function is lexically bound', function() {
  const obj = {
    arrow: () => {
      return this;
    }
  };
  assert.strictEqual(obj.arrow(), this);
});

it('Non-arrow function is not lexically bound', function() {
  const obj = {
    nonarrow: function() {
      return this;
    }
  };
  assert.strictEqual(obj.nonarrow(), obj);
});


Generated group acts without fixed points

Question: A friend of mine gave me a problem and while trying to solve it I came up with a question/conjecture:
Let $M$ be a complete oriented Riemannian manifold and let $S\subset ISO_{+}(M)$ be a collection of orientation preserving isomorphisms from $M$ to $M,$ such that no $\phi \in S$ has fixed point. Does it follow that the group generated by $S$ acts without fixed points on $M$?
If this is not true in general, what are some "natural\easy" assumptions for it to be true? Simply connectedness? Non-positive sectional curvature? Do restrictions on the dimension help?
Thanks in advance.
EDIT: As was pointed out by Jason de Vito the general form was clearly wrong.
So I'd like to restate my question now with the restriction that the sectional curvature is bounded above by a non positive constant, i.e. $K_M\leq \delta\leq 0.$
Answer: It's certainly not true in general.  Consider, for example, the $S^1$ action on $S^3$ given by $z(w_1, w_2) = (zw_1 ,z^2 w_2)$.  Here, I am thinking of $S^1$ as the unit complex numbers, and I am thinking of $S^3$ as $S^3 = \{(w_1, w_2)\in \mathbb{C}^2: |w_1|^2 + |w_2|^2 = 1\}.$
Take $S = \{i\}$.  Then the element $i\in S^1$ doesn't fix any points: if $iw_1 = w_1$, then $w_1 = 0$.  Likewise, if $-1 w_2 = w_2$, then $w_2 = 0$.  But $(w_1,w_2) = (0,0)$ is not in $S^3$.
On the other hand, $i^2 = -1$ does fix points.  In fact, $-1(0,w_2) = w_2$ for any $(0,w_2)\in S^3$.
Note that $S^3$ is simply connected.  If you also want the group to be simply connected, instead, just replace all uses of the word "complex" above with "quaternionic".  This gives an action of $S^3$ on $S^7$ for which $S= \{i\}$ doesn't fix anything, but $i^2 = -1$ does.
I am not aware of any nice conditions which guarantee what you want, other than trivial things like "The whole group acts fixed point free" or something like that.  I don't think restricting the dimension will count because you can now consider actions of $S^3$ on $S^7 \times M$ where $M$ is your favorite manifold (and $S^3$ acts trivially on it).  One will still have $i$ fixing nothing, but $-1$ fixing even more.


Finding the right dimensions of a physics-motivated equation

Question: I have been trying to find the right dimensions of some functions in the equation
$$\begin{cases}-\rho U\cdot \nabla u = -\nabla p + \nabla^2u \\
\nabla \cdot u = 0 \end{cases}$$
as seen here, in this Wikipedia article about the Oseen equations.
$u$ and $U$ are two velocities, which makes me think they are both vectors of the same dimension $d$ (the dimension we are working on) and they depend on the spatial coordinates (and maybe on time as well). So I think $u, U: \mathbb{R}^d\to \Bbb{R}^d$ or $u,U:\Bbb{R}^{d+1}\to\Bbb{R}^d$. $p$ is the pressure, so I would say it is a scalar function that depends on the spatial coordinates as well, but not on time, so $p: \Bbb{R}^d \to \Bbb{R}$.
I believe my struggle has to do with the fact that I don't know what are the meanings of the operators in the context they are being used.
If $u,U$ and $p$ have the dimensions I think they have, then  $\nabla \cdot u$ is the only thing that I understand. What does the gradient, $\nabla u$, mean? When $u$ is scalar, $\nabla u$ is a vector. What if $u$ is a vector already? Is $\nabla u$ a matrix?
While trying to understand what is going on I read about dyadics in Wikipedia. It felt like it could make sense here, but then what is the meaning of $U\cdot \nabla u$, if $U$ is a vector and $\nabla u$ is a matrix?
And of course, $\nabla^2$ which I know is the Laplace operator, with which I am also familiar when applied to a scalar function. If $u$ is a vector, then what is $\nabla^2 u$? Is it a vector as well? I think it should be, in order to be summable with $-\nabla p$...
If anyone could point me to something to read/learn in order to be able to understand this, I would be glad. The problem is, I don't even know where to go looking for answers.
Comment: Ah no, I'm pretty sure that $U\cdot \nabla u$ should be $\sum_i U_i(\frac{\partial}{\partial x_i} u)$, where $U_i$ is the $i$th component of $U$.
Comment: Look I could be completely wrong, I've never seen a proper definition of gradient of vectors, but based on my experience with similar confusing notation in my physics classes, this is my interpretation of what they are likely to have meant.
Comment: My interpretation based on my experience with physics, is that $\nabla u$ should be thought of as a "vector of vectors," with the $i$th component being the $i$th partial of $u$. Then $U$ is a vector of scalars, so you can take the dot product $U\cdot \nabla u$ to get a vector. However, I'm not *entirely* sure that this is what was intended, but that certainly makes all the dimensions work. (Probably you need to restrict to position partials if this depends on time?)
Comment: @jgon restricting the $\nabla$ to just the spatial coordinates is common practice, I read about it on my quest to understand this... Thinking of $\nabla u$ as a vector of vectors then the $i$th vector of $\nabla u$ would be the divergence of the $i$th component of $u$?
Comment: No, the $i$th vector of $\nabla u$ would be the $i$th partial of $u$, i.e. $\frac{\partial}{\partial x_i} u$.
Comment: Also divergence can't be taken of scalars, and divergence is a scalar not a vector.
Comment: @jgon I meant gradient, not divergence; sorry. Then you say that $U \cdot \nabla u$ would have, as $i$th component, $U \cdot \frac{\partial}{\partial x_i}u$?
Comment: $\nabla \bf{u}$ is a tensor quantity, represented by an $n \times n$ array where $n$ is the length of the vector $\bf{u}$, the velocity vectors are your usual vectors whose components are the derivatives of spatial components wrt time, that is $u_i = \frac{\partial x_i}{\partial t}$ (the same is true for $\bf{U}$, though its the flow of the surrounding fluid far from the object). The quantity $-\nabla p$ is a vector as you suspect since $p$ is a scalar function of the spatial variables.
Comment: A neat thing about the quantity $\nabla \bf{u}$ is that it has a lot of information about $\bf{u}$ rolled up into it, if you take the trace of this matrix it yields the divergence of $\bf{u}$, if you anti-symmetrize it you will obtain a matrix of curl components. The term $\bf{U} \cdot \nabla \bf{u}$, is known as a convective term, the external flowing field $\bf{U}$ carries the "object" $\nabla \bf{u}$ along with it in the fluid.
Comment: @Triatticus very well, that does make some sense. What would then be the different components of the tensor $\nabla u $? I alright got what the diagonal components are. Also, I didn't quite get what you mean by "the external field $U $ carries the 'object' $\nabla u $ along with it in the fluid"... can you refer me to some reading material? I guess a couple of wikipedia articles could suffice (just enough for me to better understand what all this is). Thanks
Comment: A lot of this stuff comes up in continuum mechanics/fluid dynamics where the primary equations of motion are the Navier-Stokes equations. They would have a familiar looking form to the ones you posted. The tensor object will be made up of all combinations of derivatives of components of $u$, in the form $\frac{\partial u_i}{\partial x_j}$, it's very similar in structure to a Jacobian matrix.
Comment: As for the convective term, imagine it this way,say you drop some dye in clear shallow water, naturally the dye will spread out due to Brownian motion and density gradients. If the surrounding water is calm the dye will only diffuse (there is a diffusion term in the N-S equations not present in the ones you posted.). Now if the water has a flow to it, the spreading dye will be carried along as it spreads, this is the convective part, if you took successive snap shots the dye will have spread and moved along with the flow.
Answer: The nabla notation is rather abstract: its purpose is to act as shorthand in long expressions with partial derivatives. Think of $\nabla$ as a vector operator, which has components
$$ \vec\nabla = \left(\frac{\partial}{\partial_x}, \frac{\partial}{\partial_y}, \frac{\partial}{\partial_z}\right) $$
It does not matter to what kind of function you apply it, the effect is always
$$ (\nabla f)_i = \frac{\partial f}{\partial x_i} $$
The question is, what mathematical meaning can be given to the RHS for each particular $f$. If $f$ is a scalar, then each component of $\nabla f$ is a single real function, and together they make a vector (it would be inaccurate to say that each component is a scalar, because they don't transform as scalars under coordinate transformations) - this is called the gradient of $f$. If $\bf f$ is a vector, the partial derivatives act on each of its components independently (this is as if we multiply the vector $\bf f$ with the "scalar" $\partial/\partial x_i$), so each "component" of $\nabla \bf f$ is a triple of real numbers, and so long as you don't make any coordinate transformations, their combined structure can be adequately represented by a matrix - but be careful not to mix up row vectors with column vectors; you should think of the first one ($\nabla$) as column and the second one ($\bf f$) as row to get a matrix.
This way of multiplying vectors is referred to as an outer product to contrast it with the inner (a.k.a. dot) product, which involves summation over indices; in the latter, when the del operator is involved, as in $\nabla \cdot \bf f$, each $\partial/\partial x_i$ acts only on the corresponding $f_i$, and the end result is the sum of all those, a scalar called the divergence of $\bf f$ (in the matrix notation, this time the first is the row and the second is the column, to produce a $1\times 1$ matrix which can represent a scalar).
If you combine more than two vectors, some of which can be $\nabla$'s, it is very important also to keep track of what is multiplied with what, and in what way. Just as with ordinary vectors, $\bf (a\cdot b)c$ is very different from $\bf a(b \cdot c)$; the reason they are different is not that these multiplications aren't associative (they are); the reason is that the dot product is not the same kind of product as the product of scalar with vector (in fact, the latter is actually more like an outer product), so we can't just switch them around. With two nablas, for example, we can have
$$
(\nabla \cdot \nabla) {\bf f} = \left(\frac{\partial^2}{\partial_x^2} + \frac{\partial^2}{\partial_y^2}+ \frac{\partial^2}{\partial_z^2}\right) {\bf f} = \nabla^2 \bf f$$
This is an example of Laplace's operator, which is a scalar operator, acting on a vector - it just acts on each component separately, just as $a{\bf u} = (au_x, au_y, au_z)$ for any scalar $a$. But it is not the same thing as $\nabla (\nabla \cdot \bf f)$, the gradient of the divergence of $\bf f$.
In the case of $\bf U\cdot \nabla \bf u$, the order in which multiplications are carried out is irrelevant, so long as the correct type of multiplications is performed for each. But, as anyone who has done large matrix computations will tell you, it is more efficient to work with lower rank objects. It is also easier to visualize the intermediate objects that way. So I would argue that the better way to imagine it is
$$
({\bf U} \cdot \nabla) {\bf u} = \left(U_x\frac{\partial}{\partial_x} + U_y\frac{\partial}{\partial_y}+ U_z\frac{\partial}{\partial_z}\right) \bf u $$
The object in the parenthesis doesn't have components; it is the scalar (operator) $\bf U \cdot \nabla$; when multiplied with the vector $\bf u$ it produces a vector, and the multiplication proceeds according to the principles of multiplication of vector with scalar - each component of $\bf u$ gets acted on by that operator independently of the others.
In the matrix notation, this would be written with $\bf U$ as a row vector, $\nabla$ as column, and $\bf u$ as row. The result will be a row vector with the same structure as the row vector $\bf u$.
Comment: you can compute it either way, the result will be the same (and the matrix way of representing these multiplications makes it obvious that the result will be the same, because matrix multiplication is associative). That's why the parenthesis is often dropped, since it is unnecessary. What is important is that the $\bf U \cdot \nabla$ is an inner product (which involves summation over indices), while the $\nabla \bf u$ is what is called outer (or tensor) product; if you are not used to that, it is easier to do $\bf U \cdot \nabla$ first, then you are left with just scalar times vector.
Comment: Certainly it would be helpful to read some course on tensor calculus. There is not single answer to which and how much of it, that is very subjective. These days there are so many readily available, that all you have to do is pick one, and if you don't like it, try another. Start with an introductory one, then take it from there. If you find that it is insufficient, follow the references in it to find a more in-depth, or more rigorous, or more extensive one, whichever is needed. @RGS
Comment: One first skim through your answer makes me feel yours is the answer I have been looking for. Either way, why is $U\cdot \nabla u $ computed as $(U\cdot \nabla)u$ and not $U\cdot(\nabla u) $?
Comment: @RGS, I edited the answer to reflect some of the points I made in the comment above, and included a reference to wikipedia page for outer product, it may be helpful if you want to get a better idea of how this fits into the framework of linear algebra.
Comment: Thanks a lot for your efforts. I think I got it now. Either way, I will be exposed to these things a lot from now on. Would you say it is helpful if I read a bit about tensor calculus? In particular, do you think [this](http://www.ita.uni-heidelberg.de/~dullemond/lectures/tensor/tensor.pdf) pdf could be of help?


Is there a term for repeated melodies of different length

Question: Inspired Flight's "An Outlet" is an example of what I mean.

For the first few measures, a melody of 16 eighth notes is established in middle register (if I have it right: A E A E; A F G C; A E E- E; A F G C). Then, starting at 0:13, a repeated melody of 9 eighth notes is introduced in a higher register (F C A; F C A; D C A). Since 9 and 16 have no common factors, there are a lot of dynamics that arise during the theoretical 144 eighth notes that it takes for the two to reach a common repetition.
Although I didn't realize this kind of quasi-periodicity was happening until I attempted to transcribe it, it seems like a neat technique for creating texture. Does it have a name?
Answer: The technique is called "phasing", and is often attributed to Steve Reich, who wrote a series of phasing pieces.
Two examples of Reich's phasing pieces can be found in this answer: What's "species counterpoint"? Are there any other types of counterpoint?
A similar-sounding technique, but not "phasing", because it's not intended to be periodic is Terry Riley's "In C", which is considered to be the first Minimalist composition.

The broadest relevant terms are "polymeter" and "polyrhythm", which are discussed in Polymeter vs Polyrhythm
Comment: Worth noting that "Piano phase" from the same Reich has the name of this technique in its title!  https://en.m.wikipedia.org/wiki/Piano_Phase


Commit and push changes to GIT and upload changed files into external server

Question: What do I need to create script that allows me to commit and push changes to GIT repository and then upload files directly from local folder to external server by calling function through terminal.
I am trying to become more efficient and I want to handle changes much more easily.
Currently I am committing and pushing changes to my private GIT repo and then dragging & dropping files from local folder to server using FileZilla. This is not okay anymore for me.
It should include some kind of version number, that I could refer later on and it should also only upload files that were committed and pushed.
PS. I am working pretty much alone on this project.
Comment: What's the external server? Is it a ftp server (can only access through `ftp://` or can also access through `http://` or `https://`)?
Comment: @MarinaLiu-MSFT `ftp://`
Comment: Did you upload files to FTP server by git-ftp successful?
Answer: You can use git-ftp to depoly files from local git repo to your FTP server.
Detail steps as below:

Download and install git-ftp.
As the example to install for windows OS:
Download file  (such as .zip) -> unzip -> download curl (such as .zip) -> unzip -> (make sure git is installed ->) in bin folder of the Git installed directory (such as C:\Program Files (x86)\Git\bin) -> copy git-ftp into the bin folder -> open git bash under installed git directory (such as C:\Program Files (x86)\Git) -> execute curl https://raw.githubusercontent.com/git-ftp/git-ftp/master/git-ftp > /bin/git-ftp -> execute chmod 755 /bin/git-ftp.
You can also refer the instruction here.
Now the git-ftp is installed.
Add a folder  (such as repo) under the FTP directory to get the files from local repo.
Setup git-ftp for local git repo and deploy to FTP server.
git config git-ftp.url ftp://ftp-server/repo
git config git-ftp.user <username for login FTP server>
git config git-ftp.password <password for login FTP server>
git ftp init
git ftp push

Now all the files and the log (record the sha-1 when pushed to ftp server) are deployed to FTP server.


Range A = range A^tA

Question: let $A\in\mathbb{R}^{m\times n}$ with $m\geq n$. ¿Is it true that rank $A$ is equal to rank $A^tA$?.  How show this?
Thanks!
Comment: What you can prove is that $\text{range }A^\top=\text{range }A^\top A$.
Comment: Thanks! It is true, I duplicated the question. I am sorry, and thanks for the link with the answer.
Answer: Counterexample $$A={1\choose0}\quad A^TA=(1)$$
Actually, if $m\neq n$, then range of $A$ is subspace of $\mathbb R^m$ while range of $A^TA$ is subspace of $\mathbb R^n$.
Comment: sorry, it was rank, not range.
Comment: @user106306 Well, I think you found the answer now.
Comment: yes, thanks for your help and time. (Although, it is always good to see an alternative proof).

Range A = range A^tA


How to get type and value information from a template

Question: Currently I have a template class that looks like this:
template<typename T, T value>
struct MyStruct{
   /* Stuff */
};

To instantiate it currently I do something like this:
typedef MyStruct<int, 123> struct_def;

I would like to do something like this:
typedef typename MagicTemplate<123>::type struct_def;

Which would resolve to MyStruct<int,123>....
So my question is how can I get both type and value information from a template argument?
Edit:
It would also be nice if the solution could be used with pointers, member pointers, function pointers, etc...
For example:
struct OtherStruct{
  int memberA;
  long memberB;
  void foo(void);
};
static OtherStruct instance;

//Expands to MyStruct<memberA OtherStruct::*, &OtherStruct::memberA>
typedef typename MagicTemplate<&OtherStruct::memberA>::type struct_defA;
//Expands to MyStruct<OtherStruct*,&instance>
typedef typename MagicTemplate<&instance>::type struct_defB;
//Expands to MyStruct<void (OtherStruct::*)(void),&OtherStruct::foo>
typedef typename MagicTemplate<&OtherStruct::foo>::Type struct_defC;

Comment: Only in [C++17](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0127r2.html).
Comment: @Oktalist Ah....that makes sense....too bad I can't use that yet
Comment: I guess macro (dark) magic it is then....since this is not really possible
Answer: You can wait for C++17.
Or you punt; take a type T, and that T is expected to be compatible with an std::integral_constant.  This kicks the can one step further down the road; but shortcuts to make particular kinds of integral_constants are cleaner than ones making some bespoke template instance.
For example, I can make 123_k be of type std::integral_constant<int,123>.  Do MyStruct<decltype(123_k)>.
As  a bonus, your MyStruct now matches template<class...> which makes certain metaprogramming easier.
Comment: This is viable but somewhat clumsy because of the fact that you have to define an `operator""_k` for every single type you are interested in.....which is definitely an improvement, but I am going to have to deal with many many types here
Comment: @darth what types are you dealing with?  I mean, `size_t` for sizes, `ptrdiff_t` for differences, and `bool` for true/false usually solves my problems...
Comment: Also this does not work for pointer types.....(unless I know the address of the thing being pointed to)
Comment: Pointers to types....Pointers to members......Pointers to member functions.....Pointers to functions......integral types
Comment: But I might end up doing something like this for the integral types
Comment: Note that `std::integral_constant` works with those as well. (`""_` operators do not.)


Given the order of an unknown element in an unknown group, find the orders of other elements in the group

Question: Given an unknown group $G$, with an element $x \in G$ such that $o(x) = 18$. Find the orders of $x^2, x^3, x^4, x^5, x^{12}$.
From my textbook, there is a theorem that states:
If $o(x)=n$ and $gcd(m,n)=d$, then $o(x^m)=n/d$.
Applying this to the first two parts of the problem gives:
$o(x) = 18$
$o(x^2) = \frac{18}{gcd(2,18)} = 9$
$o(x^3) = \frac{18}{gcd(3,18)} = 6$
However, the theorem is fairly general. Could it be interpreted to use the results of $o(x^2)$ as $n$ rather than the $o(x)$ given in the original problem?
For example,
$o(x) = 18$
$o(x^2) = \frac{18}{gcd(2,18)} = 9$
$o(x^3) = \frac{9}{gcd(3,9)} = 3$
Clearly, this is giving a different answer for $o(x^3)$. Is this supposed to be correct, or am I only supposed to use the original $o(x)$ for $n$?
Answer: Since you take $o(x^2)=n$, your last computation is for $o((x^2)^3)=o(x^6)$, not $o(x^3)$.
Answer: Two simple, elementary observations make many things easy here.

Order of an element is equal to the order of cyclic (sub)group generated by that element.
If $k$ is relatively prime to order of $x$, then $x$ and $x^k$ generate same cyclic (sub)group, i.e. $<x>=<x^k>$

Suppose given $o(x)=n$. To find order of $x^m$ ($m\leq n$), write $m$ as product of two numbers, where one number divides $n$ and other is relatively prime to $n$:
$$m=dn', \mbox{where $d$ divides $n$ and $n'$ is relatively prime to $n$}.$$
(This is exactly what the gcd business in your arguments: $d$ is gcd of $m$ and $n$.)
Now how this simplifies the finding of order of $x^m$? Well! By two remarks above,
$$o(x^m)=o(<x^m>)=o(<x^{dn'}>)=o(<({x^{n'})}^d>)=o(<x^d>)=o(x^d).$$
Since order of $x$ is $n$ and $d$ is a divisor of $n$, the order of $x^d$ must be $n/d$.

A small mistake in your last step: it should be
$$o(x^3)=\frac{18}{gcd(3,18)}=6.$$


Large errors for logistic regression, what does it mean?

Question: I run the following scripts in r for mixed effect logistic regression.
<code>textbook.usage.glm <- glmer(textbook.usageSession ~ session.week * condition.player  + (1|group.name),family="binomial",data=dfDSP)
summary(textbook.usage.glm)
</code>
And I got the following results.
<code> Generalized linear mixed model fit by the Laplace approximation
 Formula: textbook.usageSession ~ session.week * condition.player + (1 |      group.name)
 Data: dfDSP
 AIC   BIC logLik deviance
 37.27 45.19 -13.64    27.27
 Random effects:
 Groups     Name        Variance Std.Dev.
 group.name (Intercept)  0        0
 Number of obs: 36, groups: group.name, 2

 Fixed effects:
                                    Estimate Std. Error z value Pr(>|z|)
 (Intercept)                            -68.00   14338.57  -0.005    0.996
 session.week                            17.31    3584.64   0.005    0.996
 condition.playerDEFAULT                 75.63   14338.57   0.005    0.996
 session.week:condition.playerDEFAULT   -20.09    3584.64  -0.006    0.996

 Correlation of Fixed Effects:
        (Intr) sssn.w c.DEFA
 session.wek -1.000
 cnd.DEFAULT -1.000  1.000
 s.:.DEFAULT  1.000 -1.000 -1.000
</code>
The results look pretty suspicious. The errors are very large, and all the p values are of the same. If the data itself does not have problems, what might be the reason?
Answer: It may be that your model is completely determined/separated. That is, there is some variable for which certain values perfectly predict failure (i.e. all observations with those values have a value of 1 in the DV). The fact that your sample is only 36 obs also signals to that possibility. It also happens when failures are extremely rare.
I know that glm() in r warns you about cases being completely determined.
Things you could try are:
1) Try looking at crosstabulations of your IVs against your DVs to look for problematic variables.
2) Try looking at your DV to see if failure is extremely rare. The best scenario would be with 50% of the observations being failures.
UCLA also has a good online resource regarding this issue, with even some r examples


Create a dynamic array of JSON Object from values of multiple elements

Question: I need a little help creating a dynamic array of JSON object from the values of different elements. Example is elements below. I have other elements to create the values required for JSON. I didnt want to post 3 lots of same code. So belwo x3

      Title:
      <input type="text" class="leds" name="title" style="width:150px"value="">

      Message:
      <input type="text" class="leds" name="message" style="width: 150px" value="">

      IP address:
      <input type="text" class="leds" name="ip_address" style="width:150px" value="">

     Message Colour:
     <select type="text" class="leds" name="led_colour" style="width:150px">
           <option value=""></option>
           <option value="255,0,0,0">Red</option>
           <option value="0,255,0,0">Green</option>
           <option value="0,0,255,0">Blue</option>
           <option value="255,165,0,0">Orange</option>
           <option value="255,255,0,0">Yellow</option>
           <option value="255,255,255,0">White</option>
           <option value="128,0,128,0">Purple</option>
           <option value="255,0,255,0">Fuchsia</option>
           <option value="192,192,192,0">Silver</option>

I can get the values with the following
 $.each($('.leds'), function(index, obj) {
console.log(index + ':' + obj.value);

});

What I would like to do is create JSON like below:
 [{
"title": "Test1",
"message": "Test1 message",
"ip_address": "126.96.36.199",
"led_colour" : "255,0,0,0"},
{
"title": "Test2",
"message": "Test2 message",
"ip_address": "18.104.22.168",
"led_colour" : "255,0,0,0"},
{
"title": "Test3",
"message": "Test3 message",
"ip_address": "220.127.116.11",
"led_colour" : "255,0,0,0"
 }]

Comment: how look your `html` code? How many `td` in `tr`? I write code for two `td`... Becouse https://drive.google.com/file/d/1-buqh21DI-VJX4pELcmhuLqgtbWFv4Zv/view?usp=sharing

Answer https://stackoverflow.com/a/50892021/2661164
Answer: I think it's solution, but better need modify your html structure
1) In your case:
function getJson(keys) {

    let result = [];

    $('.leds').each(function(i) {

        let keyIndex = i % keys.length,
            key = keys[keyIndex];

        if (!keyIndex) {
            result.push({});
        }

        let index = result.length - 1;
        result[index][key] = this.value;
    })

    return result;
}

const jsonData = getJson(['title', 'message', 'ip_address', 'led_colour']);

console.log('jsonData:', jsonData);

2) Try use tbody for group your tr
DEMO in Codepen.io

function getJson() {

    let result = [];

    $('tbody').each(function() {
        let item = {}
        $('.leds', this).each(function() {
            let $this = $(this);
            item[$this.prop('name')] = $this.val();
        })
        result.push(item);
    })

    console.log('result:', result)

    return result;
}

$(() => {

    getJson();

    $('button').click(() => {
        console.clear();
        const jsonData = getJson();
        alert(JSON.stringify(jsonData));
    })
})

<button>Get Json Data</button>

                Title:

                <input type="text" name="title" style="width:150px" value="title1" class="leds"/>

                Message:

                <input type="text" name="message" style="width: 150px" value="mess1" class="leds"/>

                IP address:

                <input type="text" name="ip_address" style="width:150px" value="192.168.1.1" class="leds"/>

                Message Colour:

                <select type="text" name="led_colour" style="width:150px" class="leds">
                    <option value=""></option>
                    <option value="255,0,0,0" selected="selected">Red</option>
                    <option value="0,255,0,0">Green</option>
                    <option value="0,0,255,0">Blue</option>
                    <option value="255,165,0,0">Orange</option>
                    <option value="255,255,0,0">Yellow</option>
                    <option value="255,255,255,0">White</option>
                    <option value="128,0,128,0">Purple</option>
                    <option value="255,0,255,0">Fuchsia</option>
                    <option value="192,192,192,0">Silver</option>
                </select>

                Title:

                <input type="text" name="title" style="width:150px" value="title2" class="leds"/>

                Message:

                <input type="text" name="message" style="width: 150px" value="mess2" class="leds"/>

                IP address:

                <input type="text" name="ip_address" style="width:150px" value="192.168.1.2" class="leds"/>

                Message Colour:

                <select type="text" name="led_colour" style="width:150px" class="leds">
                    <option value=""></option>
                    <option value="255,0,0,0" selected="selected">Red</option>
                    <option value="0,255,0,0">Green</option>
                    <option value="0,0,255,0">Blue</option>
                    <option value="255,165,0,0">Orange</option>
                    <option value="255,255,0,0">Yellow</option>
                    <option value="255,255,255,0">White</option>
                    <option value="128,0,128,0">Purple</option>
                    <option value="255,0,255,0">Fuchsia</option>
                    <option value="192,192,192,0">Silver</option>
                </select>

                Title:

                <input type="text" name="title" style="width:150px" value="title3" class="leds"/>

                Message:

                <input type="text" name="message" style="width: 150px" value="mess3" class="leds"/>

                IP address:

                <input type="text" name="ip_address" style="width:150px" value="192.168.1.3" class="leds"/>

                Message Colour:

                <select type="text" name="led_colour" style="width:150px" class="leds">
                    <option value=""></option>
                    <option value="255,0,0,0" selected="selected">Red</option>
                    <option value="0,255,0,0">Green</option>
                    <option value="0,0,255,0">Blue</option>
                    <option value="255,165,0,0">Orange</option>
                    <option value="255,255,0,0">Yellow</option>
                    <option value="255,255,255,0">White</option>
                    <option value="128,0,128,0">Purple</option>
                    <option value="255,0,255,0">Fuchsia</option>
                    <option value="192,192,192,0">Silver</option>
                </select>

Comment: Thanks @Slaawwa. This worked perfect. Once I stringified the jsonData  I got the expected results. I tried to upvote but Im not at that level yet
Comment: @sqlNoob, you are wellcome!
Answer: A simple way is to loop each tr and get all .leds inputs, get the name of input and it's value an build object, then put it to array. See the code bellow.
var itemsArray = [];
$.each($('tr'), function() {
   var item = {};
   $(this).find('.leds').each(function(index, obj) {
       item[$(obj).attr("name")]=$(obj).val();

    });
    itemsArray.push(item);
});

Comment: Thansk for your reply. Response below gave me exactly what I needed


Ler Duas Notas e Fazer Media Caso Sejam Notas Válidas

Question: Estou com dificuldades de resolver o exercício abaixo

Devo usar Desvio Condicional
E pelos meus "pensamentos" acredito que devo usar o Desvio Encadeado
Sei que ambas as notas devem atender o critério de terem valores entre 0 e 10, e só assim poderei fazer a média!
Pensei em usar apenas o 'IF' (que sera para caso atenda os "requisitos" e o 'ELSE' para exibir a mensagem caso uma das notas não for válida!
Estou pensando corretamente? E se sim,que não consegui "indentificar" quais serão as condiçoes que devo colocar no IF em relação as notas!
Comment: Carol apenas uma observação em relação às suas perguntas. Se pensou numa forma de resolver e ainda que instruções utilizar, porque não coloca as suas tentativas de resolução ? Isso ajuda a qualquer pessoa que queira responder pois percebe qual a sua real dificuldade.
Comment: Eh que geralmente quando venho perguntar não tenho resolução feita!
Ai não consigo e acabo perguntando!
Answer: Não há mistério! Um desvio composto pode ser suficiente, a não ser que você tenha em mente algo mais sofisticado.
public class Average {
    public static void main(String[] args) {
        double nota1 = 0, nota2 = 10, media;
        // Verifique se as duas notas obedecem o critério...
        if((nota1 >= 0 && nota1 <= 10) && (nota2 >= 0 && nota2 <= 10)) {
            // ... Se sim, calcule a média
            media = (nota1 + nota2)/2;
            System.out.printf("%.2f", media); // Perceba o uso de printf para dar precisão ao valor de output
        } else {
            System.out.println("Uma das notas é negativa ou maior que 10.");
        }
    }
}

Se você alterar os valores iniciais das variáveis, verá que o código acima, simples, atende os requisitos do desafio.
Comment: Era extamente isso que estava pensando,so não sabia se usava apenas If ou usava tambem Else If!


How can I pretty-print Java source code as a PDF?

Question: I'm planning to put some Java code in an appendix to my report. The report is a PDF document, and I use Eclipse for Java.
How can I present it best and do this easily? Any recommendations?
Answer: For this purpose, I created a LaTeX doclet. This is a Javadoc doclet, which converts the javadoc comments to LaTeX code, and (if wanted) also includes a pretty-printed version of the source code of the documented methods.
You can then convert the generated LaTeX document to PDF, and append it to your report.
Answer: I usually prefer to install a PDF "psuedo" printer in whatever OS I am using. That way I can use the print facilities of whatever app I am using (like Eclipse for example) and get the result in  PDF file.
EDIT:
Here is one example of a pseudo printer, this for the Windows platform. Mac OS X has a built in "print to PDF file" capability.
Comment: What's a pseudo printer? Possibly a dumb question but I'm not familiar with the term.
Comment: @user528676 A pseudo printer installs as if it is a printer, and appears to Eclipse as if it is a printer, but actually outputs to a PDF file.  It is a slightly more elaborate version of "print to file".
Comment: Nice. Any recommendations for ones that you use?
Comment: This needs still some program to actually print the Java source code. (I suppose you don't want to append screenshots from your IDE to the PDF.)
Answer: If you use Windows, install CutePDF. This adds a "Printer" that when you print to it it asks you a file name and then prints the output to a .pdf document on your hard drive - hence it is a psuedo printer - it acts like a printer, but is really a pdf file writer.
Don't know solutions for other o/s...
Answer: You can use doxygen to generate documentation for your project which can include a formatted source file listing in addition to Javadoc. doxygen can generate both HTML and PDF output. You'll need latex to generate the PDF output.
Answer: Another way to pretty print is with IntelliJIDEA. It works also with the community edition.
It's advisable to install a PDF printer, in order to try printouts without wasting a lot of paper. Once you're satisfied with the result, you can print on the real printer. On Windows you can use CutePDF, on Linux Ubuntu install the package cups-pdf with sudo apt-get install cups-pdf.
Note that IntelliJ prints the theme's background, so it's advisable to be on a white background to avoid wasting ink.
To print click on menu File -> Print. The printer selection is in the next menu, after you press on the Print button.
Interestingly you can also print only the selected text, which is useful if you don't want to print import statements.
Other options include the possibility to add line numbers, syntax highlighting and colour printing. On Linux IntelliJ 14.0.3, the default font was a huge size 14, so you might want to change that too.
Answer: You could just copy & paste into Word (2007+) and save as PDF. It's a little more straightforward than the file printer, and you can format your code for best results in Word.
Answer: You could just copy & paste into OpenOffice/LibreOffice and export to PDF.


Chi-squared Vs Mutual information

Question: Is chi-squared feature selection better than Mutual information based feature selection mechanism?
Comment: Better in what respect?
Comment: In classification accuracy when used with SVM.
Comment: I would say that MI is better based upon the premises on which the Chi-squared is developed. Also given that there is the 'vanishing p-value' problem for large datasets and the complexity of dealing with significance testing in those situations, that MI is going to be more robust for machine learning applications.
Answer: They are related, so I don't suspect there to be a big difference (hence, go for mutual information if it's easier to calculate).
I haven't seen a formal argument for this, but my logic is:

A g-test is a derivate of mutual information ($G=2\cdot N \cdot MI(r,c)$, cfr. wiki link)
A Chi-squared leads
to the same conclusion as a g-test for reasonably sized samples

Therefore, Chi-squared and MI lead to more or less the same results for reasonably sized samples. In other cases, it will deterministically depend on the dataset properties.
Answer: Just as a follow up to @ciri answer, the same arguments have been developed in the following paper:
Richter et al., 2018

Chi-squared Vs Mutual information