Operador ternário " ?: "

Question: Recentemente entrei em uma discução com os colegas de trabalho sobre a funcionalidade mais compacta do if ternário ( x ?: 10) e alguns deles disseram que o mesmo seria retirado no php 7. Fiz uma busca na web e não achei nada relacionado a isso.
Existe alguma informação sobre isso?
Comment: Nem sei o que fazer com esta pergunta. Fechei agora como não claro por faltar uma informação que indique sobre isso. Se for só rumor acéfalo acho que é fora de de escopo, se for algo pra levar a sério talvez dê para responder ou talvez seja baseada em opinião, ou até duplicata já que o assunto, no geral, já foi abordado algumas vezes.
Comment: Eu acho que ele só quis saber se o operador foi retirado no PHP7 (não foi), porque parece que os colegas se confundiram com a introdução do `Null Coalescing`.
Comment: No mínimo baseada em opiniões. Não há registros da remoção do operador em qualquer parte da documentação, mesmo ela estando atualizada para versão 7. Tanto que a informação sobre esse operador está ao lado do `null coallesce`, que devem ter se confundido.
Comment: As pessoas adoram inventar boatos baseado em pedaços de informações, lembro da época que falavam que require era lento e include rápido. PHP é uma zona de boatos por parte dos desenvolvedores infelizmente :/
Comment: Até hoje não removeram a palavra chave `var` ou o comportamento do construtor com o mesmo nome da classe. Leva algumas eras para o pessoal do desenvolvimento retirar qualquer coisa na linguagem.
Comment: Então, durante a discussão um deles falou que disseram essa informação em uma palestra sobre PHP. Eu fiz uma pesquisa e não achei nada dizendo que essa funcionalidade seria tirada no PHP 7. E também achei estranho por causa da insersão da null Coalescing, que é uma melhoria do elvis operator. Resolvi perguntar para saber se mais alguém tinha essa informação da retirada da funcionalidade.
Answer: O nome desse operador é elvis operator.
Ele ainda existe no PHP 7. Pode ser só questão de compatibilidade ou até visando por conforto para quem já é acostumado, mas só quem desenvolve a linguagem pode responder com certeza.
No PHP 7 existe null coalescing operator (??) e este operador faz a mesma coisaver edição.
A principal diferença entre eles é que o null coalesce não vai gerar um E_NOTICE quando a variável não for definida.
$a = null;

print $a ?? 'não há valor';  // Saída: não há valor
print $a ?: 'não há valor';  // Saída: não há valor

print $b ?? 'não há valor';  // Saída: não há valor
print $b ?: 'não há valor';  // Notice: Undefined variable: b

Edit:
Eles não fazem exatamente a mesma coisa, há uma diferença importante ainda não mencionada. O operador null coalescing (??) avalia sua segunda expressão apenas se a primeira expressão for null ou não atribuída ainda. Ex.:
null ?? 'Teste'  == 'Teste';

Já o operador Elvis avalia a segunda expressão apenas se a primeira expressão for falsy, ou seja, um valor que, se convertido para boolean, tem o valor false. Veja esta resposta com uma explicação mais detalhada. Ex.:
0 ?: 'Teste'  == 'Teste';

Alguns exemplos que demonstram a diferença entre os operadores:
null ?: 'Nope' == Nope
null ?? 'Nope' == Nope

'' ?: 'Nope' == Nope
'' ?? 'Nope' == ''

' ' ?: 'Nope' == ' '
' ' ?? 'Nope' == ' '

false ?: 'Nope' == Nope
false ?? 'Nope' == false

0 ?: 'Nope' == Nope
0 ?? 'Nope' == 0

1 ?: 'Nope' == 1
1 ?? 'Nope' == 1

[] ?: 'Nope' == Nope
[] ?? 'Nope' == []

Repl.it com o código funcionando.
Comment: É exatamente isso.
Acredito que meu colega estava errado sobre a retirada da funcionalidade. Fiquei com a pulga atrás da orelha porque o mesmo disse que ouviu essa informção em uma palestra sobre php há pouco tempo.

Operador ternário " ?: "


Help with Euler Substitution

Question: Let $a < 0$. Find the following indefinite integral by using the third Euler substitution.
$$\int \frac{dx}{(x^2 + a^2) \sqrt{x^2 - a^2}}$$
Where the third Euler substitution is defined by:
Given an integral of the form $\int R(x, \sqrt{ax^2 + bx + c})dx,$ $a \neq 0$.
If the quadratic polynomial under the radical has 2 distinct real roots $\alpha_1$ and $\alpha_2$ i.e.,
$$ax^2 + bx + c = a(x-\alpha_1)(x - \alpha_2),$$
then set
$$\sqrt{ax^2 + bx + c} = t(x - \alpha_{1 \text{ or } 2}).$$
Hint: $t^4 + 1 = (t^2 - \sqrt 2t + 1)(t^2 + \sqrt 2t + 1)$.
I tried beginning by setting $$\sqrt{x^2 - a^2} = t(x-a)$$ and attempted to solve for $x$ in order to find some function to define $dx$ in terms of $dt$ but I'm having some trouble. I'm not quite sure how to apply the hint here.
Thanks in advance.
Comment: Ahh, the exponents aren't very legible in the first integral.The denominator is (x^2 + a^2) * sqrt(x^2 - a^2)
Sorry, I'm new to MathJax.
Answer: I went with $\sqrt{x^2-a^2}=t (x+a)$, although I doubt it matters.  In any case, there's just a bunch of algebra to work through:
$$t=\sqrt{\frac{x-a}{x+a}} \implies x = a \frac{1+t^2}{1-t^2}$$
$$dx = \frac{4 a t}{(1-t^2)^2} dt$$
$$x^2+a^2 = 2 a^2 \frac{1+t^4}{(1-t^2)^2}$$
$$x^2-a^2 = a^2 \frac{4 t^2}{(1-t^2)^2}$$
so that
$$\begin{align} \int \frac{dx}{(x^2+a^2) \sqrt{x^2-a^2}} &= \frac{2a}{a^3} \int dt  \frac{t}{(1-t^2)^2} \frac{(1-t^2)^2}{1+t^4} \frac{1-t^2}{2 t}\\ &= \frac{1}{a^2} \int dt \frac{1-t^2}{1+t^4} \end{align}$$
Now put that hint to good use.  Actually, I'll give you a better one:
$$\frac{1-t^2}{1+t^4} = \frac{1}{2 \sqrt{2}} \left ( \frac{2 t + \sqrt{2}}{t^2+\sqrt{2} t+1} - \frac{2 t - \sqrt{2}}{t^2-\sqrt{2} t+1} \right )$$
Note that the fractions are of the form $h'(t)/h(t)$ for some function $h$.
Comment: @ellipsis318: no, you caught an error of mine via transcription.  Glad you are checking this and following through!  I will edit for completeness.
Comment: Yes, that's what it is called.  I provided that last expression because it turned out to be a little trickier than I first thought, and I didn't want to leave you hanging.  Yes, nice how it all worked out, but less surprising given @julien's solution below (which is a much more natural way to evaluate this integral, to be sure; your assignment required that it be done this way, though).
Comment: There's just one thing I'd like to verify. For the step when you find:
$$x^2 + a^2 = a^2\frac{1+t^4}{(1-t^2)^2},$$ I'm getting the same answer just multiplied by 2. i.e,
$$2a^2\frac{1+t^4}{(1-t^2)^2}$$
My process being:
$$x^2 + a^2 = (\frac{a(1+t^2)}{(1-t^2)})^2 + a^2\frac{(1-t^2)^2}{(1-t^2)^2}$$
which gives
$$a^2\frac{(1+2t^2+t^4)+(1-2t^2+t^4)}{(1-t^2)^2} = a^2\frac{2(1+t^4)}{(1-t^2)^2}$$
Am I making some error?
Comment: Okay, thanks again! Writing that comment with proper syntax took a few tries for me, haha.
Comment: Good job on that!
Comment: You use partial fractions after applying the hint, right? Awesome how it turns out to be the perfect format for substitution.
Answer: Here is an alternative which does not really answer the question, but proposes a way to check the answer.
I recall that in such a situation, the trigonometric substitution
$$
x=a\sec\theta \qquad dx=a\sec\theta\tan\theta d\theta
$$
could help.
So I tried and I found it yields, after simplification
$$
\frac{1}{a^2}\int\frac{\cos \theta}{2-\sin^2\theta}d\theta.
$$
Now change the variable again with $u=\sin\theta$ to get
$$
\frac{1}{a^2}\int \frac{du}{2-u^2}=\frac{1}{2\sqrt{2}a^2}\int \left(\frac{1}{u-\sqrt{2}}-\frac{1}{u+\sqrt{2}}\right)du
$$
$$
\frac{\sqrt{2}}{4a^2}\log\lvert\frac{u-\sqrt{2}}{u+\sqrt{2}} \rvert +C.
$$
Can I let you substitute back to get functions of $x$?
You can use
$$
\sin \mbox{arcsec}(x/a)=-\frac{\sqrt{x^2-a^2}}{x}
$$
for $x<a<0$.
Comment: @rlgordonma I know, I was just proposing an alternative to double check the answer.
Comment: The point was to employ that particular substitution.

Help with Euler Substitution


Using NSUInteger Input to insertObject:___ atIndex:___

Question: I'm trying to create a simple commandline tic-tac-toe game using an NSMutableArray.
Created a class called "Board" with the method "getPosition"
(I'm assuming this is the best way to get a user input)
I'm asking for position, then casting from int to NSUInteger)
#import "Board.h"

@implementation Board

-(void)getPosition;
{
    int enteredPosition;
    scanf("%i", &enteredPosition);
    NSUInteger nsEnteredPosition = (NSUInteger ) enteredPosition;
    NSLog(@"Position = %lu", (unsigned long)nsEnteredPosition);
}

#import <Foundation/Foundation.h>
#import "Board.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSString *currentPlayer;
        NSMutableArray *gameBoard=[[NSMutableArray alloc] initWithCapacity:9];

        for(int i; i<=2; i++)
        {
            if(i %2)
            {
                currentPlayer=@"X";
            }
            else
            {
                currentPlayer=@"O";
            }

        NSLog(@"Player %@, select an open spot 1 - 9 on the board", currentPlayer);
        Board *currentPosition = [[Board alloc] init];
        [currentPosition getPosition];
        [gameBoard insertObject:currentPlayer atIndex:currentPosition]; //this is where i have a problem
        }

As I understand it atIndex requires an NSUInteger parameter, but I'm receiving the error message:

"Incompatible pointer to integer conversion sending 'Board *_strong"
  to parameter of type 'NSUInteger' (aka 'unassigned long')
Answer: You're using currentPosition as your index which is a Board object. Perhaps [currentPosition getPosition] is supposed to return an NSUInteger. If so, try rewriting the last portion of your code like this:
Board *theBoard = [[Board alloc] init];
NSUInteger currentPosition = [theBoard getPosition];
[gameBoard insertObject:currentPlayer atIndex:currentPosition]; //this is where i have a problem

Comment: Thanks @somegeekintn, however when I change the code to that, I receive the following error: "Initializing 'NSUInteger" (aka 'unsigned long') with and expression of incompatible type void. Is it because I've defined method in Board class to return (void)? I tried changing it but doesn't seem to help.
Comment: Perhaps. It might be helpful to amend the question showing the source for the Board class as well.
Comment: Nevermind. I think I fix it now. I needed to change the getPosition method type from (void) to (int) both my class header and implementation files.


Smallest subfield containing $F$ and $\alpha$

Question: Let $F$ be a field and let $K$ be an extension of $F$. Show that if $\alpha\in K$ is algebraic over $F$, $F[\alpha]=\{p(\alpha)\mid p(x)\in F[x]\}$ is the smallest subfield of $K$ containing $F$ and $\alpha$.
Comment: @user72870 The interesting part is division, for this, consider the minimal polynomial $g(x)$ for $\alpha$ over $F$, note that it must be irreducible... given $p(x)\in F[x]$ not having $\alpha$ as a root, can you find $f(x),h(x)\in F[x]$ such that $f(x) p(x) + h(x) g(x) = 1$ ? what does that imply?
Comment: Show $F[\alpha]$ is a subfield, and show any subfield containing $F$ and $\alpha$ must contain $F[\alpha]$.
Comment: That's only true if $\alpha$ is algebraic over $F$.
Comment: Thanks, I've edited :)
Any idea for the proof?
Comment: For division, it is enough to show that for every non-zero $\beta$ that is algebraic over $F$, $1/\beta \in F[\beta]$. Applying this to an arbitrary (non-zero) element $\beta = p(\alpha) \in F[\alpha]$ shows that $F[\alpha]$ is a field.
Answer: You have to show that (1) $F[\alpha]$ is a field, and (2) that whenever $K$ is a field with $F \subseteq K$ and $\alpha \in K$, then $F[\alpha] \subseteq K$.
Once you have shown (1), then (2) is not too hard: Assume that $K$ is a field with $F \subseteq K$ and $\alpha \in K$. Then surely all elements of the form
$$a_0 + a_1 \alpha + a_2 \alpha^2 + \cdots + a_n \alpha^n$$
with $a_i \in F$ and $n \in \mathbb{N}$ must be elements of $K$, i.e. $F[\alpha] \subseteq K$.
Thus it remains to show (1). The proof relies on the fact that $\alpha$ is algebraic over $F$. Let $p(x)$ denote the minimal polynomial of $\alpha$ over $F$. Then in fact the ring $F[x]/(p(x))$ will be isomorphic to $F[\alpha]$ (as rings). If you can show this, and that $F[x]/(p(x))$ is a field, then you're done.


Best way to check jQuery POST method parameters for reducing jsp prepared statement query extra function

Question: How can I make Submit TRUE result I mean from 2 INPUT field how to POST only one field of value to same JSP page like
<% string param=req.......

The most important thing is my PreparedStatement of jdbc have to be written twice for reason of two fields ... for checking Oracle DB of EMPLOYEE NO || NAME
By using Name field it's working fine and after changing of code by using Number it's working fine but I want you to help me is there any good way to code this stuff
this is HTML Form
 <form id="contact" method="get">
             Employee No:  <input type="text" id="contact_number" size="15" name="number"/>

        Employee Name: <input type="text" id="contact_name" size="25" name="name"/>

    <input type="submit"/>
        </form>

This is validation jQuery
$(document).ready(function() {
    $("#contact").submit(function() {
        if (($('#contact_number').val().length !== 0) && ($('#contact_name').val().length !== 0)) {
            return false;
        } else if (($('#contact_number').val().length === 0) && ($('#contact_name').val().length === 0)) {
            return false;
        } else {
            return true;
        }
    });
});

This is complete JSP & String sql="Oracle query" & JDBC
<%String number = request.getParameter("number");
String name = request.getParameter("name");
if (name != null) { %>

 Search results for   <%= name %>

<% }
else { %>

 Enter any Information on above field ...

<% } %>

<%@page import="java.sql.*" %>
<%Class.forName("oracle.jdbc.driver.OracleDriver");
String sql="SELECT * FROM RWEMP WHERE ENAME= ?";
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hari","root");
PreparedStatement stat=con.prepareStatement(sql);
stat.setString(1,name);
ResultSet rs=stat.executeQuery();
try {
    if(rs!=null) {
        %>

         Emp ID
         Emp Name
         Emp Dept
         Emp D.o.B
         Show Record
         Record Update
         Compassionate

        <%
        while(rs.next()) {
            %>

            <%= rs.getString("EID")%>
            <%= rs.getString("ENAME") %>
            <%= rs.getString("EDEPT")%>
            <%= rs.getString("EDOB")%>
            <input class="ui-button" type="button" onSubmit="result.jsp" target="destination" value="Show">
            <input class="ui-button" type="button" onclick="update.jsp" target="destination" value="update">
            <input class="ui-button" type="button" onclick="compassionate.jsp" target="destination" value="Compassionate">

            <%
        }
    }
}
catch(SQLException e) {
    e.printStackTrace();
}
con.close();
%>

For more Viewing Look at this Fiddle's HTML output only
Comment: please explain point 1 a bit more its unclear why you want to post only 1 value?
Comment: Employee Number [   ]    &  Employee name [  ]  ... is >> Form <<  &&  if user Enters Value of any one field ... it is okay ..

 i have a Query for DB search in only one coloum filed search ...  so i want to get " HTML FORM RESULT (  of only one value ) " ..

if  user enters two FORM FIELDS VALUES .. form wont send any thing ...
Comment: i want to make sure to send only one result to JSP page .. which is  either from ** NUMBER **   or ** Name **
Comment: so why dont you just put a restriction on form submit to enter only one field
Comment: yes i did ... and  that  " only one field option is working " ..User had a Choice of Searching by  NUMBER  or NAME...  so if he enters Number .. the REAL PROBLEM COMES OUT .. i don't know how to test in best way .. i just did by Considering *** 2 request.getparament()'s *** .. and again checking in JSP ...  it looks like that was odd .. so i want best way
Comment: for that put a dropdown which say select the criteria of search in your case is number and name and then provide him with a input field so when you submit form you have both columname and data to the next page
Answer:
How can i make Submit TRUE result ... i mean from 2 INPUT field .. how
  to POST only one Field of Value to same JSP page ... like :- <% string
  param=req.......

To do that put a dropdown which say select the criteria of search in your case is number and name and then provide him with a input field so when you submit form you have both columname and data to the next page and you dont have write 2 queries.Form should be like this

If possible help me that if user Click on Particular userS table row
  ... how to SEND that user row details to others jsp page ... for
  complete record viewing or record editing purpose

Solution :Pass id of that row to other page
Create a column on each row name say Detail and do
<a href="/detailed.jsp?user_id="<%=user_id%>>Detail

On detailed.jsp get value of user_id from get parameter and the apply the query with user_id to get all the details of that row


How to know whether a polyhedron fits within another?

Question: I need to know whether a sofa fits within an elevator.
I know their dimensions, and I found this topic.
However, does it check the fitting regardless of the orientation of the contained solid ? Or does it only try translating the moving object inside the container without changing its orientation ?
I know a bit about linear algebra but pretty much nothing about convex optimization.
Comment: There are two different questions: does the sofa fits ? It is possible to enter the sofa in the lift ? The first is difficult. The second awful.
Comment: In 3 dimensions, I assume. Correct?
Comment: Is your sofa convex? Or are you using its convex hull?
Answer: This is a difficult problem in its full generality.
There is actually a paper entitled,
"On Moving a Sofa Around a Corner,"
discussed at this MO question.
See also Sofa in a snaky 3D corridor:

Hammerslay's "sofa" in a corridor.


How to access Google CloudML REST API from NodeJS application running in appengine

Question: I am running my prediction running in CloudML. I want to invoke predict REST API from my NodeJS application and I want to show the prediction result in the NodeJS app running in AppEngine.
I can find the documentation to do it for Python application. But can't find it for NodeJS.
Can I use normal rest client like node-rest-client? If yes how can I pass the Google Application Default Credentials?
Answer: Yes you can use the normal node-rest-client, but since the process for Google Application Default Credentials isn't baked into that client you'll have to use https://github.com/googleapis/google-auth-library-nodejs to use Application Default Credentials.
Alternatively you can use the https://github.com/googleapis/google-api-nodejs-client which should support ADC out of the box. You can find the Cloud ML API here:
https://github.com/googleapis/google-api-nodejs-client/blob/master/src/apis/ml/v1.ts
Specifically, you're looking for the "predict" method.
Comment: But https://github.com/google/google-api-nodejs-client does not have API for CloudML
Comment: Yes it does. I have updated my answer to reflect that.


What are the characteristics of a signal from a typical electric guitar?

Question: A standard electric guitar utilizes passive induction pick-ups, which generate fluctuating voltage as the vibrating string moves in a magnetic field. This is high-school physics. Because it's passive, the signal is likely to be unbalanced - the signal coming down the guitar cable is a literal reflection of how each string interacts with the magnetic field[s], not how much noise each string is making.
But, how is it unbalanced? It will vary slightly between strings and pickups but your lower strings are heavier than your higher strings, and your higher strings vibrate faster than your lowers strings - both of these factors should have an effect.
What are the characteristics of a typical signal? Is a signal typically weak in the bottom end, weak in the mid-range, or weak in high-end?
Comment: Well, it will be unbalanced mostly because you send it over an unbalanced line, i.e., you basically ground one of the ends of the coil that is in the sensor.
Comment: Google search of "guitar pickup physics" yields several articles like this http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&ved=0CEEQFjAF&url=http%3A%2F%2Fwww.physics.princeton.edu%2F~mcdonald%2Fexamples%2Fguitar.pdf&ei=N9SFVNKYN8mnyASfhYDICQ&usg=AFQjCNHCICedwueUdFZa0F90XRPgINYC3g&sig2=Oi7Tg-3a03VLde1vQPdF1g&bvm=bv.80642063,d.aWw
Comment: Interesting - I'll try to dig through it - but I'm really after skipping to the end result, i.e. by asking the question hoping someone who knows that stuff well can explain what the implications are.
Comment: "This is high school physics." It's not nice to assume that we all took physics, ever.
Comment: Why do you think I bothered explaining things in my first paragraph, except for those who don't know the physics?
Answer: The similarity between "how much noise each string is making" and "how each string interacts with the magnetic field" is greater than your question implies.
In an acoustic guitar

The vibration of the string transfers through the bridge of the guitar to the sounding board. This saps energy from the string causing its vibration to decay.
The sounding board transfers its vibration to the air, by virtue of being a big flat surface that pushes and pulls air as it vibrates. This saps energy from the sound board causing its vibration to decay. The sound board has resonances of its own that affect the tone of the sound.
Other components resonate or absorb vibrations at certain frequencies - the neck via the nut, etc. This subtly affects the overall tone and sustain of the instrument.

In an electric guitar

The vibration of the string transfers through magnetic induction to the pickup. This saps energy from the string causing its vibration to decay.
The resulting electric current is carried to effects, amp, speaker. These components have properties of their own that affect the sound.
Other components resonate or absorb vibrations at certain frequencies - the body of the guitar via the bridge, the neck via the nut, etc. This subtly affects the overall tone and sustain of the instrument.

The actual vibration of an acoustic string versus an electric string isn't much different. A mathematically "ideal" electric guitar would be completely rigid, so that no energy is lost other than through the pickup - and solid-body guitars come closest to that. Because the loudness of the amplified sound comes from another source of energy, a pickup takes very little energy from the string, so electric guitars can have long sustain.
Other than that, the string behaves the same on both acoustics and electrics. Thick heavy strings vibrate slowly for a bass sound, light thin strings vibrate quickly for a treble sound. If you pluck near the middle of the string you get close to a pure sine wave. If you pluck away from the centre you get more layers of vibration: harmonics.
You use the word "unbalanced", but I'm not sure what you mean by it.
Typically when talking about electrical sound signals, "unbalanced" refers to a signal path that doesn't compensate for interference. If I ran 100 metres of guitar cable -- which contains a signal wire and a ground wire -- and plugged it into a guitar and an amp, I would hear a load of crackle and hum, just from stray magnetic interference in the environment.
If I ran 100 metres of balanced microphone cable in the same way, to suitable equipment, I wouldn't hear this interference. That's because balanced cable has one ground and two signal wires. Each signal wire has the same signal, but one is inverted. They both pick up almost the same interference. At the receiving end, one is inverted again and the signals are combined: the interference cancels out, and the signal is retained.
The same effect happens with pickups. A standard pickup is just a single coil around a magnet. It picks up interference, and that's audible as a hum. That hum is always there under the signal from the vibration of the guitar strings.
A "humbucker" pickup counters this by using two coils next to each other, and wired again such that the interference cancels out. However, because the coils aren't exactly in the same place, and because of complex magnetic fields, the combined signals interfere with each other a little, and it has a little less treble than a single coil pickup -- a sound that's often described as "fatter" or "rounder".
Comment: Mr.Boy - a) that is not what unbalanced means, and b) a truly flat amp does no boosting
Comment: When I say "unbalanced" I mean that my understanding is an acoustic amp is pretty "flat" - with all the EQ knobs at 0 it is ideally not modifying your sound - but an electric amp with all the EQ knobs at 0 will be doing some _baseline_ adjustments (such as pumping the mid) as a kind of 'correction' before anything interesting happens.
Answer: This is a really old thread, but it is still missing some of the basics.  An electric guitar output can be quantified by the voltage amplitude of the string being plucked or strummed.  In the magnetic coil pickups that dominate the market, the peak voltage will usually correspond to the peak velocity of the string because this gives the peak rate of change in magnetic flux in most configurations.  This, in turn, through Faraday's law, gives the peak voltage in the coil.
The string peak velocity depends on both the amplitude of the initial pluck, and the frequency, with higher frequency strings (or frettings) having a higher velocity than lower frequency strings (or frettings).
But that's not the whole story.  The reason the coil generates a voltage is that the presence of the string modifies the net magnetic field going through the coil as stated above.  Some people like to view this as the permanent magnet field inducing a magnetic dipole in the ferromagnetic string, which in turn generates it's field which causes the change when it moves during vibration.  But, when calculated this way, the field of the string dipole needs to be calculated correctly by noting any magnetically permeable materials in the vicinity (like magnet or steel poles, etc.) - i.e., it is not the field of a magnetic dipole in free space.  Others prefer to look at the problem in its entirety and solve for the proper solution for the magnetic field of the permanent magnet in the pickup which will depend on the proximity of any magnetically permeable materials in the vicinity - most notably the string and its changing location during vibration.  When done correctly and self-consistently, these two pictures are identical.
The relevance of this is that the thickness of the string - the amount of ferromagnetic material - also has a great influence on the voltage produced.
So for a properly "balanced" set of strings, for a comparable pluck or strum, they are chosen with thickness, tension, and a net amount of ferromagnetic material such that the desired composite of all these effects give a balanced sound.  It's actually kind of nice that nature made it not too different from the strings you'd use on a steel string acoustic.
Answer: You have nearly answered your own question. Except for one thing.

the signal coming down the guitar cable is a literal reflection of how each string interacts with the magnetic field[s], not how much noise each string is making.

Frequency and volume are the same, but you can't forget velocity. If two strings are tuned to the same frequency but one is vibrating at a velocity higher than the other, the one with a greater velocity/volume will be sensed by the pickup more.

But, how is it unbalanced? It will vary slightly between strings and
  pickups but your lower strings are heavier than your higher strings,
  and your higher strings vibrate faster than your lowers strings -
  these should both have an effect.
So, are the characteristics of a typical signal that it is weak in the
  bottom end, or the mid-range, or what?

Another thing to consider the sensitivity of the pickups. Here's an example. You pluck the high E and low E with the same velocity. The high E will vibrate at a frequency of 329.63 Hz. The low E will vibrate at a frequency of 82.41 Hz. Knowing what portion of the EQ will dominate the signal is up to the characteristics of the pickups. Some pickups are more sensitive to bass, so the bass notes are more prominent. In this instance, the lower E will dominate the signal.
It is logical to assume that most pick ups are weak in the mid-range as the low-end will likely overpower the rest of the signal.
Answer: The term for the characteristic you're looking for is "frequency response".  There's a thorough exploration at buildyourguitar.com for example, but basically any pickup is more efficient at conveying some frequencies (pitches) than others, and the frequency that is most efficient is the resonant frequency.  The guitar's frequency response curve shows the relative strength of the output voltage across a large frequency range.
Frequency response is affected by the type of pickup (humbucker, single coil) the number of windings, the circuitry in the guitar, the materials and physical construction of the guitar, and even the cable.


osquery daemond won't start on Ubuntu 15

Question: Cannot start osquery on Ubuntu 15:
I am getting this in the logs:
● osqueryd.service - LSB: run osqueryd daemon    Loaded: loaded
(/etc/init.d/osqueryd)    Active: failed (Result: exit-code) since Tue
2015-08-18 05:15:09 UTC; 8s ago
     Docs: man:systemd-sysv-generator(8)   Process: 27710 ExecStart=/etc/init.d/osqueryd start (code=exited, status=127)

Aug 18 05:15:09 public-server-01 systemd[1]: Starting LSB: run osqueryd daemon...

Aug 18 05:15:09 public-server-01 osqueryd[27710]: osqueryd: error while loading shared libraries: libgcrypt.so.11: cannot open shared object file: No such file or directory

Aug 18 05:15:09 public-server-01 systemd[1]: osqueryd.service: control process exited, code=exited status=127

Aug 18 05:15:09 public-server-01 systemd[1]: Failed to start LSB: run osqueryd daemon.

Aug 18 05:15:09 public-server-01 systemd[1]: Unit osqueryd.service entered failed state.

Aug 18 05:15:09 public-server-01 systemd[1]: osqueryd.service failed.

This is how I installed it:
dpkg -i osquery-latest.deb

apt-get install osquery

So why is it not starting?
Comment: That's a pretty sucky package, if it doesn't declare dependencies on the library packages it needs.
Answer: the key error is right here
Aug 18 05:15:09 public-server-01 osqueryd[27710]: osqueryd: error while loading shared libraries: libgcrypt.so.11: cannot open shared object file: No such file or directory

Looks like you are missing libgcrypt.so.11 Looks like that's a 14.04 and not available in 15. From reading it seems you can install the 14.04 version though.
Comment: I tried installing libgcrypt11 with apt-get but it did not change anything.
Comment: I got it from: https://launchpad.net/ubuntu/+archive/primary/+files/libgcrypt11_1.5.3-2ubuntu4.2_amd64.deb


How to cover method inside arrayList in mockito junits

Question: I am trying to cover below main class if (!Utility.isEmpty(errors)) block code coverage and i tried below code for adding errors in array List inside client class but still array showing as empty can some one help me to solve this issue.
Main class
public void processDiohShippingMethod(ShippingMethodRequest request) {
        List<ResolvableErrorEnum> errors = new ArrayList<>();
        checkoutRestClient.updateShippingMethod(request, errors);
        if (!Utility.isEmpty(errors)) {
            logger.info("ProcessDiohShippingMethod: Shipping method update failure  from {} -> {}. Reverting. ",
                    existingSm, request.getShippingMethodType());
            if (existingShippingMethod != null && Constants.RTG_ENJOY.equalsIgnoreCase(existingSm)) {
                request.setStartTime(existingShippingMethod.getDropOffShippingInfo().getStartTime());
                request.setEndTime(existingShippingMethod.getDropOffShippingInfo().getEndTime());
                request.setScheduleType(existingShippingMethod.getDropOffShippingInfo().getCustomerScheduleType());
            }
        }
    }

Client
public void updateShippingMethod(ShippingMethodRequest request, List<ResolvableErrorEnum> errors) {
    String url = Utils.formatHttpUrl(url, Cart_Request);
    try {
        HttpEntity<?> entity = new HttpEntity<>(request);
        JsonNode jsonNode = restTemplate.postForObject(url, entity, JsonNode.class);
        if (!jsonNode.has(Constants.CONTENT)
                || !jsonNode.path(Constants.CONTENT).path(Constants.ERRORS).isMissingNode()) {
            errors.add(ErrorMessages.SM_ERR_01);
            return;
        }
    } catch (HttpClientErrorException e) {
        errors.add(ErrorMessages.SM_ERR_01);
    } catch (HttpServerErrorException e) {
        errors.add(ErrorMessages.SM_ERR_01);
    }
}

Test
@Test
    public void test_processMethod() throws Exception {
        Request req = new Request();
        HttpEntity<?> entity = new HttpEntity<>(req);
        String jsonResponse = "{\"error\":{\"errorId\":\"1234\",\"message\":\"error message\"}},\"status\":\"success\"}}";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(jsonResponse);
        when(restTemplate.postForObject("url", entity, JsonNode.class)).thenReturn(actualObj);

        ShippingMethodResponse response = helper.processDiohShippingMethod(req);
    }

Answer: Since you didn't post the whole test code this is just an educated guess, but the most probable cause is that your helper object (the one from the test method) uses a different instance, but not the one you mocked (since I can't see any code in the test, that would set the client).
So a solution could look like this:
@Test
public void test_processMethod() throws Exception {
    Request req = new Request();
    HttpEntity<?> entity = new HttpEntity<>(req);
    String jsonResponse = "{\"error\":{\"errorId\":\"1234\",\"message\":\"error message\"}},\"status\":\"success\"}}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree(jsonResponse);
    when(restTemplate.postForObject("url", entity, JsonNode.class)).thenReturn(actualObj);

    //get this mocked object into the helper object somehow
    //otherwhise the mocked method will never be called
    helper.setClient(restTemplate);

    ShippingMethodResponse response = helper.processDiohShippingMethod(req);
}

You probably assumed the mocking call when(restTemplate.postForObject(...))... to mock the method for all objects of this class. But it will just create a decorator- / wrapper-object arround the object. So you've got to make shure that you call the mocked method on the mocked object, but not on any other object.
Comment: how can we get mocked object into helper class?
Comment: have you tried using a setter method like in the code snippet? If this doesn't work you could also try to refactor it into a parameter.


Wp_query doesn't work inside a php file for ajax call (return 500 Internal Server Error)

Question: I'm trying to display a Custom Post Type (espositori) post's with ajax when i select a dropdown's menu voice from select.
Inside file1.php i have this code:
<select id="tipologia-cliente" name="cpt" onchange="showVariables(this.value)">
  // some options
</select>

and the ajax script is

Inside the getcpt.php File the code is:
$args = array(
    'post_type' => 'espositori',
    'numberposts' => -1
);

$myquery = new WP_Query( $args );

if($myquery->have_posts()):
    while($myquery->have_posts()):
        $myquery->the_post();
        the_title();
        echo '
';
    endwhile;
    wp_reset_query();
endif;

When i'm select one option, i receive this error on console
GET https://www.mysite.it/wp-content/themes/mysite/templates-page/getcpt.php?q=espositori 500 (Internal Server Error)
If i replace the getcpt.php code with a simple echo "Hello World!", this work...
Can anyone help me?
Thanks so much
Comment: Great, you have a 500 error, meaning your exact problem will be in the `error_log`
Comment: And what would be the solution?
Comment: Firstly, to let us know what the actual error message is. Look in your log!
Comment: You cannot directly run a theme file like this since WordPress will not get initialized. You can try WordPress AJAX method - do you need the code?
Comment: @delboy1978uk oh sorry, i'm just frustrated about this error.. on error_log i have this error:
error:  Class 'WP_Query' not found in /var/www/vhosts/mysite/httpdocs/wp-content/themes/mysite/templates-page/getcpt.php on line 10\n', referer: https://www.mysite/my-page/
Comment: @OutsourceWordPress yes please, if you have the code can you post it? Thanks
Comment: You need to find where the file for that class is, and use `require_once '/path/to/Whatever.php';`
Comment: Check my answer below and let me know.
Comment: It's because you are "doing AJAX wrong" to begin with, at least by WP conventions … you should not put script files just anywhere on the server and call them on your own, forgoing WordPress. The proper way would be to add this via `wp_ajax_my_action` _inside_ of WP.
Answer: Here is the working code using WordPress AJAX.
Add this to functions.php:
add_action('wp_ajax_load_custom_espositori', 'load_custom_espositori_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_load_custom_espositori', 'load_custom_espositori_ajax_handler'); // wp_ajax_nopriv_{action}

function load_custom_espositori_ajax_handler() {
   $args = array(
        'post_type' => 'espositori',
        'posts_per_page' => -1
    );

    $myquery = new WP_Query( $args );

    if($myquery->have_posts()):
        while($myquery->have_posts()):
            $myquery->the_post();
            the_title();
            echo '
';
        endwhile;
        wp_reset_query();
    endif;

    wp_die();
}

Add this to Template File:

Let me know the WordPress version if not works.
Comment: Thanks for the code!
I'll try it in next hours and i'll check you!
Comment: Ok i'll tryed it and work perfectly!!! Thanks alot!!!
Now i have another problem... What if i select the CPT name from option select? From your code i can't understand how i can use value from  like a varaible and set it in 'post_type' query
Comment: What are you trying to achieve while changing the dropdown? You need another custom post type to load?
Comment: I have to create a filter selection with Select drop down menu.
At first i want to choose che CPT to show by drop down menu, then i have to create more select to filter by ACF field.
But first i want to understand how simple filtering with variable work.
Like, if i had CPT 1<option value="cpt2>CPT 2 how this work with your code?
Comment: Now the dropdown value passed to AJAX via 'qry' variable (`data : { action : 'load_custom_espositori', qry : str }`) and if you just want to load different custom post type data, just replace `'post_type' => 'espositori',` with `'post_type' => $_REQUEST['qry'],` in 'functions.php'. You can just have the custom post type names in your dropdown.
Comment: Yes! I just tryed by myself and it's work!
Now i read your answer and i did the same things! Now i think i can go with my code!

Last thing! Due to not write alot of code inside the function.php file, can i write the code inside function load_custom_espositori_ajax_handler() in a .php file and call it with a require  inside that function?

Thank very very very much!
Comment: Yes, but don't forget to add this to your 'functions.php' - `require_once ( get_stylesheet_directory() . '/filename.php' );`
Comment: I just wanna cry!!! I did it and got again 500 internal server error...
on function.php i have
/*-------------------*/
add_action('wp_ajax_load_custom_espositori', 'load_custom_espositori_ajax_handler'); // wp_ajax_{action}

add_action('wp_ajax_nopriv_load_custom_espositori', 'load_custom_espositori_ajax_handler'); // wp_ajax_nopriv_{action}

function load_custom_espositori_ajax_handler() {
 require_once( THEME_PATH . '/inc/ajax/ajax-filter-system.php' );
}
/*-----------------*/
Inside ajax-filter-system.php there is all the code with $_POST and WP_Query, but i get again 500 error
Comment: Don't be panic. Just check the server's error log and let me know the exact error.
Comment: I get this message:
PHP Warning:  require_once(): https:// wrapper is disabled in the server configuration by allow_url_include=0 in /var/www/vhosts/mysite.it/httpdocs/wp-content/themes/mysiste/functions.php on line 792\nPHP message: PHP Warning:  require_once(https://www.mysite.it/wp-content/themes/mysiste/inc/ajax/ajax-filter-system.php): failed to open stream: no suitable wrapper could be found in /var/www/vhosts/mysite.it/httpdocs/wp-content/themes/mysiste/functions.php on line 792\n
Comment: PHP message: PHP Fatal error:  require_once(): Failed opening required 'https://www.mysite.it/wp-content/themes/mysiste/inc/ajax/ajax-filter-system.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/vhosts/mysite.it/httpdocs/wp-content/themes/mysiste/functions.php on line 792\n', referer: https://www.mysite.it/mypage
Comment: Where is your new PHP file located? My previous code assumes 'inc' folder inside your theme folder.
Comment: the path of new PHP file is
https://www.mysite.it/wp-content/themes/mysytetheme/inc/ajax/ajax-filter-system.php
Comment: You added wrong function - look at my original comment, replace `THEME_PATH` with `get_stylesheet_directory()`.
Comment: Yeah!! Now work all fine!!! THEME_PATH assume get_stylesheet_directory_uri() and i haven't read that you said get_stylesheet_directory()!!
Now seem work all fine! Hope i will not have problem with filter sistem!
Thanks very very much!!
Answer: Use this code. As you need to set post limit, the attribute is posts_per_page. WP_Query link
$args = array(
    'post_type' => 'espositori',
    'posts_per_page' => -1,
);
global $post;
$myquery = new WP_Query( $args );

if($myquery->have_posts()):
    while($myquery->have_posts()):
        $myquery->the_post();
        the_title();
        echo '
';
    endwhile;
    wp_reset_query();
endif;

Comment: Thanks for answer, I tryed but isn't the solution.
The query inside a normale php page work fine.
Comment: Have u added `global $post;`
Answer: Try using $wpdb global object instead. Here's an example from your code:
$args = array(
  'post_type' => 'espositori',
  'posts_per_page' => -1,
  'post_status' => 'publish',
);
global $wpdb;
$posts = $wpdb->get_posts($args);

if(!empty($posts)){
  foreach($posts as $post){
  setup_postdata($post);
  //You can use the_title() the_content() the_excerpt() the_permalink() etc...
  echo get_the_title($post->ID);
  echo '
';
}
}

Hope that helps!


Custom Apps Script function not executing on some certain rows on Google Sheet

Question: I have written some Apps Script code to fetch stock data from Yahoo and Fizviz, and for a while it worked fine.
Ever since I reached a certain number of rows in my table (around 20 tickers), some specific rows stop executing, the cells say "Loading" forever. The row's apps script functions do not show up in stackdriver logs. If I sort the table to trigger a refresh, these tickers are then executed, but some other different specific rows stop executing, so the problem shouldn't be the ticker. Also, the bizarre thing is that the number of rows not executing is different for different sort orders, sometimes I could find a sort order that most of the rows execute. If I delete all rows except one that does not execute, it stays not executed.

I tried to formulate different explanations, and at this point it just all seems like random black magic to me.
Does anyone have the same experience as I am having?
The code is here if anyone is curious, the main entry point functions used by the sheet directly is in FinanceData.gs: https://github.com/hoangbv15/FinanceAppsScripts
Edit: Thank you guys very much for the array formula suggestions. I tried to use it but it cannot cope with my filter table when I change filtering/sorting. Perhaps I am not using it correctly?
Comment: use a single array formula instead of multiple formulas
Comment: Are you exceeding the quota? [Apps Script Quotas](https://developers.google.com/apps-script/guides/services/quotas)
Comment: @JamesD I don't think so as it is only my precache trigger that is doing the network calls, the methods invoked by the cells simply lookup the value in another temporary cache sheet. At least I don't see any quota related to reading values from another sheet? Also would it give me an error about exceeding my quota in that case?
Comment: @TheMaster I tried, but the rows get all messed up once I change the filter or sorting. Is there a way to use array formula and be compatible with table filter/sort?
Comment: No. but you can use query to filter /sort. Something like `= query( custom fun, " where Col1='example' sort by Col1")`
Answer: I tried to reproduce your error but for the moment it works fine, it's just a bit slow. It could be a quota problem, and I might not facing it yet.
To avoid exceeding the quota I suggest you to wrap your custom function calls in an <code>=ARRAYFORMULA()</code>. In this way your n function calls will be batched in one.
I don't think your App logic is suited to work well on Google Apps Script though. You will have to adjust it to reduce the response time otherwise you will get a timeout on the custom function call.
Comment: thank you for your reply! unfortunately arrayformula doesn't work as I need to be able to sort & filter the table, however it is still a great idea. W.r.t. response time, my get functions are very quick as they only look in the cache and not do any network calls. It is the precache service that is doing the network calls and putting values into the cache. In theory, the get calls should just return straight away.
Comment: I ended up changing to arrayformula, and adjust my sheet to allow filtering/sorting! It works fully now! Strange how it's not any of the quota or slow response time problems, just Google servers acting up I guess.
Comment: Yeah, sometimes it's hard to understand what is going on. I'm glad it worked!
Comment: weird I can't set your answer as the correct one? Is Stack Overflow having an issue?
Comment: I have no idea, just try later maybe. I see that you tried.


TypeError: Cannot read property 'Collection' of undefined discord.js

Question: im cannot run the script becauce i get the error:
TypeError: Cannot read property 'Collection' of undefined

const fs = require('fs');
const { Client, Util, MessageEmbed, discord} = require("discord.js");
const prefix = (process.env.DISCORD_PREFIX);
const { Player } = require('discord-player');
const bot = new Client({
    disableMentions: "all"
});

bot.player = new Player(bot);
bot.emotes = require('./config/emojis.json');
bot.filters = require('./config/filter.json');
bot.on('message', message => {
    bot.commands = new discord.Collection()();;
});

Please Help me:(
(with example please)
Answer: Try to create another costant like this const Discord = require('discord.js') and change
new discord.Collection() to new Discord.Collection()


how do I open  next to each other?

Question: I've made a little navigation thingy at the top of my website. But, when you hover it, I want the options to open next to each other, instead of on top of each other.
I hope someone can help me out.
ul {
    margin: 0;
    padding: 0;
    list-style: none;
    width: 50px;
}
ul li {
    position: relative;
}
li ul {
    position: absolute;
    left: 49px;
    top: 0;
    display: none;
}
ul li a {
    display:block;
    text-decoration: none;
    color: #777;
    background:none;
    padding: 5px;
}
/* Fix IE. Hide from IE Mac */
 * html ul li {
    float: left;
}
* html ul li a {
    height: 1%;
}
/* End */
 li:hover ul {
    display:block;
}
li:hover ul, li.over ul {
    display: block;
}
/* Fix IE. Hide from IE Mac */
 * html ul li {
    float: left;
    height: 1%;
}
* html ul li a {
    height: 1%;
}
/* End */
 #uno:hover {
    -webkit-transition-duration: 0.8s;
    -moz-transition-duration: 0.8s;
    -o-transition-duration: 0.8s;
    transition-duration: 0.8s;
    -webkit-transform:rotate(45deg);
    -moz-transform:rotate(45deg);
    -o-transform:rotate(45deg);
}

I do not have a link to the website because it's not online yet. If you need more information I can try to make a little demo but I thought, probably you will know what I mean.
Comment: I think a demo would be most useful. Try http://jsfiddle.net
Comment: Here's a awesome website to make demos mate. http://jsfiddle.net/. Plus I need to see your HTML structure.
Comment: You're hiding your CSS from *IE Mac*?? That software was discontinued **ten years ago**. I think it's now safe to assume that NOBODY is viewing your website with this browser.
Answer: You should try replacing
display: block;

with
display:inline-block;

Answer: In your CSS you have a width:50px; set on your ul tag which is stopping your links to align side by side.
Also add
ul li { display:inline;}

As elements are defaulted to display:block
http://jsfiddle.net/V3sTd/1/

how do I open  next to each other?


Understanding a detail of a proof about topological compactifications

Question: I don't completely the following proof from Van Douwen's paper. My exact questions are below the proof.
Van Douwen proves that

If $X$ is a non-compact strongly zero-dimensional space in which every
nonempty clopen subspace is homeomorphic to $X$, then the only
H-compactification (or "topological compactification") of $X$ is the Stone-Čech compactification.

The Proof:
Let $\gamma X$ be an arbitrary H-compactification of $X$. In order to show that $\gamma X$ is the same as $\beta X$ we prove that every clopen subset of $X$ has an open closure in $\gamma X$, which will, according to one of the equivalent characteristics of the Stone-Čech compactification, lead to the desired conclusion.
Denote again by $\overline{\:}$ the closure operator in $\gamma X$.
If $U$ is a clopen subset of $X$, we can assume $\emptyset \neq U \neq X$. Then we can find
a nonempty clopen subset $V$ of $X$ such that $\overline{U} \cap \overline{V} = \emptyset$. $U$ and $V$ are indeed homeomorphic. Then there exists an automorphism $h$ of $X$ such that $h(U) = V$ and $h$ sends any  $x \not\in U \cup V$ to itself.
By the assumption, $\gamma X$ is a H-compactification, so we can define an extension of $h$ over $\gamma X$. Denote such extension by $\gamma h$.
Since the intersection of closures of $U$ and $V$ is assumed to be empty and $h$ maps every $x \in U$ to $y \in V$, we see that $\gamma h$ satisfies
$\overline{U} \cap (\gamma h)(\overline{U}) = \overline{U} \cap \overline{V} = \emptyset$.
Observe that from our definition of $h$, $\gamma h(x) = x$ for each $x \in \overline{(X \setminus (U \cup V))}$. Therefore we have
$\overline{U} \cap \overline{(X \setminus U)} = (\overline{U} \cap (\gamma h)(\overline{U})) \cup (\overline{U} \cap \overline{(X \setminus (U \cup V))}) = \emptyset$.
Hence the closure $\overline{U}$ is open in $\gamma X$.
My questions are:

I don't understand the last sentence in bold. How do we obtain the conclusion that the $\overline{U}$ is open in $\gamma X$? and Did we somehow use the properties of $X$ stated in the claim? Is it because since $U$ is homeomorphic to the whole $X$? (I still don't see how this would imply the last sentence though.)

How is the strong zero-dimensionality used in the proof?

Definition of H-compactification (or "topological compactification") is that every automorphism on the original space can be continuously extended over the compactification.
Answer:
Because you now have that $\overline{U}$ is the complement of $\overline{X\setminus U}$ in $\gamma X$ (which is a closed set) the set $\overline{U}$ is open.
In the very first paragraph of the proof: strong zero-dimensionality means that disjoint zero-sets are separated by clopen sets, and the fact that clopen sets in $X$ have clopen closures in $\gamma X$ implies that disjoint zero-sets in $X$ have disjoint closures in $\gamma X$ (see Corollary 3.6.2 in Engelking's book).
Comment: A zero-set is what Engelking calls functionally closed: a set of the form $\{x:f(x)=0\}$ for a continuous function $f:X\to\mathbb{R}$.
Comment: By zero-sets do you mean closed sets? I think these are equivalent in metric spaces, but here we don´t assume a metric, right? I dont understand how zero-sets appeared here.


Providing web-based training using VNC or other tools

Question: I am attempting to implement the capability to provide real-time web-conference style training to a group of 10-15 students located on another continent. We're in Canada, they're in Australia. Here are the basic requirements:

I need to share my desktop with all the students simultaneously. I will be alternating between slides and computer demonstrations.
I need to be able to share my voice with all students simultaneously. We can use an already existing Asterisk conference bridge to accomplish this, but it will still impact upstream bandwidth.
The upstream bandwidth of my connection is nominally 1 Mbps.

Historically we have done this with an Asterisk conference bridge + VNC for screen sharing, but we've never had this many students and never this far away. Both upstream bandwidth and latency are serious considerations.
I'm not sure if commericial solutions like WebEx could solve this problem by, for example, allowing me to broadcast audio and my desktop to a central server located closer to the students and then re-broadcast to all students at the same time, greatly reducing my upstream needs.
Or, if there is sufficient headroom in the VNC protocol with compression enabled etc. to make this feasible.
Or even if I could set up my own re-broadcast capability using an EC2 or similar instance located in Asia or Australia, if such a thing exists.
All thoughts and suggestions would be appreciated.
Comment: This question is off-topic under current topicality rules.
Answer: You don't need to send the data to all the users at once. The best you can do is to send the data to one server and that server will send the video and audio data to all users in real time, with ~10 seconds latency.
You can find some free webs that do this, but the most used are Youtube.com (Yes Youtube offers live broadcasting) and Twitch.tv
The good thing is that using this system you can have from 1 user to millions of users connected regardless of your bandwith, and also your users don't have to install any aditional software.
EDIT: Also, those webs have chats so your users can comment and ask questions while you explain.
Comment: I looked into a few free web services and am running with MeetingBurner.com for now. It's free for up to 10 students at a time and am very pleased with the ease of use and performance. It has the chat feature you mentioned, but doesn't offer the ability for a participant to share their screen to the instructor... this is just a nice-to-have for me at the moment.
Comment: Yes, if you want your students to share their screen, sure they have to install aditional software. Maybe, they can have their own account in MeetingBurner, Twitch or somewhere else and share the streaming link to you (And,  if need be, to any other student). Thanx for accepting the answer.


Remove Confirmation box on backbone PUT and DELETE request to django api on firefox

Question: Firefox is showing a confirmation box when a PUT or DELETE request is going from backbone to django rest api, whereas no such confirmation being asked for POST request.

This web page is being redirected to a new location. Would you like to resend the form data you have typed to the new location?

In chrome no such confirmation box coming.
Is there any way to remove this box? what would be the reason for it?
Comment: Please help me anyone
Answer: The problem is with the django rest framework.
include following in urls.py

router = routers.DefaultRouter(trailing_slash=False)

by default trailing_slash = true
Now its working fine
You can find more details here:

Http Delete request to django returns a 301(Moved permenantly)


Does the variance in the estimates of the coefficients for standard linear regression decrease as $O\bigg(\frac{1}{n}\bigg)$?

Question: I am interested in how the estimate of the regression $\beta_1$ decreases with respect to sample size $n$. Does this look ok or am I missing something?
$$
\begin{align}
\text{Var}(\hat \beta_1) & = \frac{\sigma^2}{\sum_{i=1}^n (x_i - \bar x)^2} \\
& \le \frac{\sigma^2}{\sum_{i=1}^n \min_i \{(x_i - \bar x)^2\}} \\
& = \frac{\sigma^2}{n \min_i\{(x_i - \bar x)^2\}} \\
& = O\bigg(\frac{1}{n}\bigg).
\end{align}
$$
Edit:
It seems that the first answer in this post seems to agree with my result. However, the first answer in this post seems to say something else as it says that $\sigma^2$ is itself estimated (by the MSE) and that this estimate has a dependence on $n$.
Can someone clarify exactly how the variance decreases with $n$?
Comment: The answer depends on your model: exactly what marginal distribution of the explanatory variables are you assuming?  This has already been explained in the answers to your previous question at https://stats.stackexchange.com/questions/491002/.
Comment: It would seem naturual that the more random observation we have (e.g. the larger $n$ gets), the more the variance is reduced, but I have not seen a formula that makes explicit how the variance decreases as $n$ increases. That is my motivation for asking this question.
Comment: I am not making an assumption on the distribution of the explanatory variables as they are coming from real life observations.
Comment: In kernel density estimation, I have seen proofs where the decay variance of the estimate with respect to $n$ is explicit (as the bandwidth goes to zero), so I figured it would also be possible to have similar explicit results for the decay of the variance of the coefficients in linear regression? Page 7 of http://faculty.washington.edu/yenchic/18W_425/Lec6_hist_KDE.pdf shows that the variance of a KDE estimate decays as $\frac{1}{nh}p(x_0) \sigma_K^2$, for example.
Answer: The true variance of $\hat\beta_1$ is $\mathcal O(1/n)$, as you correctly proved. The estimated variance of $\beta_1$ is a random variable and its asymptotic behavior is better described using big O probability notation. Since the MSE is a consistent sinais of $\sigma^2$, we have $\hat\sigma^2=\sigma^2+\mathcal o_p(1)$. If we replace $\sigma^2$ by $\hat\sigma^2$ in your proof, we get that the estimated variance of $\beta_1$ is $\mathcal O_p(1/n)$.
TL;DR: the true variance is $\mathcal O(1/n)$, while the estimated variance is $\mathcal O_p(1/n)$ (that is, it is asymptotically bounded by $1/n$ with probability 1).


How does the type of wood used to make an acoustic guitar affect its sound?

Question: I understand a similar question has been asked before; as the link below

Does the kind of wood used in making a violin affect its sound?

However, I would think a violin and guitar are very different. If so, how doees the type of wood affect the sound of a guitar?
Comment: Most people disagree with most other people _if_ there's an effect, to what extent etc. It would probably help to know if you're talking acoustic or electric guitar?
Comment: Possibly useful: http://www.amjbot.org/content/93/10/1439.full Breedlove guitars has a more qualitative description http://breedlovemusic.com/features/top-woods-binding-styles , I've seen other similar (and similarly unsubstantiated) tone wood graphs in other places too.
Comment: I interpret this question as  being significantly different from the violin one: this one (seems to) ask "What effects will different woods have", the latter seems to ask "Why should I care about the type of wood in a violin?".  I cannot envision an answer to the "What effects..." question that is not one of (a) subjective or (b) a book length answer that goes into the overall design of guitars
Comment: I'd answer this that the physics of how a violin and a guitar produce sound is almost the same, so the materials to make them sound good their best are also the same. The only major difference is bowing vs plucking, and that primarily affects string setup rather than wood. So the linked question is an actual duplicate, not just similar. Maybe if the question was more about effects of particular woods on an instrument's sound?
Comment: It's all about absorptivity and coefficients of restitution and other fancy words :-), which boil down to "does the wood vibrate easily in response to the frequencies you want, and preferably not vibrate in response to frequencies you don't want."
Answer: In the case of Acoustic:
The density of the wood affects its resonance. the sound is echoed inside the hollow base and the quality of the wood affects how much sound is distributed outwards. The same effects are applied with damp wood, if the wood is damp it will affect the sound.
In the case of Electric:
I am unaware of any effects the wood has on the sound or quality of the guitar, its mostly down to professional appearance and finish. also the better the wood the longer the guitar will last and more of a beating it can take.


Get records from primary table when secondary table is returning null in left join

Question: I have two tables (Joined using Left Outer Join) primary table always have data and secondary table may have or many not have data using where clause,
My issue here is when secondary table returns rows then only my query displays some data if secondary table returns Zero rows then my query also returns zero rows but I am using left join as per my knowledge though secondary table returns Zero rows I need to have data from primary table.
select * from
(
    SELECT Flag, [Description1], [group_code], [category_code]
    FROM Item_TMP
) b --Primary table
Left outer join
Base a --Seconday table
    on a.Part_ID = b.category_code
where b.category_code between 'A' and 'F'
AND b.type = 'Goods'

I need to have data irrespective of table 2 returns rows.
Edit
Item_TMP table
Flag   [Description1]   [group_code]   [category_code]
WO      Computers        FP               A
SO      LAptops          FP               F

Base Table
part_id    quantity
 A           50
 F           100

Now where Base table may return or may not return
Required Output
If Base table returns data then
Flag   [Description1]   [group_code]   [category_code]  Sales
WO      Computers        FP               A              50
SO      LAptops          FP               F             100

If Base table doesn't return data
Flag   [Description1]   [group_code]   [category_code]  Sales
WO      Computers        FP               A              0
SO      LAptops          FP               F             0

Comment: This should not compile - I din't see any column called `Code` in your `b` table...
Comment: @ZoharPeled actually I can't paste the orginal query here, so made some changes but query is compiling but returns zero rows if table returns zero rows, can you please help struck here
Comment: @ZoharPeled actually I need a way to get the records of left table irrespective of right table records
Comment: Zohar's point is @Siva is that you have the column `[category_code]` within your subquery (which you alias `b`, however, outside the query you reference `b.code`; there is no column `code` inside the subquery `b`. This might seem like a small mistake, but if the code you have supplied is clearly wrong, it lowers the trust of the users here have of your example, as it isn't going to compile in the first place.
Comment: @Larnu yes sir accepted I will update the question but how can I get the data can you please help
Comment: @Larnu I have updated the question
Comment: Can you provide sample data and expected results?
Answer: I would write it in a simple left join with isnull()
select b.Flag, b.[Description1], b.[group_code], b.[category_code],
isnull(a.quantity, 0) Sales
FROM Item_TMP b
    Left join Base a  on a.Part_ID = b.category_code
where b.category_code between 'A' and 'F'
    AND b.type = 'Goods'

Answer: You can try to use ISNULL or coalesce function
select b.*,coalesce(quantity,0) Sales
from
(
    SELECT Flag, [Description1], [group_code], [category_code]
    FROM Item_TMP
) b --Primary table
Left join
Base a --Seconday table
    on a.Part_ID = b.category_code
where b.category_code between 'A' and 'F'
AND b.type = 'Goods'

Comment: Thanks for the answer, will try now


Is it advisable to use virtual Linux server installed on i5 / 8GB / 500GB desktop class computer?

Question: We have CentOS 4.3 P4 / 512MB /Linux server installed somewhere in 2006-7. This machine has three network interaces for leased line, broadband (backup) and LAN. We use Sendmail, Fetchmail, NAT, Squid, DNS insalled on this server for about 70-80 users. Now the hardware and software has become quite old, I want to upgrade this server to latest CentOS edition.
My question is, can I go for virtual server environment using entry level desktop board having i3 or i5, 8GB RAM and 500 GB HDD without compromising any performance compared to existing machine? I intend to install VMWARE vSphere Hypervisor for this configuration.
Comment: @Silkograph You can buy a highly decent, **real** server (albeit an older one) [on eBay for that price](http://www.ebay.com/itm/Dell-PowerEdge-2950-II-Server-2x-2-33GHz-E5345-Quad-Core-16GB-RAM-2x1TB-PERC-5i-/221295119685?pt=COMP_EN_Servers&hash=item3386378d45), and it's well worth the investment, compared to trying to make a desktop computer a server. (Just one of many examples.) This would not be my first choice, of course, but with a budget of ~$300 for a server, buying a used one is the best way to get an actual server within your budget.
Comment: For a developer, perhaps. For this I'd buy a real server.
Comment: See [this](http://serverfault.com/questions/165384/server-hardware-what-do-you-suggest/165393#165393) answer. Much of the same problems exist when using "desktop" computers as servers as when people assemble their own servers.
Comment: Since the existing hardware is so simple I am not going to get funds for server class machine. I will be getting just entry level assembled desktop machine (about $330 equivalent Indian rupees).
Answer:
can I go for virtual server environment using entry level desktop
  board having i3 or i5, 8GB RAM and 500 MB HDD without compromising any
  performance compared to existing machine?

With the exception of th hard discs (if you can go with an SSD that will make a hugh difference) the answer is clearly yes. The P4 is ancient - seriously ancient. Likely my mobile phone has more processing power than this one. An i3 is going to run circles around it.
Wikipedia gives the most modern P4 (http://en.wikipedia.org/wiki/Pentium_4) in a 65nm process. It was though a looong processor - the P4 line goes back to 1995.
Anyhow, you jump multiple generations if you get a current processor, so the speed advantage will be significant.

How many network interfaces would require if I create three VMs on this server?

How long is a piece of string? You are supposed to know basics as professional admin (and only those are supposed to ask here). We can not answer that. One, if you isolate draffic with VLANÄs and can live with the 1gigabit or 10 gigabit limit that this imposes. 100 if the VM's need that.

I want to move to virtual environment for two reasons, I may create
  two or three Windows machines which can be used for s/w product
  testing

You have a problem here. A 500mb hard disc WILL overload. IO is generally a very limiting factor in virutalization and patching can get hard. I would suggest either a 500mb velociraptor if you can not afford more (that at least givey you 10k RPM) or - much better - a SSD. If you run compilations / builds then man, this one poor HD will really get hit hard.
Comment: Thanks for your answer.
Extremely sorry for the typo, I will be using 500 GB HDD not MB. I asked about no. of network interfaces because I think, I must use at least 3 interfaces for leased line, BB and lan, but not sure about other vms I will be creating for testing.
Comment: Totally depends how professional your backend is and whether you can dwal with VLAN's. For example in my backend all traffic runs one line towards the office. Uplink, everything. VLAN coded. THe VM's have multiple virtual NIC's that are attached to different VLAN's - of the same physical NIC.


How to install Erlang or Elixir with Observer using the Nix package manager?

Question: Every time I install Erlang, I end up without Observer. Used the commands below on a Ubuntu laptop with Xmonad and a Debian 9 running in the cloud, and seemingly they both resulted in the same package being installed:

nix-env -iA pkgs.beam.packages.erlangR22
nix-env -iA nixpkgs.beam.interpreters.erlang
nix-env -iA nixpkgs.beam.interpreters.erlangR22_odbc_javac

The Nixpkgs manuals 15.2. BEAM Languages (Erlang, Elixir & LFE) section (Version 19.09.1484.84586a4514d) does not mention Observer at all. It has a fairly recent update by DianaOlympos that does mention it, albeit I tried all these packages, but no joy:

Many Erlang/OTP distributions available in beam.interpreters have versions with ODBC and/or Java enabled or without wx (no observer support). For example, there's beam.interpreters.erlangR22_odbc_javac, which corresponds to beam.interpreters.erlangR22 and beam.interpreters.erlangR22_nox, which corresponds to beam.interpreters.erlangR22.

Shane Sveller pointed it out that the wxGTK package needs to be set up using propagatedBuildInputs, but not sure how to do that. (Simply just installing wxGTK then Erlang doesn't work of course; was naive enough to try it. Also found out that chapter 20 of Nix Pills is exactly about this topic.)
This is also kind of a follow-up to the question "How to install Erlang/Elixir on a non-NixOS system?", but I didn't realize it then that Observer is missing...

update: Apparently, it works somewhere out of the box. (Probably on NixOS.)
Answer: I have an overwrite for erlang, such that wx support is enabled:
{ pkgs ? import <nixpkgs> {} }:

with pkgs;

let
  inherit (lib) optionals;

  erlang_wx = erlangR21.override {
    wxSupport = true;
  };

  elixir = (beam.packagesWith erlang_wx).elixir.override {
    version = "1.9.2";
    rev = "ffe7a577cc80f37381dc289c820842d346002364";
    sha256 = "19yn6nx6r627f5zbyc7ckgr96d6b45sgwx95n2gp2imqwqvpj8wc";
  };
in

mkShell {
  buildInputs = [ elixir git ]

    # For file_system on Linux.
    ++ optionals stdenv.isLinux [ inotify-tools wxGTK ]

    # For file_system on macOS.
    ++ optionals stdenv.isDarwin (with darwin.apple_sdk.frameworks; [
      # For file_system on macOS.
      CoreFoundation
      CoreServices
      wxmac
    ]);
}

Save this (as shell.nix for example), and just run it:
$ nix-shell shell.nix

# or, if you are in the same directory:
$ nix-shell

Works on my machine!

Note: wxmac in buildInputs is specific to MacOS (and wxGTK to Linux). To find the right package for your OS, here are the available wx packages.
Comment: Thanks! In the end, the solution is way more mundane, but accepted your answer because it is very educational on how to write a `nix-shell` script.
Comment: Edited your answer to make the `wx` packages part of the `optionals` too, but was only able to try out the Linux-side of things. If you don't agree with any of the changes, just nix mine. Thanks again! (For reference to future self: see sections _184.108.40.206. lib.lists.optional_ and _126.96.36.199. lib.lists.optionals_ in the [Nixpkgs Manual](https://nixos.org/nixpkgs/manual/)).
Answer: Kind of ashamed to admit that I am an idiot, but Observer was there all this time (along with net_adm)...
For some reason, it wouldn't autocomplete on the erl shell, but once observer:start(). was typed in and executed, it would recognize the module, and provide a list of available functions when hitting the Tab key.
I probably messed up translating between iex and erl ( observer.start(). and other combinations), and I assumed that the resulting error message (together with no autocompletion) means that the module was missing.


Vercel can't deploy due to react icons module is not found but it is actually installed

Question: I am trying to deploy a project to Vercel but it marks down an error on the building phase, saying react icons can't be found even if it is installed to package.json and imported correctly to the component that uses that module.
Here is the public repository where is all my code since it planned to be public: https://github.com/Benevos/react-nextjs-tailwind-juice-slider
This is the faulty component:
'use client';

import React from 'react';
import Link from "next/link";

import Navbar from "@/components/Navbar";

import { FaCircleUser } from "react-icons/fa6"; \\ <---- Here is where the error shows
import { FaShoppingBag } from "react-icons/fa";

import { Londrina_Solid } from 'next/font/google';

const londrinaSolid = Londrina_Solid({weight: '400' , subsets: ['latin']});

function Header({ backgroundColor, textColor }) {
  return (

        <Link href={"/#"} className={`text-3xl flex-initial ml-10
                                        max-md:ml-5 ${londrinaSolid.className}`}>
            Trademark
        </Link>

        <Navbar/>

            <Link href={"/#"}>
            <FaCircleUser/>
            </Link>

            <Link href={"/#"}>
            <FaShoppingBag/>
            </Link>

  )
}

export default Header

This is package.json:
{
  "name": "juice-slider-vercel-fix",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "14.0.4",
    "react": "^18",
    "react-dom": "^18",
    "react-icons": "^4.12.0",
    "sass": "^1.69.5"
  },
  "devDependencies": {
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.4",
    "postcss": "^8",
    "tailwindcss": "^3.3.0"
  }
}

Vercel logs:

I used the suggested command by react icons documentation to install the module (npm install react-icons --save).
Already tried to start a fresh project installing react icons at beggining and importing all the source code but still not working.
I also checked deploy my next.js project on vercel, Cannot find module 'react-icons/Fa' or its corresponding type declarations but seems not to be the problem.
Someone knows what could be the problem, please?
Comment: are you able to display  `react-icons/fa6` on ui
Comment: Yes, development server runs perfectly
Answer: your code builds

and starts with npm run start

Maybe you need to update node version. my system has:
node --version
v18.17.1

I also deployed on vercel successfully:

here is the production link:
https://testing-vercel-bay.vercel.app/
check your vercel settings for node version
Comment: As can be seen in `package.json` in this post, there is no `react-icons` key in the object that contains `devDependencies`. By te way, I also looked for installations globally, but `npm -g ls` showed no sign of `react-icons` there.
Comment: I just realized that. do u have a git repo?
Comment: It's written on the post: https://github.com/Benevos/react-nextjs-tailwind-juice-slider
Also, Nettlify did the deployment with no problems.
Comment: I know how to start production server, I have already build my project. But this is not about that. The problem is on Vercel and its hosting. Im glad you are trying to help, but did you even read the post?
Comment: since I started, I will deploy too
Comment: Thanks, I do not know what just happened, Vercel deployed without me doing anything at all few seconds ago. I'll mark your answer as solution since seems you did something that dealt with the problem
Comment: maybe vercel had issue at that moment


How to show Forms in nodes stored in the node tables

Question: Mine is shared hosting account with limited CPU usage so I want to minimize CPU and mysql usage.
I'm generating 100,000s of nodes which contain some information. I also want to add a form in those pages. Since these nodes will be stored in node table how can I generate form on the fly? I think using filters but that'll not use Drupal caching hence it'll affect the shared hosting CPU quota due to this performance issue.
I don't want to use _menu to generate those pages on the fly because 1) it will slow down my site 2) It'll be difficult to use Drupal Taxonomy to classify "these" generated pages on the fly. Generating pages from the node table will be faster and also cacheable.
Another way is to insert the Form code in the nodes at the time of generation with the option that it won't contain/verify dynamically generated tokens(eg without #token) but it'll be security risk for my site.
What is the best way to handle this case?
Answer: What do you mean "generate form on the fly"? As in: the form for page "page/form" doesn't exist in a canonical state but is generated based on variables such as date/url/taxonomy? Or is it just the default values for the form etc?
In anyway: the options to have a form on a page are:

Hardcode HTML into the node content, e.g. <form><input> etc
Use hook_menu to create the page and use the form API
Use hook_menu to create the page and use the straight HTML
Use hook_nodeapi to add a form to the content with the Form API
Use hook_nodeapi to add a form to the content using HTML
Use a module such as webforms to add the forms

I would suggest either 2 or 4. When you say that hook_menu generates these plages "on teh fly": that's not true. hook_menu is only run on cache clear, and assuming you're using caching then the generation of forms isn't going to make much difference to your server. This may be a case where you're sweating about optimisation unnecessarily.
Using Form API gives you a load of tools that you'd otherwise have to handle yourself - validation, submission, sanitising, standardising, etc.
Comment: On the fly is just like generating the page using hook_menu without caching turned on and instead of fetching pre-built page from the node table. I don't want to use hook_nodeapi as it'll need to be called for every page load and I'll have tons of pages as well as traffic. I'm looking for embedding Form code within the node. So simply fetching the code from node table and displaying will be the work to do.
Comment: Apemantus got it right AFAIK : standard Drupal caching will do a better job performance wise than the overhead caused by any custom code I can think of. Unless of course you code it from the bottom up, in which case using Drupal makes no sense. And you'll have to be really really smart in your development to outwit the skillful people who have coded what exists.
Comment: hook_nodeapi is called by lots of different modules every time a page is viewed: you adding one more call per page  isn't going to make any real difference. And as you presumably have caching turned on (with lots of pages and lots of traffic on a shared server), I'm not sure why you're worried about hook_menu either. Again, there's many calls to hook_menu throughout your site, even before you touch custom code. One of the stages of Drupal development (for me) was learning to accept that in the vast majority of cases I was better off working with Drupal, rather than against it.
Comment: On another note - why not just create the form using FAPI, use `hook_menu` to call it...and cache the forms yourself using `cache_set`.  Then you get the benefits of caching, plus the benefits of `hook_menu`.  Check [this](https://www.lullabot.com/articles/beginners-guide-caching-data-d6) out for help with caching.


What should be in a discrete mathematics book?

Question: Recently, one of my teacher ask me to help him for writing a book on discrete mathematics book and this book will use in our university for teaching discrete mathematics. The target audience are first year students in computer engeneering. They have seen some basic graph theory and combinatorics. The book should allow them to study data structures and algorithms afterwards. It is supposed to contain things like: Set theory, logic, graph theory, relations and functions , number theory, recursion and enumeration but.

Are there any topics missing for the target audience? Has anyone
  experiences in teaching such a course?
Comment: @AliAmiri I edited the question to make it more focused and conform to this site. I hope the edits are fine with you.
Comment: Voting to close.  From the FAQ: "Avoid asking subjective questions."
Comment: @NateEldredge Where could I ask this question?
Answer: It really depends a great deal on the intended audience. What is their expected mathematical background? Is this likely to be their first exposure to mathematics that isn't primarily computational? (Standard first-year calculus, as it's usually taught, is primarily computational.) Are they likely to go into mathematics, or are they more likely to go into computer science? In a related vein, is the course intended to have an applied bias? Is it intended, as such courses sometimes are, to be an introduction to theoretical mathematics?
As far as I'm concerned, there are only two clusters of ideas that are absolutely indispensable in a first course in discrete mathematics. One is the basic counting techniques of elementary combinatorics; the other is recursive definition and proof by induction. The natural point of contact of these two clusters is the solution of recurrences. The basic theory of homogeneous linear recurrences is accessible, and one can also deal at this level with first-order non-homogeneous recurrences that are simple enough to be 'unwrapped'. (Rigorously proving that the solution found by unwrapping really is the solution gives more practice in proof by induction.)
Beyond that a great deal depends on how much time is available. In a typical U.S. semester I'd expect to be able to do a decent job with one or maybe two more topics, depending on the calibre of the students. I've usually chosen either to do a bit with formal languages, concentrating on regular languages, regular sets, and finite-state automata, or to do some graph theory.
I don't really care for the kind of comprehensive text that you seem to be contemplating: either it contains far more material than can be covered in one course, or it gives a very inadequate introduction to a wide range of topics without actually doing anything very worthwhile with any of them. The latter is useless. The former is acceptable if the people using it understand that any given course will be only a selection of topics from the text, and it may be necessary if the text will be used by different instructors for different kinds of audience. Still, I prefer a more focussed text.
I also think that most elementary discrete mathematics texts do far too much formal logic. In my experience it does not help students learn to read and write proofs and is largely a waste of time. Similarly, it's very easy to get bogged down in basic set operations and relations and functions; beyond whatever bare minimum is actually needed, these really belong in some other course.
Comment: Tnx for answer;
about the background : they know a little combination and a basic theory of graph.
and they are firs year student at computer engineering. this course is basic for data structure and algorithms.


How to write fraction value using html?

Question: I want to write fraction value such as the picture below:

How do I write fraction value using html without using image?
NOTE: I don't want this 1 1/2 pattern but strictly just as the pic above
Comment: Times have changed and we can now use MathML. See [my answer below](http://stackoverflow.com/questions/7525977/how-to-write-fraction-value-using-html/10081414#10081414).
Comment: @0b10011 To be fair: there is a [problem with browser support](https://stackoverflow.com/questions/7525977/how-to-write-fraction-value-using-html#comment64486744_10081414) for your solution. It is still [like this in 2020](https://caniuse.com/#feat=mathml).
Comment: This source is pretty old, but I find it useful for creating simple fractions in HTML and CSS. https://www.periodni.com/mathematical_and_chemical_equations_on_web.html
Answer: Try the following:

11⁄2

This displays as:
11⁄2
Comment: In the most recent versions of Chrome, Firefox, and Opera, inputting `1 1⁄2` will automatically convert the numerator and denominator to unicode super- and subscripts, which looks even better than HTML super- and subscripts: 1 1⁄2
Answer:

.frac {
    display: inline-block;
    position: relative;
    vertical-align: middle;
    letter-spacing: 0.001em;
    text-align: center;
}
.frac > span {
    display: block;
    padding: 0.1em;
}
.frac span.bottom {
    border-top: thin solid black;
}
.frac span.symbol {
    display: none;
}
1

    1
    /
    2

Comment: Works perfectly! I think this should be the accepted answer as in the question the asker wanted something looking EXACTLY the same, which is not what is in the accepted answer.
Comment: This answer is definitely visually the most pretty! Thanks!
Comment: I also like how you have a backup way of displaying the fraction in case the CSS is disabled
Comment: Runs perfect. Thanks!
Comment: omg, this is such an underrated solution. The way it works it genius! Brilliant. +1
Answer: The following code will be rendered just as the example in the question, and if the client does not support CSS it will be rendered as plain text, still readable as a fraction:

1 12/256.

span.frac {
  display: inline-block;
  font-size: 50%;
  text-align: center;
}
span.frac > sup {
  display: block;
  border-bottom: 1px solid;
  font: inherit;
}
span.frac > span {
  display: none;
}
span.frac > sub {
  display: block;
  font: inherit;
}

The middle  serves only for the clients who do not render CSS - the text is still readable as 1 12/256 - and that's why you should place a space between the integer and the fraction.
You may want to change the font-size, because the resulting element may be a little taller than the other characters in the line, or you may want to use a relative position to shift it a little to the bottom.
But the general idea, as presented here, may be enough for the basic use.
Comment: When writing two fractions with a plus sign, the plus sign is not aligned. You can change this by wrapping the + sign with: `+`, see result http://jsfiddle.net/hx5oyotq/1/
Answer: Check out the following:

span.frac {
  display: inline-block;
  text-align: center;
  vertical-align: middle;
}
span.frac > sup, span.frac > sub {
  display: block;
  font: inherit;
  padding: 0 0.3em;
}
span.frac > sup {border-bottom: 0.08em solid;}
span.frac > span {display: none;}

7 42⁄73.

CodePen
Comment: omg, this is such an underrated solution. The way it works it genius! Brilliant. +1
Answer: You can use  and  elements in conjunction with the fraction slash entity ⁄
1⁄2  is 1⁄2
UPDATE: I made this fiddle that shows a hyphenated fraction in HTML using a table.

          1
          1

            2

Comment: The table is not a legal element in a ``, so it will not be possible to use this solution in a sentence, for example. Besides that, the `` should not be used for things other than tabular data.
Comment: Is that possible to use fraction hyphen instead of fraction slash?
Comment: Agree, your proposal is much better.
Comment: Doesn't seem to be on the [1.4 specs](http://www.w3.org/TR/html4/sgml/entities.html), so I guess there's no standard entity. I'm no css expert, so I'd do it with a two row, one column `` with a border in the middle. Quick and dirty.  Here you can see it in action: [Math in HTML](http://www.cs.tut.fi/~jkorpela/math/#twodim)
Answer: I think there is an easier way for doing this. Use the following HTML.

1 ½

Result is 1 ½
Comment: what if I have a fraction such as 2/15, how can I write it ??
Comment: This actually renders a unicode character, there are just the most used fractions available, won't work with any fraction.
⅐ ⅑ ⅒ ⅓ ⅔ ⅕ ⅖ ⅗ ⅘ ⅙ ⅚ ⅛ ⅜ ⅝ ⅞ ¼
½ ¾
Comment: Perfect! Simplest is best - all of these other answers are too much for something so simple.
Answer: Using MathML (Specification, Wikipedia):

<math>
 <mrow>
  <mn>1</mn>
  <mfrac>
   <mi>1</mi>
   <mi>2</mi>
  </mfrac>
 </mrow>
</math>
Comment: More specifically, it doesn't work on *most* browsers.  That link shows only Safari 9.1+, iOS Safari 9.2+, and Firefox 46+ with MS Edge "Not currently planned" and Chrome "No longer pursuing".
Comment: @Kartheeks As mentioned by jedierikb, MathML isn't fully supported by all browsers. It looks great in my default mobile browser though (Firefox), so it all depends on which browsers you're supporting.
Comment: Ah, the eternal chromium feature request: https://bugs.chromium.org/p/chromium/issues/detail?id=152430
Comment: for cross browser support of MathMl use MathJax :-
Answer: Using pure html and with margin property of br you can work around

br {
    content: "";
    margin: -1%;
    display: block;
 }
<big>1</big> <big>1</big>
   <big>2</big>
Answer: Here is another method using newer CSS methods. This method also uses custom tags, but you can change these to

 if you're not fond of custom tags.
Copy the following to your CSS:
Use .fraction and .numer if you use classes instead
fraction {
  display: inline-grid;

  grid-template-columns: 1fr;
  grid-template-rows: 1fr 1fr;

  font-size: 0.8em; // You can change fraction size here. I recommend 0.5em ~ 0.8em
  vertical-align: top;
}

numer {
  border-bottom: 1px solid;
}

You can now use the tags like this:
Add 1 <fraction> <numer>1</numer> 2 </fraction> cups of flour into the bowl and stir.

Output

I'd also recommend using read-only formatting for screen-reader output:
CSS
read {
  position: absolute;
  font-size: 0;
}

HTML
1 <fraction> <read>and</read> <numer>1</numer> <read>over</read> 2 </fraction>

Screen-reader: "one and one over two..."
Answer: Simple "inline" HTML
a

    1
    2

b

CodePen
https://codepen.io/eyedean/pen/bGMqBaB
Screenshot
Answer:
br {
    content: "";
    margin: -1%;
    display: block;
 }

<big>1</big> <big>1</big>
   <big>2</big>

How to write fraction value using html?


jquery array to php JSON

Question: I have various textnodes (p) and headers that I extract using jquery and store into an array :
<code>var textnode = $(source).children("p:not(:has(img))").map(function () {
    return $(this).outerHTML();
}).get();
var headerone = $(source).children('h1').map(function () {
    return $(this).outerHTML();
}).get();
</code>
I need to take the textnode array and headerone array and pass it via ajax to a php script (which will consequently store it in mysql). Does serializeArray work in this case or could I use .stringify. Would I need to .decode this in php (version 5.3.4)?
Comment: i am not sure what you are doing. that does not look like proper jQuery at all...
Comment: is this javascript? and if it is, what library are you using?
Comment: @Praneet Sharma: Have you tried anything yet or are you just wondering?
Comment: I posted the slice of code that shows how I add elements into the array. @netcoder, I've been looking at jquery-json but I was wondering if decoding in php would also be necessary and how I would use the .ajax method to pass it to php
Comment: @Neal: yes it does, what are you talking about?
Comment: @Dereleased, when have you ever seen jQuery code that had just `.get()` at the end?...
Comment: @Neal: When you want to get a raw HTMLElement object out of a jQuery array.  This is not the same as jQuery's AJAX Get method.
Comment: @Neal: http://docs.jquery.com/Get#.get.28.29_-_DOM_manipulation
Comment: @Dereleased. the code above has **no** index. its just `get(null)`
Comment: @Neal: `function (a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]}` is `jQuery.fn.get` -- Contrast to `jQuery.get` which is `function (a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})}`
Answer: If you send it via jQuery Ajax, it will be automatically serialized and will be available to your PHP as a $_REQUEST array variable.
http://api.jquery.com/jQuery.ajax/
Comment: $.ajax({
   type: "POST",
   url: "store.php",
   data: textnode&headerone,
   success: function(){
     alert( "saved data" );
   }
 });
Comment: would that be enough or would I have to encode in json first?
Comment: well, you'll need for data to look more like: `'textnode=' + textnode + '&headerone=' + headerone` or `{textnode:textnode,headerone:headerone}`, but you don't have to serialize it as JSON.  If you send it like that, you'll access it using `$_POST['textnode']` and `$_POST['headerone']`
Comment: @Dereleased, according to the documentation jQuery .ajax will serialize a key->value array automagically.  So, you're correct that you can pass a string, but according to the documentation you can also send a properly formatted array and it will do the rest.
Comment: Nothing you just said isn't true =) I was responding to the suggestion of `data: textnode&headerone`
Comment: if you're going synchronous or don't care about a return value, .post is fine.  But if you're going asynchronous or want to get a result back, .ajax is your solution.  Don't shy away, it's really very easy to use.

jquery array to php JSON