Closed form solution for $\int_{0}^{2\pi}|\cos^N x||\sin^M x|\cos^n x\sin^m x dx$

Question: I am trying to calculate Fourier series coefficients (by hand) and the integrals I need to solve are of the following type
$$I(N,M,n,m)=\int_{0}^{2\pi}|\cos^N x||\sin^M x|\cos^n x\sin^m x dx,$$
in which $N,M,n,m \in \{0,1,2,3\}$. I tried to use WolframAlpha / Maple to come up with a general formula because doing all the $4^4$ cases would make it impossible for me to work with that list but both didn't give a result.

It would be great if there was a way to obtain a simple closed form solution. If that is not possible is there a way to get very accurate approximation for $I(N,M,n,m)$?
Comment: Why does this have the [tag:asymptotics] tag?
Comment: I added it because of the approximation that I needed, do you mean that it is inappropriate?
Comment: I don't see how it's relevant at all. In what sense are you seeking an asymptotic?
Comment: I think that an asymptotic expression can also be used as an approximation. Like Stirling's approximation is actually is more of an asymptotic expression.
Comment: You're asking about a finite set of values. It doesn't make sense to ask for an "asymptotic" for that.
Comment: I will simply remove it.
Comment: Actually this an exact value no need of approximation see my answer.
Answer: $$I(N,M,n,m)=\int_{0}^{\pi}|\cos^N x|\sin^M x\cos^n x\sin^m x dx \\+\int_{\pi}^{2\pi}|\cos^N x||\sin^M x|\cos^n x\sin^m x,dx$$
Set $u =x-\pi$
$$\int_{\pi}^{2\pi}|\cos^N x||\sin^M x|\cos^n x\sin^m x,dx\\=\int_{0}^{\pi}|\cos^N x||\sin^Mx |\cos^n (x+\pi)\sin^m (x+\pi),dx $$
So that
$$I(N,M,n,m)=\int_{0}^{\pi}|\cos^N x|\sin^M x\cos^n x\sin^m x dx \\+(-1)^{n+m}\int_{0}^{\pi}|\cos^N x||\sin^M x|\cos^n x\sin^m x,dx$$

But $\cos(x+\pi) = -\cos x$ and $\sin(x+\pi) = -\sin x$ Hence,

\begin{split}
I(N,M,n,m)&=&\int_{0}^{\pi}|\cos^N x|\sin^M x\cos^n x\sin^m x dx \\
&+&(-1)^{n+m}\int_{0}^{\pi}|\cos^N x||\sin^M x|\cos^n x\sin^m x,dx\\
&=&[1+(-1)^{n+m}]\int_{0}^{\pi}|\cos^N x||\sin^M x|\cos^n x\sin^m x,dx\\
 &=&[1+(-1)^{n+m}]\int_{0}^{\frac{\pi}{2}}\cos^N x\sin^M x\cos^n x\sin^m x dx \\
&+&[1+(-1)^{n+m}]\int_{\frac{\pi}{2}}^{\pi} |\cos^N x||\sin^M x|\cos^n x\sin^m x dx
\end{split}

Setting  $ t= \pi-x$  and noticing that  $\cos(\pi-x) = -\cos x$ and $\sin(\pi-x) = \sin x$ We get ,

$$\int_{\frac{\pi}{2}}^{\pi} |\cos^N x||\sin^M x|\cos^n x\sin^m x dx = (-1)^n\int^{\frac{\pi}{2}}_{0} \cos^N x\sin^M x \cos^n x\sin^m x dx$$
 Therefore,
\begin{split}
I(N,M,n,m)&=&
 [1+(-1)^{n+m}]\int_{0}^{\frac{\pi}{2}}\cos^N x\sin^M x\cos^n x\sin^m x dx \\
&+&[1+(-1)^{n+m}]\int_{\frac{\pi}{2}}^{\pi} |\cos^N x||\sin^M x|\cos^n x\sin^m x dx\\
&=& [1+(-1)^{n+m}][1+(-1)^{n}]\int_{0}^{\frac{\pi}{2}}\cos^N x\sin^M x\cos^n x\sin^m x dx
\end{split}
and
$$ [1+(-1)^{n+m}][1+(-1)^{n}]= [1+(-1)^{m}+(-1)^{n}+(-1)^{n+m}]$$

Conclusion
  $$\bbox[yellow]{I(N,M,n,m) =[1+(-1)^{m}+(-1)^{n}+(-1)^{n+m}]\int_{0}^{\frac{\pi}{2}}\cos^{N+n} x\sin^{M+m} xdx }$$

Also note the following relation with Beta function and Gamma function \url{https://fr.wikipedia.org/wiki/Fonction_b%C3%AAta}.
$$\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)} =B(x,y) = 2\int_{0}^{\frac{\pi}{2}}\cos^{2x-1} t\sin^{2y-1} tdt ,~~x>0,y>0$$
So that ,
$$\bbox[yellow]{I(N,M,n,m) =\frac{1}{2}[1+(-1)^{m}+(-1)^{n}+(-1)^{n+m}]B\left(\frac{M+m+1}{2},\frac{n+N+1}{2}\right)\\=\frac{1}{2}[1+(-1)^{m}+(-1)^{n}+(-1)^{n+m}] \frac{\Gamma\left(\frac{M+m+1}{2}\right)\Gamma\left(\frac{N+n+1}{2}\right)}
{\Gamma\left(\frac{M+N+m+n+2}{2}\right)}}$$
Comment: +1: Excellent answer. This will save me a lot of trouble :D.
Comment: I edited your answer because I think there were some minor mistakes. In the Beta function definition and for the relationship between $\Gamma$ and $B$.
Comment: Cool no problem
Answer: Hint: An easy way is to use the following identity which is quite easy to prove

which is an easy consequence of Integration, trigonometry, gamma/beta functions
Comment: The problem with this formula is that I need to split the integral into 4 pieces. I knew this method, but I wanted a direct method (but not the closed formula for the integral). Without splitting. If no one comes up with a more compact solution I will accept your answer :).
Comment: Maybe you a look to my answer it give the relation with Beta function


Finding a linear transformation $L$ such that $ L(\vec{u}_{i}) = {v}_{i}$ for $ 1 \leq i \leq 3$.

Question: I've been tearing my hair out for hours over this seemingly straightforward linear question. I know it's bad form to post homework without some partial amount of work done, but my work is garbage. I think I'm misunderstanding this question very badly and would appreciate a sanity check.
Define these six vectors:
$$ \vec{u}_{1} = (1,4,7,2) \qquad \vec{u}_{2} = (3,1,1,5) \qquad \vec{u}_{3} = (-3,10,19,-4) $$
$$ \vec{v}_{1} = (7,1,6,5) \qquad \vec{v}_{2} = (-2,1,3,1) \qquad \vec{v}_{3} = (11,3,2,9) $$
Find a linear transformation $L$ such that $ L(\vec{u}_{i}) = {v}_{i}$  for $ 1 \leq i \leq 3$.
(Hint: write down the three equations $L(\vec{u}_{i}) = {v}_{i}$ in terms of the columns of the coefficient matrix of $L$. This will be a system of three equations with four $vectors.$ Find four vectors that satisfy this system.)
Comment: It is **extremely rude** to vandalize your own question, even more if two people took the time to answer it.
Answer: It is impossible.
Note that $u_3 = 3 u_1-2 u_2$. Hence we should have $v_3=L(u_3) = 3 L(u_1)-2 L(u_2) = 3 v_1-2 v_2$.
However, it is easy to check that this is not the case, hence no such linear transformation exists.
(Possibly there is a transcription error?)
Comment: You're right. There must be a transcription error, so that the $u_k$ (as actually stated) are linearly independent.
Comment: I thought I was messing up the substitution, and I couldn't understand how four vectors could satisfy the system.

I double-checked, and it's written the same way in the book. Ouh.
Answer: For convenience, let me take the elements of $\mathbb{R}^4$ to be column vectors, and in particular replace the $u_k$'s and $v_k$'s by their transposes, the corresponding column vectors.
Well, let $L : \mathbb{R}^4 \to \mathbb{R}^4$ be your linear transformation, and let $A$ be the matrix of $L$ with respect to the standard ordered basis of $\mathbb{R}^4$; let $A_k \in \mathbb{R}^4$ be the $k$-th column of $A$, $k=1,\dotsc,4$. Then for each $k$, by unpacking the matrix multiplication, one can check that
$$
 v_k = L(u_k) = A u_k = (u_k)_1 A_1 + (u_k)_2 A_2 + (u_k)_3 A_3 + (u_k)_4 A_4,
$$
where $(u_k)_j$ denotes the $j$th entry of $u_k$. Plugging your given $u_k$ and $v_k$ gives the hinted-at system of three linear equations in four unknown vectors.
Comment: They were actually supposed to be column vectors already, I think. My instructor uses commas for column vectors and none for row vectors, but this was taken out of a textbook so I wasn't entirely sure.

I had gotten as far as that before, but I got tripped up with dimensionality. I end up with a 3 x 4 matrix, but I'm unclear on how the augment should work. Do I just use $\vec{u}_{1}, \, \vec{u}_{2}, $and$\, \vec{u}_{3}$ on the right hand side?

Thanks for the help.
Comment: Yeah, your three equations would be
$$
 (u_k)_1 A_1 + (u_k)_2 A_2 + (u_k)_3 A_3 + (u_k)_4 A_4 = v_k
$$
for $k=1$, $2$, $3$. This'll give you a perfectly reasonable system of linear equations, but it'll fail to be consistent precisely for the reason copper.hat pointed out. Given that the problem clearly presupposes the existence of $L$, something must have gone very, very wrong in the typesetting...


execute python program inside django

Question: I am new to django. I successfully created my first django site. I want to make web interface to a python program:
<code>def func(a,b,c):
    return a*b*c
</code>
Input form fields: numerical values of a,b,c
Output: print func(a,b,c)
My python program solves some differential equations where the inputs are values of a,b,c,.. and output is a text file containing result.
Comment: OK. So what is your question?
Comment: django seems to be an overkill for this purpose.
Answer: Create a form class. Write a template that displays the form and the calculation result. Write a view that receives the values from the form and performs the calculation. Read the tutorial.
Answer: You won't be able to pass arguments to Python from a template using Django tags. You can do it by combining it javascript and passing it to the server via AJAX or another method and then returning the result with a combination of Django template tags and javascript.
Please be more descriptive in the future. In return, the answers will likely be more specific.

execute python program inside django


MultiJson::DecodeError unexpected token at {"email":"firstname.lastname@example.com"}

Question: I'm developing a new Ruby on Rails 3.2 application.
This application will receive a periodic json callback with statistics.
The callback i receive is not entirely valid. The json rules are separated by newlines.

The callback POSTs have a content-type header of application/json, and contain exactly one JSON string per line, with each line representing one event. Please note that currently the POST headers define this post as application/json, though it's not; each line is a valid JSON string, but the overall POST body is not. For example:

This is a example of the callback:
<code>{"email":"firstname.lastname@example.com","timestamp":1322000095,"unique_arg":"my unique arg","event":"delivered"}
{"email":"firstname.lastname@example.com","timestamp":1322000097,"unique_arg":"my unique arg","event":"click"}
{"email":"email@example.com","timestamp":1322000096,"unique_arg":"my unique arg","event":"open"}
</code>
When i receive this callback my Rails application crashes with a "MultiJson::DecodeError"

743: unexpected token at '{"email":"firstname.lastname@example.com","timestamp":1322000096,"unique_arg":"my unique arg","event":"open"}'

I think the application detects the application/json header and try automatic to parse it.
How can i convert this to a valid JSON object, so i can use this in my controller?
Thanks.
Answer: Put
gem 'yajl-ruby' in Gemfile and
require 'yajl/json_gem' config/application.rb
Comment: this works, but i don't get why i was getting the error in the first place!
Answer: In gem file declare
 gem 'yajl-ruby'
 It is used to Parse and encode multiple JSON objects to and from streams or strings continuous.
And require 'yajl/json_gem' in application.rb
Answer: Put Elements in Brackets:
<code>   [{"email":"email@example.com","timestamp":1322000095,"unique_arg":"my unique arg","event":"delivered"},
    {"email":"firstname.lastname@example.com","timestamp":1322000097,"unique_arg":"my unique arg","event":"click"},
    {"email":"firstname.lastname@example.com","timestamp":1322000096,"unique_arg":"my unique arg","event":"open"}]`
</code>
Answer: Unable to reproduce your problem by copy-and-pasting the error message token using both ActiveSupport::JSON.decode and MultiJson.decode in a Rails shell. Rails 3.2.1
Any other clues?
Answer: This issue is likely due to response body encoded in ISO-8859-1 instead of UTF-8. Possible fix on client side is be convert it back to UTF-8 using ruby 'iconv' encoding methods.

MultiJson::DecodeError unexpected token at {"email":"foo@bar.com"}


combobox text still showing previous value on change

Question: I am using 1 combobox to populate a 2nd combobox. What is happening however, is that the 2nd combobox dropdown is changing and displaying the correct values but when the change occurs, the text property still retains the old value. I am using items.clear() and thought that would also clear the text value of the combobox.
I am using winforms and would be grateful if someone could point out my newbie error. Thanks
Private Sub cmbCustomer_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbCustomer.SelectedIndexChanged

        ' This is the routine to populate the departments box with values from customer

        sql = "SELECT * from Departments WHERE Customer = ?"

        Dim cmd As New OleDb.OleDbCommand

        cmd.Parameters.AddWithValue("@p1", cmbCustomer.Text)

        cmd.CommandText = sql
        cmd.Connection = oledbCnn
        dr = cmd.ExecuteReader

        cmbDept.Items.Clear()
        cmbRequestBy.Items.Clear()

        While dr.Read()

            cmbDept.Items.Add(dr("Name"))

        End While

        cmd.Dispose()
        dr.Close()
        'oledbCnn.Close()

    End Sub

Answer: You are clearing the Items collection not the Text property of the combo.
This behavior depends on the DropDownStyle property of the combobox.
The default is DropDown that allow the combo to maintain separate inner controls for Items (A List of some kind) and Text (a TextBox)
If you change the property to DropDownList clearing the Items collection will clear also the 'text' part of it.
Of course you loose the possibility to type inside the TextBox portion of the combobox for example to add an item not included in the list
See Microsoft Connect for Microsoft Response to similar question
Comment: Steve, if I wnated to keep the textbox aspect, how would I clear the textbox element. Thanks
Comment: Simply call ComboBox.Text = string.Empty or [CombBox.ResetText](http://msdn.microsoft.com/en-us/library/f16139cd(v=vs.110).aspx)


How to teleport a villager with a pseudo NBT tag?

Question: Pseudo NBTs are like NBTs that aren't real like these:

So I tried doing something like this:

But it says this:

I don't want mods - I want to do this in vanilla Minecraft.
Comment: Hello, welcome to Arqade!!! I have a segustion, maybe explain your question more by typing it instead of just showing pictures. Because I know that I cannot access the pictures, this would be a great help at helping us solve your problem!!
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: First of all, those are called "pseudo tags".
Secondly, there is an easy way to accomplish this - tags.
By tags I don't mean NBT tags, but the tags you add on to an entity with the /tag command. Simply tag the villager with something and teleport entities of that specific tag.
E.g.
/tag @e[type=villager,sort=nearest,limit=1] foo
/tp @e[tag=foo] to somewhere
Or
You can summon an entity with a default tag as well
/summon villager ~ ~ ~ {Tags:["foo"]}

Always look for easier ways to solve a problem.
By the way, I tried out your original command and it seems like your original summon command would not summon a villager with the pseudo tag. Even using /data merge {Fake:1b} won't do the job. If I were you I would not waste time on this. NBT is simply something that determines entities' properties and there are other, much easier approaches to your problem.


Inaccessible propaganda poster on Bell Tower?

Question: How can you get to this poster? I tried jumping and spamming the action key (I'm on PC) and it didn't work. I tried dropping from the upper floor, can't get close enough to it.
Answer: Throw a Molotov at the poster, and it Will burn.
Comment: It seems like a quarter of the posters are located in inaccessible spots. To take them down in addition to a Molotov and Fire Arrow, I believe some weapons like the Grenade and Rocket Launchers will also work. So you have option!
Comment: You can also use your repair tool to set stuff on fire
Comment: Just smacked my forehead, so obvious.
Comment: surprised no one has mentioned a flame thrower
Answer: yep, like RussellM said - a Molotov; or a Fire Arrow.
Answer: You can use a grenade launcher, M79 side arm or anything explosive (sticky c4) too.


Generating unique IRI from a filename

Question: I have an ontology, created using Protegé 4.3.0, and I would use the OWL-API in order to add some OWLNamedIndividual objects to a file OWL. I use the following instruction in order to create a new OWLNamedIndividual:
OWLNamedIndividual objSample = df.getOWLNamedIndividual(IRI.create(iri + "#" + id));

the variable id is a String;
iri is the base IRI of the loaded ontology; in order to get the base IRI of the ontology, I used the following instruction: iri = ontology.getOntologyID().getOntologyIRI().

So the new OWLNamedIndividual is added to the loaded ontology and then the ontology is saved to OWL file using the following instruction.
XMLWriterPreferences.getInstance().setUseNamespaceEntities(true);
OWLOntologyFormat format = manager.getOntologyFormat(ontology);
manager.saveOntology(ontology, format, IRI.create(file.toURI()));

The variable id is a String generated from the base name of a file (ie. the file name without the extension). If the base name of the file has one or more spaces in the name, the ontology is saved without any error, but when I open the newly saved OWL file, Protegé reports a parsing error at the first occurrence of the IRI containing spaces.
How could I create a valid IRI for an OWLNamedIndividual object using the base IRI of loaded ontology and the base name of a file?
Comment: What do you mean the base name has one or more spaces? Can you provide an example?
Comment: Yes, the string `id` has one or more spaces.
Comment: Of course you can't have spaces in the namespaces, that is the rule. You can have them as labels but not in the `iri`.
Answer: IRIs are suppose to be a block that represents your resource. If I understand you correctly you have an id such as big boat and you are creating IRIs that look like <http://example.com#big boat>. This is not a valid IRI, and you need to replace the space with an _ or a -, such that you have <http://example.com#big_boat>. Even if you enter a modelling element name with a space in Protégé, it automatically will put a _ in the middle.
Take a look at the this article for the invalid characters in an IRI.

Systems accepting IRIs MAY also deal with the printable characters in
     US-ASCII that are not allowed in URIs, namely "<", ">", '"', space,
     "{", "}", "|", "\", "^", and "`", in step 2 above.  If these
     characters are found but are not converted, then the conversion
     SHOULD fail.

Generating unique IRI from a filename


Android variable to JavaScript

Question: I am building an Android WebView which loads an url on a server of mine. However, now I want to use an identifier from the Android as parameter of a function on the JS code and I simply can't do it.
I already tried appending "javascript:myFunction(myParameter);" to the url on the loadUrl method and tried adding a JavascriptInterface. Neither of them did work, and it looked like it needed my files (html and js) to be local. However, I need to open a xml document and, as far as I know, you can't do it with local files, so I couldn't test it.
I am not used to web/android dev, so I don't even know if I'm not trying to do something dumb, but it seems to me that it should be simple to do and yet I'm stuck on it. Thanks in advance.
Answer: Add the variable to the URL, for example:
file://my/file.html?variable=someValue

You should then be able to parse the URL in JS using document.location, for example:
alert(document.location);

Comment: Works like a charm. Thank you!

Android variable to JavaScript


Pandoc is not converting citation keys into citations

Question: I'm trying to get Pandoc to convert markdown citation keys (e.g. [@xxx]) to full citations (in .odt or .docx) but for some reason it isn't working.
I have the following files in the relevant directory: xxx.md, xxx.bib, xxx.csl. I have pandoc and pandoc-citeproc installed (in Ubuntu).
I run the following command or similar:
<code>pandoc --filter pandoc-citeproc -s -o test.odt xxx.md
</code>
The document test.odt is produced, and the markdown is converted appropriately, but the citation keys remain untouched. In the .odt document they still appear as [@xxx] and the #References list is unpopulated. It's like the keys haven't been recognised as citations at all.
The YAML data in my xxx.md file references the .bib and .csl files in the directory. In case it's relevant, the .bib file is generated by exporting from Zotero.
I'm sure I'm making some really basic error with how I use pandoc, but for the life of me I can't work out what it is that I'm doing wrong.
Other similar questions such as this and this don't seem to address the same issue.
Any help would be very gratefully received!
Comment: I think you need `--bibliography xxx.bib`, see http://pandoc.org/README.html#citation-rendering
Comment: Thanks, but I was under the impression that's not needed if the `bibliography` variable is set within the .md document's YAML metadata. I did try the command with the addition of `--bibliography xxx.bib` but the end result was the same.
Answer: Actually turned out to be a problem with the .bib file rather than with the installation or use of pandoc.
Comment: Hi, I am having the same problem, I am wondering if you can tell me what exactly is the bib file problem that you encounter?


Embed players for several types of video streams

Question: Suppose we've different media file links such as
$link = "http://www.my_site.com/test.mp4"; //MP4

// could be anything else such as
//$link = "http://www.my_site.com/test.flv" //FLV
//$link = "http://www.my_site.com/test.asf" //ASF
//$link = "http://www.my_site.com/test.avi" //AVI
//$link = "http://www.my_site.com/test.rmbv" //RMVB
// so on up to 25 well known extensions

Okay since no player support all media extensions so i've been thinking to set
flv,mp4 to jwplay - asf,avi,wmv,mpg,mpeg to media player - rmvb,rmv to real player - mov to quick time ..etc.
So for every and each $link there should be function will get the link file extension by using pathinfo($link, PATHINFO_EXTENSION); and show player name.
Question : Example of 2 extensions wmv and mp4 how to write function embed($link) that can knows the extension of the media file and and show player name.
Like this (but it is not working just for showing what i mean)
function embed($link){
$ext = pathinfo($link, PATHINFO_EXTENSION);

//some code here i can not know what should be
//something like this
//if ($ext === 'mp4') {
//$what = 'JW Player';
//} else if($ext === 'wmv') {
//$what = 'Media Player';
//} else {
//$what = 'Unknwon';
//}

return $url;
}

// then at applying it for link
$link = "http://www.my_site.com/test.mp4";
echo embed($link); // Output : JW Player

// then at applying it for link2
$link2 = "http://www.my_site.com/test.wmv";
echo embed($link2); // Output : Media Player

// then at applying it for link3
$link3 = "http://www.my_site.com/test.ra";
echo embed($link3); // Output : Unknown

so can you please wrote function do such job so i can understand how it does works and apply it for further complex examples ~ thanks for help
Answer: Just change the return var to $what, like this:
function embed($link){
$ext = pathinfo($link, PATHINFO_EXTENSION);

//some code here i can not know what should be
//something like this
if ($ext === 'mp4') {
$what = 'JW Player';
} else if($ext === 'wmv') {
$what = 'Media Player';
} else {
$what = 'Unknwon';
}

return $what;
}

Now it returns the player name.
Then when you call it like this...
$link = "http://www.my_site.com/test.mp4";
echo embed($link);

...it outputs JW Player.


How important is carpet warranty when determining which to pick?

Question: I have a quote, one from a big name national store and one from a local carpet store, the specs i.e. face weight, thread twist, density, etc are exactly the same, both are made from nylon, etc.  However, one has a 25/15/15 warranty while the other has 10/7/7.  And both are comparable in price.
My questions are:

How is it possible the warranties are so different if all other stats are equal.
How much difference does the longer warranty make in terms of
  quality of carpet?
Comment: not a stupid question, they stand for manufactures, stain, and abrasive warranties and it is measured in years
Comment: Stupid question perhaps, but what do the numbers in "25/15/15" and "10/7/7" represent?
Answer: From what I understand, carpet warranties are all but useless. They have so many conditions that it is effectively impossible to actually make a warranty claim. For example:

You must have your carpet cleaned professionally every 16-24 months. You need to produce receipts showing a professional company came to clean this frequently since installation
Stain resistant warranties not covering non-food/beverage stains, such as caused by animals or cleaners
Other limitations on stain warranties, like "there can be some slight loss of stain resistance in high-traffic areas such as stairs (and hallways, in front of doors). The warranty excludes any residual stains that my occur in those areas."
Warranty may only cover replacement of the affected area (so say a 5x8 area is affected, they'll just cut out and replace that bit), and may not even be 100% - apparently they can degrade, so after say 3 years, they'll only cover 60% of the cost. They won't replace your entire carpet because there's a problem in one small area.
Warranty may not cover labor after some period of time. Worse, you may be forced to use a specific installer at whatever rates they charge (thanks, shirlock)

I have no direct experience trying to get warranty on it, but because of all of this, I would put very little faith in the warranty numbers. If you can never effectively never file a warranty claim, they may as well offer a 25 year or even lifetime warranty. What's it matter - if you were 2 months late having your carpet cleaned 4 years ago: warranty voided.
Comment: Greg is right on many points. Read the fine print. If the specs are identical, the warranty after 10 years is all marketing. I'd be more influenced by the cost of similar products.  Warranties usually don't include labor after a short period of time. All good questions to ask the supplier.


Fragment Not open inside RecyclerView.Adapter (show error in getFragmentManager() while calling fragment)

Question: Here I want to open fragment inside RecycleView but its show error but when I open activity its work here. When try to open a fragment with here of fragment manager the Recycler view class can not resolve to getFragmentManager() method inside it. Kindly provide a solution for it
public class AdapterMudra extends RecyclerView.Adapter<AdapterMudra.ReyclerViewHolder> {

private LayoutInflater layoutInflater;
private Context context;
private ArrayList<ItemMudra> items;

public AdapterMudra(Context context, ArrayList<ItemMudra> items) {

    this.layoutInflater = LayoutInflater.from(context);
    this.context = context;
    this.items = items;

}
@Override
public ReyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View item = layoutInflater.inflate(R.layout.item_recycler_view, parent, false);

    return new ReyclerViewHolder(item);
}

@Override
public void onBindViewHolder(final ReyclerViewHolder holder, int position) {
    ItemMudra item = items.get(position);

    holder.image.setImageResource(item.getDrawableMudra());
    holder.appName.setText(item.getNameMudra());
}

@Override
public int getItemCount() {
    return items.size();
}

class ReyclerViewHolder extends RecyclerView.ViewHolder {
    private ImageView image;
    private TextView appName;

    private ReyclerViewHolder(final View v) {
        super(v);

        image = (ImageView) v.findViewById(R.id.image);
        MyName = (TextView) v.findViewById(R.id.my_name);

        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(MyName.getText().toString()=="XYZ")
                {

 ***//Fragment Not open here show error////
***
Here I want to call Fragment but its show error in GetFragment Manager***

                Fragment fragment= new XYZ();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.fragment_container, fragment);
                transaction.addToBackStack(null);  // this will manage backstack
                transaction.commit();

                }
                if(MyName.getText().toString()=="ABC")
                {

*** //Here Its Work When I open activity inside it***

                    Intent intent=new Intent(v.getContext(),ExtraActivityFormTesting.class);
                    context.startActivity(intent);
                }

            }
        });
    }
}
}

Answer: I assume your context is an Activity so you can do something like
((Activity) context).getFragmentManager()

Answer: First make sure the other fragmented class has the necessary implementations and constructors to be fragmented. Meaning, the class XYZ could be preventing your fragment transaction for missing out few essentials.
The following imports for instance
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

Now if thats in order. then Firstly I want you to reform
   Fragment fragment= new XYZ();

to
   XYZ fragment= new XYZ();

Second your fragment manager is badly constructed
reform this
 Fragment fragment= new XYZ();
            FragmentTransaction transaction = getFragmentManager().beginTransaction();

to
     XYZ fragment= new XYZ();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

*And for future references, you need to bring in the error log from the terminal
Comment: On using ***FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();***
Error Occered

-->
Error:(74, 59) error: cannot find symbol method getSupportFragmentManager()
Answer: if your problem is using getFragmentManaget to implement do like below:
create
FragmentManager fm = getFragmentManager();
in your Fragment and passed it to your RecyclerView and again passed it to your ViewHolder and use it. so easy.
note: passed means send it as argumant to constructor
Answer: Fragment fragment= new FirstFragment();
FragmentManager manager = (MainActivityForRecy)context).getSupportFragmentManager();
                    FragmentTransaction transaction = manager.beginTransaction();
                    transaction.replace(R.id.fragment_container, fragment);
                    transaction.addToBackStack(null);  // this will manage backstack
                    transaction.commit();
                    Toast.makeText(context, "you press clicked",Toast.LENGTH_SHORT).show();

Comment: brackets are misplaced try **((MainActivityForRecy)context).getSupportFragmentManager();**
Comment: there is no need to again pass the **mainActivityForRecy** as context is already passed. Only thing is required is to cast that context to activity then  call getSupportFragmentManager
Comment: yes, because it is required to cast it to some activity
**((YourActivityName) context).getSupportFragmentManager();** will work


Maximum Span of Deck Joists

Question: According to the following, a deck using 2x10" joists, spaced 12" apart, can have a span (distance from attachment to house to row of footings) of 16'.
https://www.decks.com/how-to/articles/deck-joist-sizing-and-spacing
I just had a contractor bid the job for my new deck, which I want to be 15' deep. He said because the footers will be ~14.5' from the edge of the house (and plans to use the aforementioned joists/construction), he plans to only put one row of footers. While this technically passes the above rule (code? rule of thumb?), is this shoddy work? He said an additional row of footers would cost extra, and definitely wasn't necessary. I wanted to get the community's opinion. Is the 16' number "built to last", or "absolute maximum before it becomes a safety hazard"?
Comment: Your question is entirely subjective as it's written, and therefore off topic.
Answer: The Code requires a "Live Load" of 40 lbs. per square foot (psf) plus you have a "Dead Load" of about 10 psf (joists and 2x decking) for a total load of 50 psf. (See Table R301.5)
A 2x10 will support about 90 psf depending on the species and grade for a 16 foot span.
I'd say you're fine, even when everyone is outside singing happy birthday at you next birthday party.
However, don't forget the new Code requires metal straps at each end of the deck strapped to the house's foundation. You can use something like this:
https://www.fastenersplus.com/products/Simpson-DTT2Z-Deck-Tension-Tie-Zmax-Finish?gclid=Cj0KCQjw7YblBRDFARIsAKkK-dJZrRsiFDrb6UevCNA1fWsgoBllbcaFbSIxYM08Q-lVaduQDD0EbOYaAvekEALw_wcB

Maximum Span of Deck Joists


MySQL, PHP and tabular data

Question: I have a semi-complex (not really, but it's not the simplest either) database structure:
appointments = id, teacher_id, child_id, slot
child = id, parent_id, name, form
parent = id, name, contact_details
teacher = id, name, subject
slot = id, time
As a result I've been using some multiple join SELECT statements to retrieve the data I require, such as:
SELECT
 DISTINCT ( ( c.id +150 ) *1055 ) AS reference_number,
 p.name AS parent_name,
 c.name AS child_name,
 c.form AS child_form
FROM appointments AS a
INNER JOIN child AS c ON a.child_id = c.id
INNER JOIN parent AS p ON c.parent_id = p.id

What I'd like to do is produce a table where the slots are one axis and the teachers are the other axis, with the name of the child booked for that teacher in that time slot as the actual data.
The slot table looks like this:
SQL query: SELECT * FROM `slots` LIMIT 0, 30 ;
Rows: 30

id  time
1   2012-03-15 16:00:00
2   2012-03-15 16:05:00
3   2012-03-15 16:10:00
4   2012-03-15 16:15:00
5   2012-03-15 16:20:00
6   2012-03-15 16:25:00
7   2012-03-15 16:30:00
8   2012-03-15 16:35:00
9   2012-03-15 16:40:00
10  2012-03-15 16:45:00
11  2012-03-15 16:50:00
12  2012-03-15 16:55:00
13  2012-03-15 17:00:00
14  2012-03-15 17:05:00
15  2012-03-15 17:10:00
16  2012-03-15 17:15:00
17  2012-03-15 17:20:00
18  2012-03-15 17:25:00

The appointments table looks like this after a few entries:
id  teacher_id  child_id    slot
1   1   1   3
2   2   1   5
3   1   3   2
4   2   3   6
5   1   4   4
6   2   4   7
7   1   5   1
8   2   5   9
9   1   6   8
10  2   6   3

I tried to put something together using PHP but it really hurt my head!
Can anyone recommend a solution, without using external scripts?

EDIT as per request here is a small screenshot of what I'm trying to achieve. I did this in Excel but obviously, as per topic, I want this in PHP/HTML.

Thanks in advance,
Comment: Please show small example of desired output.
Comment: Thanks for the suggestion @MarcusAdams - I've done that now.
Answer: Off the top of my head I would try something like this. The first bit is pseudo code.
This should produce a table with all the teacher names in the first column, then a column for each time slot, and then the childname in the cells where there is an appointment booked.
$appointments =
SELECT
 DISTINCT ( ( c.id +150 ) *1055 ) AS reference_number,
 p.name AS parent_name,
 c.name AS child_name,
 c.form AS child_form,
 a.id AS appointmentid,
 a.slot AS slotid
FROM appointments AS a
INNER JOIN child AS c ON a.child_id = c.id
INNER JOIN parent AS p ON c.parent_id = p.id
$teachers = SELECT id, teacher FROM teachers
$slots = SELECT id, time FROM slots
Get those into associative arrays so you have $appointments $teachers $slots (you can add the code for that)
<?php

// simply add a blank child element to each slot
foreach($slots as $slotKey => $slot)
{
    $slots[$slotKey]['child'] = '';
}

// now add the full empty slot list to all teachers
foreach($teachers as $key => $teacher)
{
    $teachers[$key]['appointments'] = $slots;
}

// now to fill in the child names into the teachers slots where they have an appointment
foreach($teachers as $teacher)
{
    foreach($teacher['slots'] as $slotKey => $slot)
    {
        foreach($appointments as $appointment)
        {
            if($slot['id'] == $appointment['slotid'])
            {
                $teacher[$key][$slotKey]['child'] = $appointment['child_name'];
            }
        }
    }
}

// now lets output the HTML table
?>

        Teacher
        <?php foreach($slots as $s): ?>
            <?php echo $s['time']; ?>
        <?php endforeach; ?>

    <?php foreach($teachers as $t): ?>

            <?php echo $t['name']; ?>
            <?php foreach($t['slots'] as $slot): ?>
                <?php echo $slot['child_name']; ?>
            <?php endforeach; ?>

    <?php endforeach; ?>

MySQL, PHP and tabular data


Feedback Loop THREE.js

Question: I have implemented a feedback loop (backbuffer) by doing:
function render()
{
    renderer.setRenderTarget(BufferA);
    renderer.render(BufferAScene, camera);
    renderer.setRenderTarget(null);
    renderer.clear(); let temp = BufferA;
    BufferA = BufferAFeedBack;
    BufferAFeedBack = temp;
    ...
 }

Although it works, it gives a warning that there is a feedback loop between the texture target and the framebuffer. I guess this is the reason why none of the shaders are visible on mobile.
Is there a more efficient way to swap FBO's in THREE.js?
I know OpenGL and have already implemented the same thing, so I imagine that I could implement the app in vanilla WebGL, but I don't want to write again the host app from scratch!
Although it seems that the layer of abstraction is making me duplicate objects that are not needed in plain WebGL, any suggestions?
Comment: Maybe you're looking for an example like [this](https://github.com/mrdoob/three.js/blob/master/examples/jsm/postprocessing/AfterimagePass.js) used in [this](https://threejs.org/examples/#webgl_postprocessing_afterimage)?
Comment: Thanks gman I'll let you know if it works.
Comment: By the way any tips debugging shaders in mobile? I know about Chrome's mobile emulator but in this case the emulator runs and mobile doesn't.
Comment: You can connect Safari remotely to iOS and Chrome remotely to Android Chrome for debugging. Google for "remote debugging safari/chrome". Maybe [this article](https://threejsfundamentals.org/threejs/lessons/threejs-debugging-javascript.html) and [this one](https://threejsfundamentals.org/threejs/lessons/threejs-debugging-glsl.html)?
Comment: Thanks! I'll let you know if your comment worked so that you can post it as an answer
Comment: It worked! Thank you very much I will add what I did to fix it, if you want to post an answer of your own that explains things better I will mark it as the final one.
Comment: I've got the remote bugging working and unfortunately that wasn't the problem, it was that the size of the FBO was too large for mobile.
Answer: From the comment by gman I made some adjustments and it works perfectly:
function render()
{

    BufferAUniforms.iChannel0.value = BufferAFeedBack.texture;
    ImageUniforms.iChannel0.value = BufferA.texture;

    renderer.setRenderTarget(BufferA);
    renderer.render(BufferAScene, camera);

    renderer.setRenderTarget(null);
    renderer.clear();

    let temp = BufferA;
    BufferA = BufferAFeedBack;
    BufferAFeedBack = temp;

    renderer.render(BufferImageScene, camera);

}

Feedback Loop THREE.js


Given $(X,d)$ compact, find a countable set of functions to approximate any continuous function at finite points in $X$.

Question: Let $(X, d)$ be compact and $C(X)$ be the set of continuous function $f \colon X \to \mathbb{R}$. Then clearly any $f \in C(X)$ is uniform continuous. Define $C_{m,n} = \{f(x) \in C(X) \colon d(x,y) < \frac 1m \implies |f(x)-f(y)| < \frac1n \}$.
Show that given any set of finite points $x_1, \cdots, x_k \in X$ and $m,n \geq 1$, there is a countable set $\{f_l\} \subseteq C_{m,n}$ so that for any $f \in C_{m,n}$ and $\epsilon > 0$ there is a $f_l \in C_{m,n}$ so that $\max_{i = 1,\cdots, k}|f_l(x_i)-f(x_i)| < \epsilon$.
It is easy to simply create many different countable set of functions s.t. $f_{l}(x_i) = r_i \in \mathbb{Q}$ so that $f_l$ is continuous and since rational is dense in real most conditions can be satisfied. The problem is how to ensure $f_l \in C_{m,n}$. I wonder how to achieve this.
Answer: Let $I=\Bbb Q^{k+1}$. For every $l=(r,y_1,\ldots, y_k)\in I$ let
$$F_l=\{\,f\in C_{m,n}:\forall i\;|f(x_i)-y_i|\,\}.$$
It may happen that for some $l$, $F_l$ is empty; in fact, $F_l$ is certainly empty when $r\le 0$.
But for those $l$ with $F_l\ne\emptyset$, pick one arbitrary $f_l\in F_l$. This gives us our desired countable subset
$$Q:=\{\,f_l:l\in I, F_l\ne\emptyset\,\}$$
of $C_{m,n}$.
Now let $f\in C_{m,n}$ be arbitrary and $\epsilon>0$. Using denseness of $\Bbb Q$, pick $r \in \Bbb Q$ with  $0<r<\frac12\epsilon$ and then $y_i\in \Bbb Q$ with $|f(x_i)-y_i|<r$, and let $l=(r,y_1,\ldots, y_k)$. As $f\in F_l$ shows that $F_l\ne\emptyset$, there exists some $f_l\in Q\cap F_l$ and for this we have $|f(x_i)-f_l(x_i)|<2r<\epsilon$, as desired.


Prove, using the method of mathematical induction that the following holds true

Question: For natural numbers $n\ge1$ show the following inequality using induction.
$$n^{1/n}\le 1+\sqrt{\frac{2}{n}}$$
Comment: Does the base case hold? Any thoughts about the inductive step?
Comment: It does, and I have literally no idea how to solve it apart from using netwons binomial which we are not allowed to used...
Comment: @Suzanne Does my answer help you?  Are there any steps that you don't understand? Your response will be appreciated.
Answer: To solve this problem, merely binomial theorem will be enough.
The base case $n = 1$ is obviously true.  Then we assume that $$n^{\frac1n}\le 1+\sqrt{\frac{2}{n}} \iff n \le \left(1+\sqrt{\frac2n}\right)^n,$$ and we try to prove $$(n+1)^{\frac1{n+1}}\le 1+\sqrt{\frac{2}{n+1}} \iff n+1 \le \left(1+\sqrt{\frac2{n+1}}\right)^{n+1}.$$
$\mathbf{Claim} \quad \left(1+\sqrt{\dfrac2n}\right)^n + 1 \le \left(1+\sqrt{\dfrac2{n+1}}\right)^{n+1}.$
With this claim, it's clear that $n+1 \le \left(1+\sqrt{\dfrac2n}\right)^n+1 \le \left(1+\sqrt{\dfrac2{n+1}}\right)^{n+1}$, so once the claim is proved, we're done.
Proof of the claim
Let $a_n = \left(1+\sqrt{\dfrac2n}\right)^n$.  Then we want $a_n + 1\le a_{n+1} \,\forall n \in \Bbb{N}$.  This is a bit tricky if we use binomial theorem and condense the higher power terms with a summation sign.
\begin{split}
a_n + 1&= \left(1+\sqrt{\frac2n}\right)^n \\
&= 1 + 1 + \sqrt{2n} + \frac{n(n-1)}{2} \frac2n + \sum_{k=3}^n \binom{n}{k} \left(\sqrt{\frac2n}\right)^k \quad \mbox{(Here we assume $n \ge 3$)}\\
&= 2 + \sqrt{2n} + (n-1) + \sum_{k=3}^n \binom{n}{k} \frac{(\sqrt{2n})^k}{n^k} \\
&= 1 + \sqrt{2n} + n + \sum_{k=3}^n \frac{(\sqrt{2n})^k}{k!} \frac{n(n-1)\cdots(n-k+1)}{n^k} \\
&= 1 + \sqrt{2n} + n + \sum_{k=3}^n \frac{(\sqrt{2n})^k}{k!} \frac{n}{n} \frac{n-1}{n} \cdots \frac{n-k+1}{n} \\
&= 1 + \sqrt{2n} + n + \sum_{k=3}^n \frac{(\sqrt{2n})^k}{k!} 1 \left( 1-\frac{1}{n} \right) \cdots \left( 1-\frac{k-1}{n} \right) \\
&< 1 + \sqrt{2(n+1)} + n + \sum_{k=3}^n \frac{(\sqrt{2(n+1)})^k}{k!} 1 \left( 1-\frac{1}{n+1} \right) \cdots \left( 1-\frac{k-1}{n+1} \right) \\
&= 1 + \sqrt{2(n+1)} + \binom{n+1}{2} \frac2{n+1} + \sum_{k=3}^n \frac{(\sqrt{2(n+1)})^k}{k!} \frac{n+1}{n+1} \frac{n}{n+1} \cdots \frac{n-k+2}{n+1} \\
&= 1 + \sqrt{2(n+1)} + \binom{n+1}{2} \frac2{n+1} + \sum_{k=3}^n \binom{n+1}{k} \left(\sqrt{\frac2{n+1}}\right)^k \\
&= \sum_{k=0}^n \binom{n+1}{k} \left(\sqrt{\frac2{n+1}}\right)^k \\
&= \left(1+\sqrt{\frac2n}\right)^n \\
&= a_{n+1}
\end{split}
What is left is the base cases for $n = 1$ and $n = 2$.
\begin{split}
a_1 + 1 &= 1 + 1 + \sqrt2 < 2 + 2 = 4 = \left( 1 + \sqrt{\frac22} \right)^2 = a_2\\
a_2 + 1 &= 1 + \left( 1 + \sqrt{\frac22} \right)^2 \\
&= 1 + 1 + \sqrt2 \cdot \sqrt2 + \frac22 \\
&= 1 + \sqrt2 \cdot \sqrt2 + \left( \frac22 + 1 \right) \\
&< 1 + \sqrt2 \cdot \sqrt3 + 2 \\
&< 1 + \sqrt2 \cdot \sqrt3 + \binom{3}{2} \frac23 + \left(\sqrt\frac23\right)^3\\
&= \left(1+\sqrt\frac23\right)^3 \\
&= a_3
\end{split}


How can I in JavaScript return audio from another JavaScript file?

Question: Maybe the question is a bit weird but I don't know how to ask this in one sentence.
This project: I used this library for JavaScript called ml5.js which uses machine learning to detect a word you are saying and displays is on screen, only 18 words are in the database.
When for example you say the word 'left', left show up on screen along with the name of the song and the artist. But I want it to play the song that is displayed so...
First of all let me share my code:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

    <audio id="myAudio" src="Left1.mp3"></audio>

html, body {
    margin: 0;
    padding: 0;
    background-color: #FFF;
  }
  canvas {
    display: block;
  }

console.log ('ml5 version:', ml5.version)

let soundClassifier;
var resultP;
var audio = nummers;

var nummers = geluid.filter(zoeken);

function zoeken(geluid) {
    return geluid.Titel.includes("Left");
}

console.log(nummers);

var nummers2 = geluid.filter(zoeken2);

function zoeken2(geluid) {
    return geluid.Titel.includes("Up");
}

function preload() {
  let options = { probabilityThreshold: 0.98 };
  soundClassifier = ml5.soundClassifier('SpeechCommands18w', options);
}

function setup() {
  createCanvas(400, 400);
  resultP = createP('waiting...');
  resultP.style('font-size','32pt');
  soundClassifier.classify(gotResults);
}

function gotResults(error, results) {
  if (error) {
    console.log('something went wrong');
    console.error(error);
  }
  resultP.html(results[0].label);
  console.log (results[0].label);
  good(results[0].label);
}

function good (label)
{
  if (label === 'left') {
    console.log ('good fun');
    var vinden = Math.floor(Math.random() * nummers.length);
    var denaam = nummers[vinden]

    resultP.html('left' + '
' + '
' + 'Song: ' +  denaam.Titel + '
'+ '
'+ 'Artist: ' + denaam.Artist);

  }
else
{
  console.log ('gestopt')
  document.getElementById('myAudio').pause();
  //audio.pause();
  //audio.currentTime = 20;
}

{
  if (label === 'up') {
    console.log ('good fun');
    var vinden = Math.floor(Math.random() * nummers2.length);
    var denaam = nummers2[vinden]

    resultP.html('up' + '
' + '
' + 'Song: ' +  denaam.Titel + '
'+ '
'+ 'Artist: ' + denaam.Artist);
    return denaam.Nummer
  }
else
{
  console.log ('gestopt')
  document.getElementById('myAudio').pause();
  //audio.pause();
  //audio.currentTime = 20;
}

}

}

[JAVASCRIPT I USE AS A DATABASE]
var geluid = [
{
    "Titel": "No Tears Left",
    "Artist": "Russ",
    "Nummer": document.getElementById('myAudio')
  },
  {
    "Titel": "The Only Way Is Up",
    "Artist": "Martin Garrix, Tiësto",
    "Nummer": document.getElementById('myAudio')
  }

]

//Audio ("Left1.mp3")

Now here to explain my struggles. I am trying to put a audio source in my JavaScript database file after "nummer"
So I want "Nummer": "audiofile"
And I want that audiofile to start playing when I it says 'left' or 'up' on screen.
How can I fix this?
Answer: It's quite hard to follow the attached code honestly, but I would suggest some approach which you might find easier.
For the database, I would store only the name of the audio file
var geluid = [
{
    "Titel": "No Tears Left",
    "Artist": "Russ",
    "Nummer": "noTearsLeft.mp3"
  },
  {
    "Titel": "The Only Way Is Up",
    "Artist": "Martin Garrix, Tiësto",
    "Nummer": "theOnlyWay.mp3"
  }
]

I would also remove the audio tag from HTML <audio id="myAudio" src="Left1.mp3"></audio>, we can just rely on JS for doing it.
I would also add this function to the script
function playSound(file){
    var cAudio = new Audio("path/to/music/" + file);
    cAudio.play();
}

Now, all you have to do is to call playSound when get results from ml5:
function good (label) {
  if (label === 'left') { // I am not sure I understand this
    console.log ('good fun');
    var vinden = Math.floor(Math.random() * nummers.length);
    var denaam = nummers[vinden]

    resultP.html('left' + '
' + '
' + 'Song: ' +  denaam.Titel + '
'+ '
'+ 'Artist: ' + denaam.Artist);

    playSound(denaam.Nummer); // Wohooo!

  }
  ...
}

Comment: Sorry for the messy code but your solution worked! Thanks!


How to check for static member variable template?

Question: I need to define a class, foo, with a static member variable template, foo::static_variable_template<T>. This member should only exist when T fulfills certain requirements. For example, when the constexpr static function T::constexpr_static_function() exists. Otherwise, foo::static_variable_template<T> should not exist. Moreover, I would like to be able to test for the existence of foo::static_variable_template<T> at compile-time via SFINAE.
Here is an approximation of what I would like to do:
#include <iostream>

struct foo
{
  template<class T>
    static constexpr int static_variable_template =
      T::constexpr_static_function();

// XXX this works but requires a second defaulted template parameter
//  template<class T, int = T::constexpr_static_function()>
//    static constexpr int static_variable_template =
//      T::constexpr_static_function();
};

struct has_constexpr_static_function
{
  static constexpr int constexpr_static_function() { return 42; }
};

struct hasnt_constexpr_static_function
{
};

template<class T, class U,
  int = T::template static_variable_template>
void test_for_static_variable_template(int)
{
  std::cout << "yes it has\n";
}

template<class T, class U>
void test_for_static_variable_template(...)
{
  std::cout << "no it hasn't\n";
}

int main()
{
  test_for_static_variable_template<foo, has_constexpr_static_function>(0);
  test_for_static_variable_template<foo, hasnt_constexpr_static_function>(0);
}

This approximation nearly works, but only if foo::static_variable_template has a second, defaulted template parameter. Because this second parameter is an implementation detail, I'd like to hide it from the public interface of foo::static_variable_template.
Is this possible in C++17?
Comment: Can't you just make the trait depend on `constexpr_static_function` and check for that?
Answer: I am not sure if your intent is to initialise foo::static_variable_template with 0 if T::constexpr_static_function() is missing or you want to disable it entirely. In case of the former, this might be useful. For example, this (clunky) solution works (requires C++17 for if constexpr; note that your variable is now a function):
#include <iostream>

template <typename T>
class has_func
{
    typedef char does;
    typedef long doesnt;

    template <typename C> static does test( decltype(&C::constexpr_static_function) );
    template <typename C> static doesnt test(...);

public:
    static constexpr bool value()
    {
        return sizeof(test<T>(0)) == sizeof(char);
    }
};

struct foo
{
    template<class T>
    static constexpr int static_variable_template()
    {
        if constexpr (has_func<T>::value())
        {
            return T::constexpr_static_function();
        }
        return 0;
    }

    // XXX this works but requires a second defaulted template parameter
    //  template<class T, int = T::constexpr_static_function()>
    //    static constexpr int static_variable_template =
    //      T::constexpr_static_function();
};

struct has_constexpr_static_function
{
    static constexpr int constexpr_static_function() { return 42; }
};

struct hasnt_constexpr_static_function
{
};

template<class T, class U>
void test_for_static_variable_template(...)
{
    if constexpr (has_func::value())
    {
        std::cout << "yes it has\n";
    }
    else
    {
        std::cout << "no it hasn't\n";
    }
}

int main()
{
    std::cout << foo::static_variable_template<has_constexpr_static_function>() << "\n";
    std::cout << foo::static_variable_template<hasnt_constexpr_static_function>() << "\n";

    /// Original test
    test_for_static_variable_template<foo, has_constexpr_static_function>(0);
    test_for_static_variable_template<foo, hasnt_constexpr_static_function>(0);
}

Prints
42
0
yes it has
no it hasn't

Tested with clang 5.0.1.
In case you want to disable foo::static_variable_template entirely, you might need to use std::enable_if:
#include <iostream>

template <typename T>
class has_func
{
    typedef char does;
    typedef long doesnt;

    template <typename C> static does test( decltype(&C::constexpr_static_function) );
    template <typename C> static doesnt test(...);

public:
    static constexpr bool value()
    {
        return sizeof(test<T>(0)) == sizeof(char);
    }
};

struct foo
{
    template<class T, typename std::enable_if<has_func<T>::value()>::type ...>
    static constexpr int static_variable_template()
    {
        if constexpr (has_func<T>::value())
        {
            return T::constexpr_static_function();
        }
        return 0;
    }

    // XXX this works but requires a second defaulted template parameter
    //  template<class T, int = T::constexpr_static_function()>
    //    static constexpr int static_variable_template =
    //      T::constexpr_static_function();
};

struct has_constexpr_static_function
{
    static constexpr int constexpr_static_function() { return 42; }
};

struct hasnt_constexpr_static_function
{
};

template<class T, class U>
void test_for_static_variable_template(...)
{
    if constexpr (has_func::value())
    {
        std::cout << "yes it has\n";
    }
    else
    {
        std::cout << "no it hasn't\n";
    }
}

int main()
{

    std::cout << foo::static_variable_template<has_constexpr_static_function>() << "\n";
    // We can't print this because it doesn't exist.
    // std::cout << foo::static_variable_template<hasnt_constexpr_static_function>() << "\n";

    /// Original test
    test_for_static_variable_template<foo, has_constexpr_static_function>(0);
    test_for_static_variable_template<foo, hasnt_constexpr_static_function>(0);
}

In this line of thought, I am not sure if you can disable a static template variable with std::enable_if. To quote the great Riemann, "I have for the time being, after some fleeting vain attempts, provisionally put aside the search for this..."
Comment: Thanks, my intent was to disable `static_variable_template` entirely. I agree that there doesn't seem to be a way to do that (yet?) for variable templates.


How can I track the answers posted by others to questions I answered?

Question: I really like to follow up on the questions I answered to see if others have better answers or to later improve mine, if an answer gives me new clues to rewrite it.
The inbox only shows comments made to me or answers on my questions, but how can I track all questions I have answered to see if they have new answers?
Answer: You can set them as favorite; in every question there is a star icon that adds the question to your favorites.
When there is a change to your favorite questions, which means there are new answers too, the "favorite" tab will show an asterisk.
Comment: But isn't this a flawed use of the favorite ? These aren't my favorites questions, I just want to track them. Isn't there a better way (and yep I know I'm not a SE dev ;) ).
Comment: @tostinni No. You can set any question as favorite.


Is there an abbreviation for "we want to prove that"?

Question: I think it's possible to abbreviate "such that" into "s.t." but is there an abbreviation for "we want to prove that"? Because this statement keeps repeating in proving inequalities.
Comment: I do not recommend using such abbreviations, they are ugly and worsen the readability. Use synonyms instead: "we claim that", "we need that" etc...
Comment: I've seen "w.t.s." for "want to show"
Comment: Prove or prove not, there is no want. -- Yoda
Comment: Sometimes (in lectures, not in handouts) I've seen "**Want**: (suff)". This is used in order to keep track of what sub-lemma a discussion that may need a certain number of blackboards is dealing with. But it's more of an ad hoc thing. In an actual paper you may be a pal to readers and be as discursive as you can, without being verbose. Keep in mind that the number of people that may want to read it widely outrange your possibility to explain your notation.
Comment: I had a real analysis lecturer use $\vdash :$, as in "$\vdash :$ $f_n\to f$" meaning "we want to prove that $f_n\to f$". I adopted that in the blackboard only, always saying the "we want to prove that" part a bit slower, exactly as I wrote the $\vdash :$.
Comment: References http://www.libragold.com/blog/2011/12/mathematical-abbreviation/ and https://en.wikipedia.org/wiki/List_of_mathematical_abbreviations
Answer: In my undergraduate math classes, I have seen some faculty use "WTS:" as shorthand for "Want to show:". I found this to be quite convenient, but only after the meaning was explained: until then it was quite confusing, so do take @GiuseppeNegro's comment above into account.
If you feel you are going to be making repeated use of it in a document/exam paper then you could mention at the start what this abbreviation stands for exactly.


Conditional formatting with "and"

Question: I have a custom formatting rule which changes the color of a series of cells. The formula is:
<code>=and(I$4>=$D5,I$4<=$E5)
</code>
I want to add one more thing, which is to display the text in the cells which is found in C5. Can anybody help?
Answer: adding text in a cell with conditional formatting is not possible. you will need to add it with standard formula:
<code>=ARRAYFORMULA(IF(AND(D5:D<=$I$4, E5:E>=$I$4), {C5:C}, ))</code>

Conditional formatting with "and"


IBM MQ - Redistributable Managed File Transfer client "runmqsc" fails

Question: I want to install a re-distributable managed file transfer agent in a Linux machine
which in turn will transfer files to a windows machine. My issue is, do I need to install the
IBM MQ in the machine which the re-distributable client is installed, because when I run
the command in the client
runmqsc MFTU < RDSAGTLIN_create.mqsc > mftu.out

to create the required object for the redistributable client, (MFTU is the Queue manager name and RDSAGTLIN is the re-distributable client agent name), the below error pops up.
[root@mqlocalhost RDSAGTLIN]# runmqsc MFTU < RDSAGTLIN_create.mqsc > mftu.out
 bash: runmqsc: command not found...

I understand runmqsc is a IBM MQ command, my question is do I have to install the IBM MQ
in the client also to setup the re-distributable file transfer agent?
Any help will be very much appreciated.
Regards,
Yasothar
Comment: No, you don't need to install IBM MQ on the machine where you want to run an agent that uses MFT Redistributable Package. But you need to have MQ installed, configured and running for use with MFT somewhere. With MFT Redistributable, runmqsc is not shipped. You need to run "runmqsc MFTU < RDSAGTLIN_create.mqsc " on a machine where agent queue manager is running.
Comment: Very much understood Shashi,
Answer: runmqsc should be delivered in an MQ Client only installation, so you don't need a full IBM MQ installation if you only need to add runmqsc. You will need a 'C' client if you are trying to use runmqsc against a queue manager on a different machine. e.g. runmqsc -c
However, your question appears to be trying to use runmqsc against a queue manager on the same machine - is this the case? If so your problem might simply be that you have not found runmqsc in your path. Have you used the setmqenv command to set up your environment?
If this is not the case and the queue manager MFTU is on a different machine then it might be as easy to run the runmqsc command directly on that machine? runmqsc will be available there because the full queue manager installation will be there.
Comment: Thank u so much Morag, the answer was really helpful. Thank u for the time.
Comment: Hi Morag, do have any good reference on installing IBM MQ client in a Linux environment (aprat from IBM documentaion), will be pleased if you can point one.
Comment: I always use the IBM documentation for installation tasks. It's the one part of Knowledge Center that is complete in my view.


cp -Rdfp $source/* $dest/ wont copy .htaccess

Question: This command wont copy .htaccess files:
cp -Rdfp $source/* $dest/

Thanks
Comment: The problem is, that the wildcard (`*`) does not expand to hidden files (starting with `.`) by default. You should check the question from my previous comment for possible solutions.
Answer: In bash, the * glob doesn't include hidden files ('dotfiles') by default - you can enable that explicitly by setting the dotglob shell option e.g.
shopt -s dotglob
cp -Rdfp $source/* $dest

You can unset the option after with shopt -u dotglob.
Alternatively, if $dest does not already exist, the much simpler
cp -Rdfp $source $dest

(avoiding the glob altogether) should work as well.


Analytically unramified local ring of dimension $1$ always admit canonical module?

Question: Let $(R, \mathfrak m)$ be a reduced local ring of dimension $1$ such that the completion of $R$ is also reduced (such rings are called analytically unramified). Note that $R$ is Cohen-Macaulay since it is reduced and has dimension $1$.
My question is:

Does $R$ necessarily admit a canonical module? I.e., is $R$ a homomorphic image of a local Gorenstein ring?
Answer: Yes, $R$ necessarily has a canonical module. This is a special case of the following:
Theorem [Herzog, Satz 6.21]. Let $R$ be a one-dimensional Cohen–Macaulay local ring. Then, the following statements are equivalent:

A canonical ideal exists.
For every minimal prime ideal $\mathfrak{p}$ of the completion $\hat{R}$ of $R$, the localization $\hat{R}_{\mathfrak{p}}$ is a Gorenstein ring.


Problem in splitting lists with different delimiters

Question: I'm solving an exercise where I take seconds as an input and I got to return the amount of time in years, days, hours, minutes and seconds.
For example:
The components are separated by a comma and a space (", "). Except the last component, which is separated by " and ", just like it would be written in English.
However, I am not being able to format the data in the format that is required to pass the tests, as I can either only do comma's or and's, not both.
[This code generates: 2 days and 4 hours and 56 minutes and 4 seconds]
def format_duration(seconds):
    result = []
    counter = 0
    if seconds == 0:
        print('now')
        return 'now'
    final_years = int(seconds/31536000)
    final_days = (int(seconds/86400))%365
    final_hours = (int(seconds/3600))%24
    final_minutes = (int(seconds/60))%60
    final_seconds = seconds%60
    returning(final_years,' year',result)
    returning(final_days,' day',result)
    returning(final_hours,' hour',result)
    returning(final_minutes,' minute',result)
    returning(final_seconds,' second',result)
    print(' and '.join(result))
    return ' and '.join(result)

def returning(time,name,array):
    if time > 0:
        if time == 1:
            array.append(str(time)+name)
        if time > 1:
            name += 's'
            array.append(str(time)+name)

format_duration(190564)

I have tried making a counter to understand how many commas and ands would be needed but I struggle to add them to the sections necessary afterwards.
Comment: You don't need to split anything. You're asking how you can _join_ items in a list with different delimiters
Comment: Gotcha, I wasnt really sure how to word the problem that i have
Comment: Checkout [divmod](https://docs.python.org/3/library/functions.html#divmod)
Comment: The [inflect](https://pypi.org/project/inflect/) module has useful tools for these sorts of sentence constructions.
Answer: First, define your plural function to accept the value and the name, and return the correctly formatted string. No need to mess about with lists passed to the function. We will check if a value is zero before passing it to the plural function.
def plural(value, name):
    if value == 1:
        return f"1 {name}"
    else:
        return f"{value} {name}s"

Next, inside your format_duration, create a list of all the pluralized strings, filtering out values that are zero. Finally, join all but the last element of this list with a comma, and the last element with an and:
def format_duration(seconds):
    result = []
    counter = 0
    if seconds == 0:
        return 'now'

    labels = ["year", "day", "hour", "minute", "second"]

    final_years = int(seconds/31536000)
    final_days = (int(seconds/86400))%365
    final_hours = (int(seconds/3600))%24
    final_minutes = (int(seconds/60))%60
    final_seconds = seconds%60

    formatted_vals = [plural(v, n)
                      for v, n in zip(
                                      [final_years, final_days, final_hours, final_minutes, final_seconds],
                                      labels
                                     )
                      if v != 0]
    if len(formatted_vals) == 1:
        return formatted_vals[0]

    return ", ".join(formatted_vals[:-1]) + " and " + formatted_vals[-1]

Comment: A missed corner case is that `format_duration(58)` returns `' and 58 seconds'`. Another corner case is `format_duration(0)`, but it's not clear if that should return `'0 seconds'` or an empty string.
Comment: Thanks @Steven. `format_duration(0)` returns `'now'`, I just retained that from OP's code


in Pandas how to reference 2 dataframes and replace the column

Question: There are 2 dataframes:
need to use 'Place' ref table to replace (or add a column to indicate) 'Region' in df by 'Code' in ref.
Mind, this is a sample, in real file, there are 100,000+ roles, and more complicated values. Please help
df=pd.DataFrame({'Date': ['1/1/11','1/2/11','1/2/11','1/2/11','1/3/11','1/3/11','1/3/11','1/3/11','1/4/11','1/5/11','1/5/11','1/5/11'],\
'Prod': ['Quad','Bellen','Quad','Bellen','Sunshine','Carlota','Sunset','Sunshine','Sunset','Sunset','Sunshine','Carlota'], \
'Region': ['East','South','West','West','East','MidWest','South','South','MidWest','South','West','West']})

ref=pd.DataFrame({'Place': ['West','East','South','MidWest'],\
'Code':['W','E','S','MW']})

Comment: Can you edit your question to make it clearer what you're asking?
Comment: hi, Im completely new to this site. I'll edit right now
Answer: You need map
df['Region'] = df['Region'].map(ref.set_index('Place')['Code'])

    Date    Prod        Region
0   1/1/11  Quad        E
1   1/2/11  Bellen      S
2   1/2/11  Quad        W
3   1/2/11  Bellen      W
4   1/3/11  Sunshine    E
5   1/3/11  Carlota     MW
6   1/3/11  Sunset      S
7   1/3/11  Sunshine    S
8   1/4/11  Sunset      MW
9   1/5/11  Sunset      S
10  1/5/11  Sunshine    W
11  1/5/11  Carlota     W

Edit: If you want to retain the name of the region that is not present in ref, use
df['Region'] = df['Region'].map(ref.set_index('Place')['Code']).combine_first(df['Region'])

Edit: @Wen is right, you can use replace instead of map
df['Region'].replace(ref.set_index('Place')['Code'])

Comment: @S.Gu maybe you can try replace then .
Comment: Thank you so much.. can I add, if one of value in 'Region' doesn't have reference in ref table (eg. North). What can I do to replace all referenceable value, AND retain 'North' as a valid value in 'Region'? Thanks again
Comment: Yes, definitely :D


Scrapy Spider Parser call function

Question: How can I call the writeXML after my parser finish crawling data? Currently I can see the data crawl but don't see the output file. I tried to print under writeXML no output too.
Below are my code:
class FriendSpider(BaseSpider):
    # identifies of the Spider
    name = "friend"
    count = 0
    allowed_domains = ["example.com.us"]
    start_urls = [
        "http://example.com.us/biz/friendlist/"
    ]

    def start_requests(self):
        for i in range(0,1722,40):
            yield self.make_requests_from_url("http://example.com.us/biz/friendlist/?start=%d" % i)

    def parse(self, response):
        response = response.replace(body=response.body.replace('
', '\n'))
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//ul/li')
        items = []

        for site in sites:
            item = Item()
            self.count += 1
            item['id'] = str(self.count)
            item['name'] = site.select('.//div/div/h4/text()').extract()
            item['address'] = site.select('h4/span/text()').extract()
            item['review'] = ''.join(site.select('.//div[@class="review"]/p/text()').extract())
            item['birthdate'] = site.select('.//div/div/h5/text()').extract()

            items.append(item)
        return items

    def writeXML(self, items):
        root = ET.Element("Test")
        for item in items:
            item= ET.SubElement(root,'item')
            item.set('id', item['id'])
            address= ET.SubElement(item, 'address')
            address.text = item['address']
            user = ET.SubElement(item, 'user')
            user.text = item['user']
            birthdate= ET.SubElement(item, 'birthdate')
            birthdate.text = item['birthdate']
            review = ET.SubElement(item, 'review')
            review.text = item['review']

        # wrap it in an ElementTree instance, and save as XML
        file = open("out.xml", 'w')
        tree = ET.ElementTree(root)
        tree.write(file,xml_declaration=True,encoding='utf-8',method="xml")

Answer: To output using the built-in XML exporter, try the following command:
scrapy crawl friend -o items.xml -t xml

If the output isn't to your liking, then you can try creating your own exporter using the XMLExporter class as a basis.
Comment: I tried use XMLExporter item_element="id" -> it give me  but I want

Scrapy Spider Parser call function


Formatting of DateUtils.getRelativeDateTimeString

Question: I have code like this
DateUtils.getRelativeDateTimeString(context, due, DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS,0)

which is outputting strings formatted like
in 23 hours, 6:18am

I don't understand well the android documentation on this method.
Is there a built in way to strip off the time or change the comma to be more sentence like?
Either of "in 23 hours"  or "in 23 hours at 6:18am" would be preferable to the current output.
Thanks.
Answer: I have used a different method and gotten the "in 23 hours" result I wanted
DateUtils.getRelativeTimeSpanString(due,now, DateUtils.SECOND_IN_MILLIS)

Comment: Unfortunately, you would have to implement the functionality of DateUtils.WEEK_IN_MILLIS yourself
Answer: According to Android Documentation, you'll need to add a flag to display "42 mins ago", instead of "42 mins ago 01/01/2020".
DateUtils.getRelativeTimeSpanString(
    item.createdAt.time,
    Date().time,
    DateUtils.MINUTE_IN_MILLIS,
    FORMAT_ABBREV_RELATIVE
)

Can use FORMAT_ABBREV_RELATIVE flag to use abbreviated relative times, like "42 mins ago".

https://developer.android.com/reference/android/text/format/DateUtils#getRelativeTimeSpanString(long,%20long,%20long,%20int)


How can similar columns be added to all entities without using embedded entity in TypeORM?

Question: If I want to add similar columns to all my entities in TypeORM, for example, each entity should have a CreatedDate and an UpdatedDate column in their respected database table and entity, using TypeORM's built in @CreateDateColumn and @UpdatedDateColumn decorators.  I can achieve this by creating an embedded entity, and it works as expected, but when I query it and it returns its JSON format, the embedded entity is a sub-object.  Is there a way to either flatten that sub-object in the JSON, or add these columns to all entities another way?  I also used inheritance but I want these particular columns to show up as the last columns in the table/entity.  When using inheritance they show up first.
Answer: If you don't want to use composition for that, you can use inheritance with an abstract class.
export abstract class AbstractEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @CreatedDateColumn()
    createdDate: Date;
}

@Entity()
export class MyEntity extends AbstractEntity {
    // Some code
}


How to return a vector of pairs

Question: I am trying to solve this challenge from testdome. I think my approach to the solution is not optimal (or even correct). But before changing my approach I was wondering is it possible to return a vector of pairs? if yes, how?.
Below you will see the challenge, and afterwards my code.
Thank you.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){

            if (list[i]+list[j] == sum)
                list1.push_back(std::make_pair(list[i], list[j]) );
        }
        tracker--;
    }

    return list1; // I am stuck here

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif

EDIT
Initially, this was my solution. But once I posted it on testdome, I am getting zero correct answers out of 4 categories. It is test number 5. That is why I thought, returning only one answer was wrong.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){
            if (list[i]+list[j] == sum)

                return result=std::make_pair(list[i], list[j]);
        }
        tracker--;
    }

    return std::make_pair(-1,-1);

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif

Comment: Yes, it is certainly possible to return a vector of pairs. However your method's signature clearly states that it returns a single pair. Note that the assignment states you need to return _any_ solution, not _all_ solutions.
Comment: you tagged C++17, so you can also return `auto` (`auto findTwoSum(const std::vector& list, int sum)`) and define `indices` using `auto` (`auto indices = findTwoSum(list, 10);`)
Comment: @ypnos I have edited my first post, please have a look. With the code in the edited section I was getting incorrect answers in all 4 categories, I was hoping to get correct in at least one of the categories. That is why I am trying now to return all of the answers.
      _Example case: Wrong answer._
      _Distinct numbers with and without solutions: Wrong answer._
      _Duplicate numbers with and without solutions: Wrong answer_.
      _Performance test with a large list of numbers: Wrong answer._
Answer: Use can do this:
 std::vector<std::pair<int, int> >findTwoSum(const
      std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    /* ...*/
     return list1;
  }
  int main()
 {
      std::vector<int> list = {3, 1, 5, 7, 5, 9};
      auto indices = findTwoSum(list, 10);
      std::cout << indices[0].first << '\n' << indices[0].second;
 }

Answer: You can simply use std::vector<std::pair<int, int>> as the return value of your function. (and not only std::pair<int, int> as you've done in your example)
So your function becomes:
std::vector<std::pair<int, int>> findTwoSum(const std::vector<int>& list, int sum) { ... }

Answer: you just need to switch the function signature to
std::vector<std::pair<int, int>> findTwoSum(const std::vector<int>& list, int sum)

But in the main you are assigning it to a pair, so you need also to change this:
std::pair<int, int> indices = findTwoSum(list, 10); // from
std::vector<std::pair<int, int>> indices = findTwoSum(list, 10); // to
std::vector<std::pair<int, int>> indices { findTwoSum(list, 10) }; // but this is better because you call just one constructor instead of a default constructor and a copy constructor

Comment: Hi, thank you for the answer. Even if I change it like that I am still getting this error _"error: could not convert 'list1' from 'std::vector >' to 'std::pair'"_
Answer: If you want to return a vector of pairs, your function signature should look like
std::vector<std::pair<...>> f();

Your current function is just returning a single std::pair.
Answer: If you are using C++17, you have two options:

use auto return type deduction

auto create_vector_of_pairs() {
    std::vector<std::pair<int, int>> v;
    v.emplace_back(1, 2);
    v.emplace_back(3, 4);
    v.emplace_back(5, 6);
    return v;
}

use std::vector<std::pair<...>> as return type

std::vector<std::pair<int, int>> create_vector_of_pairs() {
    std::vector<std::pair<int, int>> v;
    v.emplace_back(1, 2);
    v.emplace_back(3, 4);
    v.emplace_back(5, 6);
    return v;
}

Then, whatever option from above you choose, in your main function you could do something like:
std::vector<std::pair<int, int>> v = create_vector_of_pairs();

or
auto v = create_vector_of_pairs();

How to return a vector of pairs


MS Excel VBA how to insert a row in the current worksheet and three others

Question: I am using MS Excel 2007 and Microsoft Visula Basic 6.5.
I want to select a row in a sheet and then use a macro to insert a row in this sheet and three others. I am trying the code below however when I run it I get the error "Run-time error '1004': Application-defined or object-defined error" on "Worksheets("Rel. Planning Meeting").Range(Lst).Activate".
Sub Copy1()
Dim Lst As Long
'save the rowNo
Lst = ActiveCell.Row

Worksheets("Rel. Planning Meeting").Activate
Worksheets("Rel. Planning Meeting").Range(Lst).Activate
ActiveCell.EntireRow.Insert

Worksheets("Master Release Plan - HTSTG").Activate
Worksheets("Master Release Plan - HTSTG").Range(Lst).Activate
ActiveCell.EntireRow.Insert

Worksheets("Inst. Gateway").Activate
Worksheets("Inst. Gateway").Range(Lst).Activate
ActiveCell.EntireRow.Insert

Worksheets("CAB").Activate
Worksheets("CAB").Range(Lst).Activate
ActiveCell.EntireRow.Insert

Worksheets("Rel. Planning Meeting").Range("A3:G5000").Copy _
Destination:=Worksheets("Master Release Plan - HTSTG").Range("A3")

Worksheets("Master Release Plan - HTSTG").Range("A3:O5000").Copy _
Destination:=Worksheets("Inst. Gateway").Range("A3")

Worksheets("Inst. Gateway").Range("A3:T5000").Copy _
Destination:=Worksheets("CAB").Range("A3")

End Sub

I have tried "Dim Lst As Range" however then I get the error "Run time error '91': Object variable or With block variable not set" on "Lst = ActiveCell.Row".
Your help is greatly appreciated.
Regards,
Glyn
New Code:
Sub InsertRow()

Dim Lst As Long
'save the rowNo
Lst = ActiveCell.Row

'Insert a row in each worksheet at the currently selected cell.
Worksheets("Rel. Planning Meeting").Rows(Lst).Insert
Worksheets("Master Release Plan - HTSTG").Unprotect
Worksheets("Master Release Plan - HTSTG").Rows(Lst).Insert
Worksheets("Inst. Gateway").Unprotect
Worksheets("Inst. Gateway").Rows(Lst).Insert
Worksheets("CAB").Unprotect
Worksheets("CAB").Rows(Lst).Insert
End Sub

Answer: In addition to @Bharath 's answer it is not necassary and a generally bad idea to use Select.
Your row insertion code can be reduced to
Worksheets("Rel. Planning Meeting").Rows(Lst).Insert
Worksheets("Master Release Plan - HTSTG").Rows(Lst).Insert
Worksheets("Inst. Gateway").Rows(Lst).Insert
Worksheets("CAB").Rows(Lst).Insert

Comment: Didn't see your comment. Wanted to add something about selecting stuff. so edited my comment. +1 for showing how to do it.
Comment: Thanks for the improvement Chris, greatly appreciated. Regards, Glyn.
Answer: in the 2nd line of your code, you are assigning lst, a value(activecell.row), which is a long variable. if you write
Worksheets("Rel. Planning Meeting").Range(Lst).Activate

that means ex - Worksheets("Rel. Planning Meeting").Range(4).Activate, if ur activecell.row is 4. This will not work on a range.
If you want to select a row then change your existing line and all other similar lines, where you have range(lst)  to -
Worksheets("Rel. Planning Meeting").Rows(Lst).Activate

I would suggest not selecting anything on the sheet as far as possible because this may slow up the execution time. Your's is a very simple macro here but it is good practice to avoid selecting or activating stuff on your sheet as much as possible.
Hope this helps.
Comment: Hi Bharath, I can not see my comment thanking you. My appologies I must not have saved it. Anyway, thank you very much, this works. Regards, Glyn.


My controller is strafing left when I hit both triggers

Question: So, I've been playing Warframe lately, and I've noticed that occasionally, when I aim (hold LT) and then fire (hold RT) I strafe left.
I have done some testing, and I have found that it's less consistent if I stop moving before I aim, then fire. It also occasionally triggers if I move while I'm aiming and shooting.
I think it might be a dodgy input in the controller? But I'm not sure. What could be causing this?
Answer: Stick Drift.
Simply put, your controller may be off by a small amount. This can happen for a variety of reasons.
Test for stick drift and recalibrate.
Should not be too hard, with access to a pc.
Comment: @Ben Yes. Wear-and-tear and build-up of dirt are both very common causes of stick drift in older, well-used, controllers. [Replacing or cleaning the sticks are the respective solutions](https://devicetests.com/why-does-your-controller-drift)
Comment: Thanks for the answer! I forgot to add it to my question, but it has only occurred recently that I know of, and the controller of fairly old, would that have any impact?


How to get the item to be discarded in python deque?

Question: Suppose we have a deque with maxlen=3. If the deque already have 3 items and when I append a new item, how can I get the item that's going to be discarded?
The reason is that I want to maintain a window in memory that only contains the last N item, and when the window is full and one item is to be discarded, I need to get that item and do some extra work.
Here's my current solution:
from collection import deque

MAX_LEN=10

q = deque(maxlen=MAX_LEN)

while True:
    if len(q) == MAX_LEN:
        discarded = q.popleft()
        process(discarded)
    q.append(some_var)

Is this the best I can get? I've thought of using list and slice the list to limit size/get discarded item, but the if is unavoidable. Using deque at least I can get O(1) performance in the push and popleft operation.
Any ideas?
Comment: What are you hoping to achieve here? There's no way the length test has a significant impact on performance, so what do you have to gain by trying to optimize it away? Besides, one way or another, you *must* check if you're at the maximum length, so the most I think you can do is `process(q.popleft())` without the interim variable binding to `discarded`.
Comment: Why not `process(q[0]); q.append(some_var)`?
Comment: @Bakuriu I need to process the one that's to be discarded. So the queue starts with 0 item, and when it reaches 3 item, I need to start processing `q[0]`. I just want to avoid the `if` comparison in the loop.
Comment: There's nothing wrong with your code, nor do I think you can do it any better. Although you *can* get rid of the `discarded` variable. And you *could* create a new subclass to do this for you
Comment: The `deque` is the right data structure (in terms of efficiency), but it doesn't provide a "built-in" way of achieving what you want (which basically is a callback to be used in conjunction with `maxlen`...). The only way to avoid the explicit `if` is to hide it into some code that could be a subclass or (IMHO better) a simple wrapper of the `deque`.
Comment: I think one would like leave the discarding to the deque, that's its job, but have a way of retrieving discarded elements anyway. This code, while functional, feels more like a hack on deque than a real solution.
Comment: @njzk2 You are right. In fact the above code would work as well without using `maxlen` at all.
Comment: @Bakuriu : exactly. all that testing and poping items is really what a deque does. It feels frustrating to re-write it.
Comment: @AbhishekBansal Can you show an example of a simpler queue? AFAIK `deque` *is* the simplest and fastest queue the stdlib provides. Note that the `queue` module provides *synchronized* queues, which are only useful when using multi-threading.
Comment: @Bakuriu yes, actually you are right.
Comment: Is your maxlen really only 3? If it is... just make your own. It'll probably be faster too. Or was that just "for example"?
Comment: If you can fit the generation of new values into a generator. You could create a dequee or tee based generator holding a 3 wide sized window of the iteration. Then you could read the first element of each yield, instead of pop and append each iteration.
Answer: The intended way to get the item about to be discarded is with indexed lookup: [0]:
>>> from collections import deque

>>> d = deque('abc', maxlen=3)
>>> about_to_be_discarded = d[0]
>>> about_to_be_discarded
'a'
>>> d.append('d')
>>> d
deque(['b', 'c', 'd'], maxlen=3)

The secondary problem is avoiding an if to determine whether the deque is full.  One approach is to have two separate loops, one that initially fills the window and another that handles discards as new values are loaded:
d = deque(maxlen=n)
for i in range(n):
    d.append(get_input_value())
while True:
    discard = d[0]
    d.append(get_input_value())
    process(discard)

Answer: Something like this might work for you.
def pairwise(iterable, n=2 ):
    from itertools import tee, islice, izip
    return izip(*(islice(it,pos,None) for pos,it in enumerate(tee(iterable, n))))

for values in pairwise(infinite_iterable_generating_your_values, n=3):
    process(values[0])
    if breakconditions:
        break

example of the pairwise function:
print [i for i in pairwise(range(10), n=3)]

[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]


vb.net byte[] to C++ char*

Question: I am calling an unmanaged C++ dll that expects a char* as one of its parameters and I want to push a byte[] into it.  The project is written in VB.NET.
What type of marshalling will work for this?
Answer: If you need to pin a managed structure in order to pass it as a parameter you can use the following code.
<code>    // (c) 2007 Marc Clifton
    /// <summary>
    /// A helper class for pinning a managed structure so that it is suitable for
    /// unmanaged calls. A pinned object will not be collected and will not be moved
    /// by the GC until explicitly freed.
    /// </summary>

    internal class PinnedObject<T> : IDisposable where T : struct
    {
        protected T managedObject;
        protected GCHandle handle;
        protected IntPtr ptr;
        protected bool disposed;

        public T ManangedObject
        {
            get
            {
                return (T)handle.Target;
            }
            set
            {
                Marshal.StructureToPtr(value, ptr, false);
            }
        }

        public IntPtr Pointer
        {
            get { return ptr; }
        }

        public int Size
        {
            get { return Marshal.SizeOf(managedObject); }
        }

        public PinnedObject()
        {
            managedObject = new T();
            handle = GCHandle.Alloc(managedObject, GCHandleType.Pinned);
            ptr = handle.AddrOfPinnedObject();
        }

        ~PinnedObject()
        {
            Dispose();
        }

        public void Dispose()
        {
            if (!disposed)
            {
                if (handle.IsAllocated)
                    handle.Free();
                ptr = IntPtr.Zero;
                disposed = true;
            }
        }
    }
}
</code>
You can then call the unmanaged code using PinnedObject.Pointer.  In your extern declaration, use IntPtr as the Type for that parameter.
<code>PinnedObject<BatteryQueryInformation> pinBatteryQueryInfo = new PinnedObject<BatteryQueryInformation>();
pinBatteryQueryInfo.ManangedObject = _structBatteryQueryInfo;
Unmanaged.Method(pinBatteryQueryInfo.Pointer);
</code>
Answer: I'm not a .net expert, but I've needed to do something similar recently.
It is not just a matter of serialization, you also have to stop the garbage collector from cleaning up your byte array while it is being used in C++ land...
The below snippet of C# should help.
// pin the byte[] (byteArray)
GCHandle handle = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();
// Do your C++ stuff, using the address pointer.

// Cleanup
handle.Free();
Answer: In your PInvoke definition just declare the char* parameter as a byte[] and the standard marshaller will handle work.
But this may or may not be the best idea.  Is the C++ function expecting a string or is it expecting a buffer of data (C/C++ code often uses char* for a buffer, relying on the fact that a char is one byte)?
If it is a buffer then a byte[] is certainly correct, but if it expects a string then it may be clearer if you declare the parameter as a string (to be explicit) and use Encoding.ASCII.GetString() to convert the byte[] to a string.
Also if it C++ function expects a string and you decide to declare the parameter as a byte[], be sure the byte array ends with a zero, since that is how C/C++ determines the end of the string.

vb.net byte[] to C++ char*


update xml file at runtime in flex

Question: How can I add new nodes/elements/properties to the existing xml file at runtime in flex.
I have a xml file which is used to display components in flex.
I want to add/edit component and their properties at runtime.
xml file sample:
<code><view id="productView" label="Products">
<panel id="chartPanel" type="CHART" ChartType="Pie2D" title="Productwise Sales"  x="215" y="80" width="425" height="240" showValues="0" >
  < /panel>
< /view>
</code>
To add new component I have created an object with all the properties and elements of components. How can I convert this object in xml format and update the existing xml file?
Thanks in advance!
Comment: By "xml" are you referring to a flex .mxml component, or do you have your own custom markup language which is loaded at runtime, parsed, and used to render components?
Comment: Here "xml" is pure xml file. At runtime im parsing this xml file to render components.
I want to add new compnents at runtime and update this xml file.
Comment: Basically i want to create Designer kind of thing, using which user can add/edit components and properties of view/dashboard. i am storing view structure in a xml file. i parsed that file at runtime and display view. Basically How to convert an object (having values,properties and sub-objects) to xml and add that xml to the existing xml file. so that next time when i parsed xml file i'll get that new component in my view/dashboard.
Answer: There is not direct way to do so.
If you wanna create objects which is dinamically created trought XML, you must wrap each component which you are planing to use.
If i were on such a problem to solve, i would probably create a proxy class, which primary target will be to produce objects out of the xml, and check if the objects ( represented by their name ) exists - just to apply the new properties.
you basically shall override each class which you are planing to use in order to be refreshed trought XML ( some Interface implementation would do the job here, due the common behaviour ).

update xml file at runtime in flex


How to bind FormBuilder input in other to send output postData to the API?

Question: HTML:

        <form [formGroup]="register_form" (ngSubmit)="register()" padding>

            <ion-item class="input-item">
                <ion-label>
                    <ion-icon name="md-person"></ion-icon> usuário
                </ion-label>
                <ion-input formControlName="username" type="text" ></ion-input>
            </ion-item>

            <ion-item class="input-item">
                <ion-label>
                    <ion-icon name="md-contact"></ion-icon> Nome
                </ion-label>
                <ion-input formControlName="name" type="text"></ion-input>
            </ion-item>

            <ion-item class="input-item">
                <ion-label>
                    <ion-icon name="md-mail"></ion-icon> Email
                </ion-label>
                <ion-input formControlName="email" type="email"></ion-input>
            </ion-item>

                <ion-item class="input-item">

                    <ion-label>
                        <ion-icon name="md-lock"></ion-icon> Senha
                    </ion-label>
                    <ion-input formControlName="password" type="{{password_input_type}}"></ion-input>
                </ion-item>

                    <ion-icon name="{{show_hide_icon}}"></ion-icon>

            <button class="register-button" color="secondary" ion-button icon-start type="submit" [disabled]="!register_form.valid">
                <ion-icon name="log-in"></ion-icon>
                Registrar
            </button>

        </form>

Register.ts:
import {Validators, FormBuilder, FormGroup } from '@angular/forms';
import { AuthServiceProvider } from "../../providers/auth-service/auth-service";

export class RegisterPage {

    //Defaults
    register_form: any;

constructor(public navCtrl: NavController, private formBuilder: FormBuilder,
          private loadingCtrl: LoadingController,  private alertCtrl: AlertController,  public authServiceProvider: AuthServiceProvider) {

        // declare the register form
        this.register_form = this.formBuilder.group({
          name:['', Validators.required],
          username: ['', Validators.required],
          email: ['', [Validators.required, Validators.email]],
          password: ['', [Validators.minLength(this.password_max_length),Validators.required]],
        });
    }

   register() {

        this.authServiceProvider.postData(this.register_form, "signup").then((result)=>{

            this.responseData = result;
            console.log(this.responseData);
            localStorage.setItem('register_form', JSON.stringify(this.responseData))

            this.navCtrl.push(EmpresaPage);

        }, (err)=>{

            console.log(err);
        });

NS: I didn't past all the input feeds in the HTML section
Answer: You might want to post your authServiceProvider function aswell.
I'm not sure if I understand your question but you can use register_form.value to get an object representing your form.
Comment: let apiUrl = "http://localhost/PHP-Slim-Restful-master/api/";

@Injectable()
export class AuthServiceProvider {

  constructor(public http: Http) {
    console.log('Hello AuthServiceProvider Provider');
  }

  postData(credentials, type){
    return new Promise((resolve, reject)=>{

      let headers = new Headers();
      this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).subscribe(res=>{

        resolve(res.json());

      }), (err)=>{

        reject(err);
      }
    });
  }

}
Answer: Maybe I missunderstand you, if you want to post the inputs to your api you hast to get the values from "register_forms". See https://angular.io/api/forms/AbstractControl#value
register() {

    this.authServiceProvider.postData(this.register_form.value, "signup").then((result)=>{

        this.responseData = result;
        console.log(this.responseData);
        localStorage.setItem('register_form', JSON.stringify(this.responseData))

        this.navCtrl.push(EmpresaPage);

    }, (err)=>{

        console.log(err);
    });

Comment: Thank you, but it shows "unexpected token" in the console, meanwhile, i have already use postman to call the same API, it was working fine with the same parameters


Xen vm stuck at grub prompt

Question: How can I get my Ubuntu server booting again?   Is there a tool that would auto-fix this situation?

No matter how many ways I run the "boot fixer" using a virtual image of
boot-repair-disk-64bit.iso
It claims success, I eject the CD ISO image (within XenCenter console), reboot, but my Ubuntu 14.04 server still keeps getting stuck at a grub prompt without booting.  This started after a power failure which took down all VMs and the XenServer itself.
The disk layout as seen by boot-repair-disk :
=================== df -Th:

Filesystem     Type       Size  Used Avail Use% Mounted on
/cow           overlayfs  3.8G   20M  3.8G   1% /
udev           devtmpfs   3.9G  8.0K  3.9G   1% /dev
tmpfs          tmpfs      773M  712K  773M   1% /run
/dev/sr0       iso9660    508M  508M     0 100% /cdrom
/dev/loop0     squashfs   435M  435M     0 100% /rofs
none           tmpfs      4.0K     0  4.0K   0% /sys/fs/cgroup
tmpfs          tmpfs      3.8G  8.0K  3.8G   1% /tmp
none           tmpfs      5.0M     0  5.0M   0% /run/lock
none           tmpfs      3.8G     0  3.8G   0% /run/shm
none           tmpfs      100M   12K  100M   1% /run/user
/dev/xvda1     ext4       395G  363G   13G  97% /mnt/boot-sav/xvda1

=================== fdisk -l:

Disk /dev/xvda: 430.6 GB, 430570471424 bytes
255 heads, 63 sectors/track, 52347 cylinders, total 840957952 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000be05e

Device Boot      Start         End      Blocks   Id  System
/dev/xvda1   *        2048   840955903   420476928   83  Linux

/boot/grub/device.map :
(hd0) /dev/xvda

(same as the output from grub-mkdevicemap --device-map=/dev/stdout)
/boot/grub/menu.lst :
 - All lines that are either blank or begin with a # (comment).

Its log is at:
http://paste.ubuntu.com/9710907/
This is a non-EFI host and system at all levels as far as I can tell.
The virtual machine's host OS is pretty much up to date, installed from:
XenServer.Creedence.20141212.RC90239.iso
Answer: NOT an acceptable solution, but just a workaround for those in a similar situation, needing to get the server started at least temporarily:
grub>

set root=(hd0,1)
linux /vmlinuz  root=/dev/xvda1   ro
initrd /initrd.img
boot

NOTE:
after booting, update-grub seems to run fine, but a reboot lands into the same helplessly stuck grub> prompt...
Same with grub-install /dev/xvda
Comment: Related? http://unix.stackexchange.com/questions/10089/debian-6-0-and-xen-pygrub-failure  and http://serverfault.com/questions/407103/xvd-device-support-with-gentoo-running-in-xen-hvm-guest   `mknod` trick , check for missing /dev/xvd* ...
Comment: did you find a real fix in the end?

Xen vm stuck at grub prompt