Q:

How does ammonium nitrate explode on its own?

I thought ammonium nitrate was an oxidizer that needed to be mixed with fuel to form a high explosive (e.g., ANFO). But apparently there have been accidental explosions involving just the "fertilizer". Are these explosions also detonations? What is the chemical formula for the process?
$$\ce{NH4NO3 -> ???}$$
Part of my motive for asking is the news today (Aug 4, 2020) of an explosion in Beirut. Initial reports say it was caused by "2750 tons of stored ammonium nitrate".

A:

It is known that ammonium nitrate decompose exothermically when heated to form nitrous oxide and water. This paper1 notes that the irreversible decomposition of ammonium nitrate occurs at the temperature range of $\pu{230-260 ^\circ C}$.
$$\ce{NH4NO3 ->[t >230 ^\circ C] N2O + 2H2O}$$
They also further noted that beyond $\pu{280 ^\circ C}$, $\ce{NH4NO3}$ is  capable of rapid, self-accelerating decomposition (to the point of detonation).
But at the detonation temperature, $\mathrm{t_d}$ (the temperature at which compounds detonate), ammonium nitrate fully decomposes to nitrogen, oxygen and water releasing a tremendous amount of energy.
$$\ce{2NH4NO3 ->[t_d] 2N2 + O2 + 4H2O}$$
In the context of Beirut explosion, the question that raised was "when did ammonium nitrate reached detonation temperature, and why did it suddenly explode?". According to a news report from cnet.com:

When heated to above 170 degrees Fahrenheit, ammonium nitrate begins
to undergo decomposition. But with rapid heating or detonation, a
chemical reaction can occur that converts ammonium nitrate to nitrogen
and oxygen gas and water vapor. The products of the reaction are
harmless -- they're found in our atmosphere -- but the process
releases huge amounts of energy.[...]
Additionally, in the explosion, not all of the ammonium nitrate is
used up and exploded. Some of it decomposes slowly creating toxic
gases like nitrogen oxides. It's these gases that are responsible for
the red-brown plume of smoke seen in the aftermath of the Beirut
explosion, Rae said.

So, my theory is that ammonium nitrate started heating (from the fire) releasing all sorts of nitrogen oxides (the red fumes). This fire further accelerated the reaction, further heating the remaining ammonium nitrate to the point of detonation and that's when ammonium nitrate exploded instantaneously releasing tremendous amount of energy which send shockwaves around the site along with a white mushroom shaped cloud (from @DDuck's comment) which could probably be nitrogen and/or water vapours where the humid air (water vapor laden air) condensed due to the explosion(@StianYttervik) with release of nitrogen. It is a sad and quite devastating incident.
References

On the Thermal Decomposition of Ammonium Nitrate. Steady-state Reaction
Temperatures and Reaction Rate By George Feick and R. M. Hainer, 1954 (PDF)
Reaction Rates of Ammonium Nitrate in Detonation
Melvin A. Cook, Earle B. Mayfield, and William S. Partridge
The Journal of Physical Chemistry 1955 59 (8), 675-680
DOI: 10.1021/j150530a002 (PDF)
https://en.wikipedia.org/wiki/2020_Beirut_explosions

A:

Ammonium nitrate ($\ce{NH4NO3}$) is widely used in the fertilizer industry and is one of the most concentrated forms of nitrogen fertilizer (35% of $\ce{N}$). At the same time, it has also been widely used as an explosive material for detonation in mines. Because of its explosiveness, $\ce{NH4NO3}$ is associated with various hazards including fire and explosion, which have occurred repeatedly in the past (more than 70 incidents during 20th century, more than half of them occurred in the US soil). Regardless, $\ce{NH4NO3}$ is not considered a flammable or combustible material at ambient temperature and pressure (Ref.1). However, it is a strong oxidizing agent that can detonate under certain conditions such as temperature, fire, confinement, and presence of impurities (e.g., $\ce{KCl}$), which can be act as a promoter to detonate (Ref.2).
To use as an explosive or a blasting reagent, $\ce{NH4NO3}$ is mixed with fuel oil, which is called ammonium nitrate fuel-oil (ANFO; Ref.1). According to Ref.2, during the explosion, following exothermic reaction would take place (hydrocarbon is represented by $\ce{CH2}$):
$$\ce{3NH4NO3 + CH2 -> 3N2 + 7 H2O + CO2} \quad \Delta H = \pu{-4017 kJ/kg} \tag1$$
Interestingly, this can be compared with TNT, the heat of combustion of which is $\Delta H = \pu{-4196 kJ/kg}$. Without fuel oil, can be detonated under certain conditions.  It is believed that the vaporization of molten $\ce{NH4NO3}$ leads to the formation of ammonia and nitric acid, which could initiate the decomposition of $\ce{NH4NO3}$ through following reaction:
$$\ce{NH4NO3 <=> HNO3 + NH3} \quad \Delta H = \pu{176 kJ/mol} \tag2$$
At higher temperatures (i.e., between $\pu{170 ^\circ C}$ and $\pu{280 ^\circ C}$) exothermic irreversible reactions (equations $(3)-(5)$) occur:
$$\ce{NH4NO3 -> N2O + 2H2O } \quad \Delta H = \pu{-59 kJ/mol} \tag3$$
$$\ce{NH4NO3 -> 1/2N2 + NO + 2H2O } \quad \Delta H = \pu{-2597 kJ/mol} \tag4$$
$$\ce{NH4NO3 -> 3/4N2 + 1/2NO2 + 2H2O } \quad \Delta H = \pu{-944 kJ/mol} \tag5$$
If the material is suddenly heated up, there will be explosive decompositions as shown in equations $(6)$ and $(7)$):
$$\ce{2NH4NO3 -> 2N2 + O2 + 4H2O } \quad \Delta H = \pu{-1057 kJ/mol} \tag6$$
$$\ce{8NH4NO3 -> 5N2 + 4NO + 2NO2 + 16H2O } \quad \Delta H = \pu{-600 kJ/mol} \tag7$$
Keep in mind that all of these reactions except for $(2)$ are exothermic. Also, most products are gases. I attached PDF file if Ref.2 if a reader is interested in how explosions happen during right conditions (otherwise, it is a broad field to explain). For instance, the reaction $(3)$ can be made more exothermic ($\pu{789 kJ/mol}$) with more gaseous products, if some oxidisable fuel is added such as $\ce{C}$ (Ref.3):
$$\ce{2NH4NO3 (s) + C (s)  -> 2N2 (g) + CO2 (g) + 4H2O (g)} \tag8$$
It is evident from the past incidents involving $\ce{NH4NO3}$ that the presence of impurities and environmental conditions have a huge effect on the detonation of $\ce{NH4NO3}$ during storage. For example, one of the deadliest industrial incidents in US history occurred on April 16, 1947, in Texas City, Texas where an $\ce{NH4NO3}$ explosion involving $\pu{2300 tons}$ of $\ce{NH4NO3}$ caused 581 fatalities and thousands of injuries. The fire was caused by the initial explosion of $\ce{NH4NO3}$ on a ship, which resulted in subsequent chain reactions of fires and explosions in other ships and facilities nearby. The exploded $\ce{NH4NO3}$ was coated with (carbon based) wax to prevent caking (See equation $(8)$ above). After this accident, the new technologies and safe practices introduced in the 1950s eliminated the use of wax coatings (Ref.2).
References:

Guy Marlair, Marie-Astrid Kordek, "Safety and security issues relating to low capacity storage of AN-based fertilizers," Journal of Hazardous Materials 2005, 123(1–3), 13-28 (https://doi.org/10.1016/j.jhazmat.2005.03.028).
Zhe Han, "Thermal Stability Studies of Ammonium Nitrate," Ph.D. Dissertation, Texas A&M University, TX, 2016 (PDF).
Alex M. Djerdjev, Pramith Priyananda, Jeff Gore, James K. Beattie, Chiara Neto, Brian S. Hawkett, "The mechanism of the spontaneous detonation of ammonium nitrate in reactive grounds," Journal of Environmental Chemical Engineering 2018, 6(1), 281-288 (https://doi.org/10.1016/j.jece.2017.12.003).

A:

First,
ammonium nitrate is a kind of mixture between an oxidizer - the nitrate part - and a reducer - the ammonium one. This is at the core of your question.
The direct decomposition correctly mentioned in the answers is nevertheless a process in which something gets oxidised and something gets reduced.
In ammonium nitrate basically you have all you need - the "fuel“ and the “oxygen“ analogues of what is involved in a standard, explosive or not, combustion.
Still the other answers are valid and more detailed from a chemical mechanicist viewpoint. One point out the presence of NO2 clearly seen by its red brownish colour before the second powerful explosion.
But the straight answer to your question is that the oxidizer and the reducing stuffs are already within the salt.

Side note: ammonium nitrate can decompose by mechanical shock, so there were enough conditions to trigger the second powerful blast.


Q:

Drawn TextView doesn't appear

I have this class for drawing text to a canvas. Nothing appears though when I draw text. Although the canvas can be drawn to because some other code works fine.
Is there something I'm missing? Also, it would be good to limit the width and height of the drawable area of the canvas too.
The context comes from the same view as the canvas.
public class GraphicsDroid
    {
        readonly Android.Graphics.Canvas canvas;
        readonly Context context;

        public GraphicsDroid(Android.Graphics.Canvas canvas, Context context)
        {
            this.canvas = canvas;
            this.context = context;
        }

        public void DrawText((Color?, Color) color, float fontSize, string text, float x, float y, float width, float height)
        {
            var textView = new TextView(context)
            {
                Text = text
            };

            textView.SetSingleLine(true);
            textView.Ellipsize = TruncateAt.End;
            textView.SetTextColor(color.Item2.ToAndroid());
            textView.TextSize = fontSize;
            textView.SetWidth((int) width);
            textView.SetHeight((int) height);

            if (color.Item1 is Color background)
            {
                textView.SetBackgroundColor(background.ToAndroid());
            }

            var saveCount = canvas.Save();

            try
            {
                canvas.Translate(x, y);

                textView.Draw(canvas);
            }
            finally
            {
                canvas.RestoreToCount(saveCount);
            }
        }
    }

A:

I rendered the textview to a layout...
public void DrawText((Color?, Color) color, float fontSize, string text, float x, float y, float width, float height)
        {
            var layout = new LinearLayout(context);

            var textView = new TextView(context)
            {
                Text = text
            };

            textView.SetSingleLine(true);
            textView.Ellipsize = TruncateAt.End;
            textView.SetTextColor(color.Item2.ToAndroid());
            textView.TextSize = fontSize;
            textView.SetWidth((int) width);
            textView.SetHeight((int) height);

            if (color.Item1 is Color background)
            {
                textView.SetBackgroundColor(background.ToAndroid());
            }

            layout.AddView(textView);

            layout.Measure(canvas.Width, canvas.Height);
            layout.Layout(0, 0, canvas.Width, canvas.Height);

            var saveCount = canvas.Save();

            try
            {
                canvas.Translate(x, y);

                layout.Draw(canvas);
            }
            finally
            {
                canvas.RestoreToCount(saveCount);
            }
        }


Q:

Query Regarding application context and beanfactory in spring

Possible Duplicate:
New to Spring - BeanFactory vs ApplicationContext?

Why we always use the term "spring applicationcontext" when we talk about the spring application deployed in some app server. Why not bean factory.

A:

Because the concrete implementation used by the app is also an instance of ApplicationContext, which extends BeanFactory.


Q:

HighCarts Tooltip position relative to mouse

I am using highcharts to create graphics in my website, however this tooltip covers my bars, Is there a way to tell the tooltip todisplay on top of the bar instead that ‘ON’ it?
here is what I am seeing:

A:

There are many s question around tool-tip positioning on StackOverflow ,The way I used in my chart was to show tooltip left or right on hover of column using positioner.
 tooltip: {
   positioner: function(labelWidth, labelHeight, point) {
                         var tooltipX, tooltipY;
                            if (point.plotX + labelWidth > this.chart.plotWidth) {
                                tooltipX = point.plotX + this.chart.plotLeft - labelWidth - 40;
                            } else {
                                tooltipX = point.plotX + this.chart.plotLeft + 40;
                            }
                            tooltipY = point.plotY + this.chart.plotTop - 20;
                            return {
                                x: tooltipX,
                                y: tooltipY
                            };
                    } }


Q:

Switch order of hyphenated words

What is the best way to parse a list of hyphenated words and return the beginning and end words switched?
Input:
spider-man
wonder-woman

Output:
man-spider
woman-wonder

A:

You could split it and then reverse it.
"spider-man".split('-').reverse.join('-')
 #=> "man-spider"

A:

You could go with regex
"spider-man".gsub(/^(.+)-(.+)$/, '\2-\1')
#=> "man-spider"

And it will be as twice as slower than @rohit89 solution ;)


Q:

Limit - Applicability of L'Hopital's Rule:$\lim\limits_{x \to 0^+} \frac{xe^x}{e^x-1}$

I am required to find $\lim\limits_{x \to 0^+} \frac{xe^x}{e^x-1}$.

My attempt:
$\lim\limits_{x \to 0^+} \frac{xe^x}{e^x-1}$ = $\lim\limits_{x \to 0^+} e^x$ $\cdot$ $\lim\limits_{x \to 0^+} \frac{x}{e^x-1}$
$=1\cdot\lim\limits_{x \to 0^+} \frac{x}{e^x-1}$
$=\lim\limits_{x \to 0^+} e^{-x}$ (L'Hopital's Rule)
$= 1$ (which is the correct answer)

My question is: Why am I not able to apply the rule to the equation right from the beginning [since substituting $0$ we get $\frac{0}{0}$]?
$\lim\limits_{x \to 0^+} \frac{xe^x}{e^x-1}$
$=\lim\limits_{x \to 0^+} \frac{xe^x}{e^x}$
$=\lim\limits_{x \to 0^+}x$
$=0$ (wrong)

A:

If you want to apply L'Hospital's rule right from the beginning, you may write
$$
\begin{align}
\lim\limits_{x \to 0^+}\frac{xe^x}{e^x-1}&=\lim\limits_{x \to 0^+}\frac{e^x+xe^x}{e^x}=\frac{1+0}1=1
\end{align}
$$ since
$$
(xe^x)'=e^x+xe^x.
$$


Q:

How to refer a job candidate when you're planning to leave for a new job soon

I've been offered and accepted a new job, which I'm excited about. The offer is conditional on a background check, so I'm waiting to give my two weeks notice and should be doing that next week.
Recently, a friend has been looking for a new job and I was able to convince them to apply for a position on my project. Personally, I think he would be a decent replacement for myself.
Will it come across as dishonest if I submit them as a referral and then resign a few days later? Will my impending resignation reflect poorly on my friend? Is there any reason for me to suggest them as a candidate after I give notice?
I tried to find a referral tag, but couldn't.

A:

The fact that you have made other plans theoretically shouldn't interfere with the recommendation. People are people and someone may be grumpy about it, but the recommendation is still more likely to help your friend than tonhurt him or her.


Q:

mvc3 dropDownList Validation because of optionLabel

@Html.DropDownList(
   "CreatedByUser_ID",
   new SelectList(
          Model.GetUsers(),
          "ID",
          "Name",
          (int)Model.CreatedByUser_ID),
   "select one user----")

CreatedByUser_ID property on model has no Required attribute, but on client side the generated select box is validated. If I remove optionLabel (select one user----) then validation is turned off.
Why mvc3 automatically validate my dropdownbox without required field ?
Thank you

A:

I guess if your model property CreatedByUser_ID is an int, the HTML rendered by the helper will not specify a value attribute for the "select one user" option. You can't give an int a null value, so the validation kicks in.
Surely you would want the user to select an option? If not, try making your CreatedByUser_ID a nullable int - int? in C#.


Q:

Difference between Element.scrollHeight and the height returned by height() method

What is the difference between Element.scrollHeight and the height returned by the JQuery $(ElementSelector).height() method.
I have seen this and this and I know that scrollHeight is the height of content, including the content which overflows outside the viewport. My question is that isn't that the same as the height returned by the height() method. I wrote this JSFiddle as a test of that.

A:

Another difference is...
The height property sets the height of an element and does not include padding, borders, or margins; it sets the height of the area inside the padding, border, and margin of the element.
scrollHeight includes the element's padding, but not its border or margin.
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight


Q:

Zoidberg curve, can't reach "zoidberg" solution

I am trying to plot the Zoidberg curve in Matlab just for fun.
I just copied the equation shown there and defined the sgn and theta functions but I can't achieve the Zoidberg plot, instead I got this:

but I should have gotten this:

Here is my code:
sgn function:
function result=sgn(in)

if in<0
    result=-1;
else
    result=1;
end

end

theta function
function result=theta(in)

if in<0
    result=0;
else
    if in==0
        result=0.5;
    else
        result=1;
    end
end
end

main:
clc;clear;
t=0:0.0001:76*pi;
x=((4619/60*sin(t+11/7)+109/8*sin(2*t+11/7)+9/7*sin(3*t+11/7)+89/15*sin(4*t+11/7)+5/11*sin(5*t+11/7)-9839/41)*theta(75*pi-t)*theta(t-71*pi)+(-179/8*sin(11/7-2*t)+2101/20*sin(t+11/7)+5/6*sin(3*t+23/5)+65/9*sin(4*t+33/7)+33/8*sin(5*t+8/5)-698/9)*theta(71*pi-t)*theta(t-67*pi)+(952/15*sin(t+11/7)+116/21*sin(2*t+19/12)+26/5*sin(3*t+11/7)+11/9*sin(4*t+11/7)+25/11*sin(5*t+11/7)+3071/10)*theta(67*pi-t)*theta(t-63*pi)+(-4/11*sin(17/11-4*t)+657/13*sin(t+33/7)+29/11*sin(2*t+47/10)+17/6*sin(3*t+14/9)+2/13*sin(5*t+22/13)+15/8*sin(6*t+33/7)+16/11*sin(7*t+47/10)+5/3*sin(8*t+47/10)+24/13*sin(9*t+33/7)+9/11*sin(10*t+47/10)+6/5*sin(11*t+47/10)+17/18*sin(12*t+47/10)+4/9*sin(13*t+75/16)+1163/3)*theta(63*pi-t)*theta(t-59*pi)+(-11/13*sin(11/7-6*t)-17/10*sin(11/7-4*t)+261/7*sin(t+11/7)+17/3*sin(2*t+33/7)+44/19*sin(3*t+11/7)+7/9*sin(5*t+14/9)+259/3)*theta(59*pi-t)*theta(t-55*pi)+(-9/11*sin(26/17-23*t)-287/9*sin(11/7-5*t)-271/9*sin(17/11-3*t)+1551/13*sin(t+17/11)+685/8*sin(2*t+17/11)+535/11*sin(4*t+14/9)+311/11*sin(6*t+14/9)+1141/60*sin(7*t+61/13)+19/9*sin(8*t+21/11)+55/8*sin(9*t+77/17)+239/12*sin(10*t+9/2)+7/9*sin(11*t+69/16)+59/6*sin(12*t+13/10)+73/24*sin(13*t+13/11)+17/12*sin(14*t+47/11)+11/16*sin(15*t+22/5)+17/6*sin(16*t+4/3)+7/11*sin(17*t+17/13)+17/9*sin(18*t+11/9)+7/4*sin(19*t+7/5)+5/4*sin(20*t+53/12)+50/13*sin(21*t+12/11)+103/13*sin(22*t+8/7)+13/5*sin(24*t+29/7)+1/2*sin(25*t+16/5)+31/16*sin(26*t+13/3)+8/7*sin(27*t+33/8)+17/14*sin(28*t+123/31)+22/9*sin(29*t+30/7)+2/3*sin(30*t+48/13)+19/12*sin(31*t+89/22)+18/11*sin(32*t+46/11)+417/8)*theta(55*pi-t)*theta(t-51*pi)+(-2/7*sin(14/9-10*t)-9/13*sin(14/9-8*t)-224/11*sin(11/7-3*t)+197/11*sin(t+11/7)+139/14*sin(2*t+11/7)+17/12*sin(4*t+47/10)+43/12*sin(5*t+33/7)+2/5*sin(6*t+47/10)+28/19*sin(7*t+47/10)+34/33*sin(9*t+47/10)+1/4*sin(11*t+14/3)+6/19*sin(12*t+19/12)-955/8)*theta(51*pi-t)*theta(t-47*pi)+(-149/28*sin(11/7-5*t)-65/6*sin(11/7-3*t)-641/12*sin(11/7-t)+265/9*sin(2*t+11/7)+37/5*sin(4*t+11/7)+7931/15)*theta(47*pi-t)*theta(t-43*pi)+(1810/9*sin(t+11/7)+1904/5*sin(2*t+11/7)+481/24*sin(3*t+61/13)+181/30*sin(4*t+11/7)+277/10*sin(5*t+19/12)+292/11*sin(6*t+19/12)+25/7*sin(7*t+47/10)+38/5*sin(8*t+8/5)+74/11*sin(9*t+8/5)+75/13*sin(10*t+8/5)+18/11*sin(11*t+19/12)+3109/13)*theta(43*pi-t)*theta(t-39*pi)+(-19/9*sin(11/7-12*t)-21/8*sin(11/7-10*t)-1/11*sin(17/11-8*t)-32/19*sin(14/9-6*t)+4137/22*sin(t+11/7)+177/14*sin(2*t+33/7)+173/14*sin(3*t+11/7)+3/2*sin(4*t+19/12)+5/8*sin(5*t+14/9)+21/8*sin(7*t+11/7)+19/10*sin(9*t+11/7)+41/15*sin(11*t+11/7)+2104/3)*theta(39*pi-t)*theta(t-35*pi)+(-5/6*sin(17/12-11*t)-7/15*sin(5/12-10*t)-32/13*sin(7/13-3*t)-139/7*sin(2/7-2*t)+2224/15*sin(t+9/10)+103/10*sin(4*t+23/5)+45/44*sin(5*t+7/3)+35/9*sin(6*t+23/8)+21/10*sin(7*t+25/11)+10/11*sin(8*t+4/5)+23/15*sin(9*t+5/7)+4/5*sin(12*t+9/2)+1339/11)*theta(35*pi-t)*theta(t-31*pi)+(1069/6*sin(t+18/13)+643/28*sin(2*t+11/7)+255/16*sin(3*t+11/15)+247/29*sin(4*t+45/13)+53/6*sin(5*t+9/11)+14/29*sin(6*t+31/7)+21/5*sin(7*t+19/7)+53/20*sin(8*t+3/14)+24/13*sin(9*t+24/11)+sin(10*t+27/14)+7/8*sin(11*t+11/9)+1/3*sin(12*t+7/4)+4512/25)*theta(31*pi-t)*theta(t-27*pi)+(-73/8*sin(1/9-11*t)-101/7*sin(7/8-3*t)+3221/13*sin(t+4/5)+389/8*sin(2*t+36/11)+368/11*sin(4*t+80/27)+107/4*sin(5*t+1/4)+29/2*sin(6*t+13/4)+237/19*sin(7*t+1/6)+263/17*sin(8*t+10/3)+79/9*sin(9*t+5/14)+68/9*sin(10*t+67/22)+43/5*sin(12*t+29/9)-3139/7)*theta(27*pi-t)*theta(t-23*pi)+(-7/9*sin(9/10-17*t)-22/13*sin(86/85-11*t)-43/10*sin(1/33-7*t)-64/7*sin(2/9-5*t)-19/10*sin(7/10-4*t)+2327/9*sin(t+19/5)+46*sin(2*t+7/4)+52/7*sin(3*t+31/9)+44/13*sin(6*t+17/11)+35/13*sin(8*t+23/8)+45/17*sin(9*t+9/2)+35/17*sin(10*t+34/9)+17/10*sin(12*t+17/8)+3/5*sin(13*t+41/10)+15/13*sin(14*t+41/14)+10/19*sin(15*t+139/35)+7/9*sin(16*t+24/11)+7/8*sin(18*t+3/5)+9/8*sin(19*t+6/7)+7/9*sin(20*t+25/14)+17/18*sin(21*t+7/11)+9/8*sin(22*t+22/15)+3/7*sin(23*t+11/4)+7/12*sin(24*t+26/9)+3/14*sin(25*t+26/7)+12/25*sin(26*t+62/25)+7/11*sin(27*t+64/15)+1/4*sin(28*t+95/24)+7/20*sin(29*t+3)+4/9*sin(30*t+14/5)+1/9*sin(31*t+4)+1/11*sin(32*t+9/11)+3/13*sin(33*t+8/5)+1/8*sin(34*t+20/11)+2/5*sin(35*t+2/7)-16257/22)*theta(23*pi-t)*theta(t-19*pi)+(-3/8*sin(2/7-5*t)-51/19*sin(1/28-3*t)-34/7*sin(3/8-2*t)+20/9*sin(t+155/52)+16/17*sin(4*t+25/7)+4/9*sin(6*t+24/7)+3/10*sin(7*t+3/7)+3/11*sin(8*t+41/11)+2/11*sin(9*t+9/19)+1/8*sin(10*t+389/97)+1/6*sin(11*t+2/7)+1/6*sin(12*t+47/16)+5910/19)*theta(19*pi-t)*theta(t-15*pi)+(-4/15*sin(12/23-7*t)+24/7*sin(t+21/8)+15/4*sin(2*t+3/2)+31/9*sin(3*t+7/5)+8/5*sin(4*t+25/7)+13/17*sin(5*t+1/4)+2/3*sin(6*t+46/15)+5/13*sin(8*t+3)+3/7*sin(9*t+2/5)+3/10*sin(10*t+53/15)+2/7*sin(11*t+2/5)+1/3*sin(12*t+25/7)+109/2)*theta(15*pi-t)*theta(t-11*pi)+(-53/14*sin(18/13-4*t)+592/7*sin(t+21/10)+107/27*sin(2*t+17/4)+29/13*sin(3*t+41/11)+859/12)*theta(11*pi-t)*theta(t-7*pi)+(287/3*sin(t+19/9)+16/5*sin(2*t+43/13)+57/10*sin(3*t+21/8)+33/17*sin(4*t+31/7)+1877/6)*theta(7*pi-t)*theta(t-3*pi)+(-5/8*sin(2/3-15*t)-17/8*sin(11/10-12*t)-11/6*sin(9/13-9*t)-507/10*sin(2/9-3*t)-69/13*sin(41/27-2*t)+1813/5*sin(t+11/3)+63/13*sin(4*t+25/8)+63/4*sin(5*t+23/5)+122/11*sin(6*t+49/16)+32/7*sin(7*t+19/9)+37/8*sin(8*t+12/7)+20/9*sin(10*t+17/8)+43/17*sin(11*t+1/69)+31/14*sin(13*t+21/5)+5/3*sin(14*t+32/11)+66/65*sin(16*t+53/14)+760/3)*theta(3*pi-t)*theta(t+pi))*theta(sqrt(sgn(sin(t/2))));
y=((-13/5*sin(11/7-5*t)-51/8*sin(11/7-3*t)-28*sin(11/7-t)+97/6*sin(2*t+11/7)+124/25*sin(4*t+11/7)-7811/8)*theta(75*pi-t)*theta(t-71*pi)+(-76/7*sin(13/9-4*t)-69/4*sin(43/29-3*t)-50*sin(17/11-2*t)+229/12*sin(t+17/11)+13/8*sin(5*t+4/5)-2538/7)*theta(71*pi-t)*theta(t-67*pi)+(-17/4*sin(11/7-3*t)-217/11*sin(11/7-t)+79/7*sin(2*t+11/7)+11/6*sin(4*t+11/7)+15/14*sin(5*t+33/7)-79/6)*theta(67*pi-t)*theta(t-63*pi)+(-164/9*sin(11/7-2*t)+845/12*sin(t+11/7)+7/8*sin(3*t+18/11)+89/10*sin(4*t+33/7)+34/23*sin(5*t+47/10)+105/26*sin(6*t+33/7)+8/11*sin(7*t+14/9)+1/8*sin(8*t+17/11)+25/12*sin(9*t+11/7)+13/9*sin(10*t+11/7)+33/16*sin(11*t+14/9)+13/27*sin(12*t+14/9)+2/3*sin(13*t+14/9)+2671/13)*theta(63*pi-t)*theta(t-59*pi)+(-64/65*sin(14/9-6*t)-25/9*sin(14/9-5*t)-34/9*sin(14/9-4*t)-57/14*sin(14/9-3*t)-19/14*sin(11/7-2*t)+21/2*sin(t+11/7)+3133/11)*theta(59*pi-t)*theta(t-55*pi)+(-25/24*sin(23/15-27*t)-5/14*sin(14/11-25*t)-2/3*sin(16/11-17*t)-55/9*sin(40/27-8*t)-352/13*sin(14/9-5*t)-1519/38*sin(14/9-3*t)+3329/32*sin(t+47/10)+297/4*sin(2*t+14/9)+1939/38*sin(4*t+14/9)+239/9*sin(6*t+32/21)+34/9*sin(7*t+19/15)+107/6*sin(9*t+10/7)+271/10*sin(10*t+40/9)+693/13*sin(11*t+86/19)+160/7*sin(12*t+13/9)+289/16*sin(13*t+7/6)+385/48*sin(14*t+9/7)+44/9*sin(15*t+5/4)+41/11*sin(16*t+13/10)+12/13*sin(18*t+12/5)+46/9*sin(19*t+40/9)+10/9*sin(20*t+38/25)+46/31*sin(21*t+75/16)+37/16*sin(22*t+41/10)+35/11*sin(23*t+43/10)+10/13*sin(24*t+63/16)+2/3*sin(26*t+47/13)+19/7*sin(28*t+6/5)+13/10*sin(29*t+59/13)+3/2*sin(30*t+4/3)+11/10*sin(31*t+5/7)+17/13*sin(32*t+15/4)-11101/75)*theta(55*pi-t)*theta(t-51*pi)+(-3/10*sin(14/9-12*t)-29/12*sin(11/7-6*t)-38/9*sin(11/7-4*t)-59/8*sin(11/7-t)+183/7*sin(2*t+11/7)+125/13*sin(3*t+11/7)+31/16*sin(5*t+19/12)+4/9*sin(7*t+11/7)+3/13*sin(8*t+47/10)+64/63*sin(9*t+14/9)+3/13*sin(10*t+33/7)+1/2*sin(11*t+19/12)-11360/13)*theta(51*pi-t)*theta(t-47*pi)+(-60/11*sin(11/7-4*t)-528/31*sin(11/7-3*t)-661/55*sin(11/7-2*t)-623/3*sin(11/7-t)+39/8*sin(5*t+33/7)-5871/8)*theta(47*pi-t)*theta(t-43*pi)+(-43/13*sin(14/9-11*t)-45/8*sin(11/7-9*t)-41/15*sin(14/9-8*t)-57/11*sin(14/9-7*t)-157/6*sin(11/7-5*t)-1813/6*sin(11/7-t)+1997/15*sin(2*t+11/7)+89/6*sin(3*t+47/10)+19/6*sin(4*t+23/15)+191/8*sin(6*t+11/7)+191/17*sin(10*t+19/12)-7307/9)*theta(43*pi-t)*theta(t-39*pi)+(-15/8*sin(11/7-12*t)-72/73*sin(14/9-11*t)-19/9*sin(11/7-10*t)-35/11*sin(11/7-9*t)-7/11*sin(14/9-8*t)-60/11*sin(11/7-7*t)-191/13*sin(11/7-5*t)-184/5*sin(11/7-3*t)-109/10*sin(11/7-2*t)-609/2*sin(11/7-t)+1/6*sin(4*t+5/4)+11/5*sin(6*t+47/10)-6582/11)*theta(39*pi-t)*theta(t-35*pi)+(-11/15*sin(6/7-9*t)-47/13*sin(26/25-5*t)-67/27*sin(13/12-4*t)-633/8*sin(3/10-t)+251/7*sin(2*t+9/8)+123/8*sin(3*t+64/15)+23/8*sin(6*t+22/13)+26/9*sin(7*t+23/6)+14/9*sin(8*t+3/5)+19/12*sin(10*t+9/7)+25/19*sin(11*t+13/3)+11/17*sin(12*t+7/12)-5757/11)*theta(35*pi-t)*theta(t-31*pi)+(-50/3*sin(3/4-3*t)+263/10*sin(t+83/28)+669/13*sin(2*t+11/5)+17*sin(4*t+13/7)+67/11*sin(5*t+19/8)+11/3*sin(6*t+1/12)+38/17*sin(7*t+9/5)+51/14*sin(8*t+5/3)+49/25*sin(9*t+41/10)+17/12*sin(10*t+7/12)+53/54*sin(11*t+24/7)+5/7*sin(12*t+7/4)-10661/26)*theta(31*pi-t)*theta(t-27*pi)+(-127/10*sin(16/17-7*t)-119/9*sin(11/9-5*t)-1191/4*sin(1/3-t)+735/11*sin(2*t+2/9)+287/8*sin(3*t+61/16)+504/19*sin(4*t+17/9)+73/9*sin(6*t+9/5)+62/7*sin(8*t+14/5)+32/5*sin(9*t+1/6)+7/2*sin(10*t+19/7)+19/7*sin(11*t+1/44)+167/56*sin(12*t+51/14)-12878/17)*theta(27*pi-t)*theta(t-23*pi)+(-5/12*sin(14/15-32*t)-1/18*sin(17/13-31*t)-23/11*sin(1/6-19*t)-11/9*sin(38/25-18*t)-243/61*sin(25/17-8*t)-35/9*sin(11/21-7*t)-87/7*sin(4/5-6*t)-2249/15*sin(1/10-2*t)+1997/10*sin(t+23/12)+725/13*sin(3*t+1)+67/8*sin(4*t+9/4)+216/11*sin(5*t+23/5)+18/11*sin(9*t+32/31)+48/13*sin(10*t+19/8)+211/35*sin(11*t+16/5)+36/13*sin(12*t+64/15)+30/29*sin(13*t+8/13)+20/11*sin(14*t+28/13)+11/17*sin(15*t+37/16)+5/8*sin(16*t+23/14)+4/7*sin(17*t+14/9)+91/45*sin(20*t+14/27)+47/31*sin(21*t+8/5)+6/7*sin(22*t+29/15)+8/9*sin(23*t+53/20)+13/10*sin(24*t+89/30)+8/9*sin(25*t+39/10)+7/20*sin(26*t+97/24)+4/9*sin(27*t+18/13)+7/8*sin(28*t+45/14)+2/7*sin(29*t+42/13)+3/11*sin(30*t+22/5)+8/17*sin(33*t+4/11)+5/9*sin(34*t+18/13)+3/14*sin(35*t+12/5)-3384/11)*theta(23*pi-t)*theta(t-19*pi)+(-1/38*sin(2/11-7*t)-35/11*sin(9/14-t)+341/85*sin(2*t+25/14)+34/11*sin(3*t+22/21)+42/43*sin(4*t+223/56)+14/15*sin(5*t+3/4)+12/23*sin(6*t+7/2)+1/7*sin(8*t+4)+2/11*sin(9*t+9/8)+2/11*sin(10*t+73/29)+1/7*sin(11*t+1/4)+2/11*sin(12*t+74/25)+2961/20)*theta(19*pi-t)*theta(t-15*pi)+(-3/11*sin(13/25-12*t)-1/3*sin(15/29-10*t)-1/9*sin(4/3-8*t)-16/9*sin(12/13-4*t)+35/18*sin(t+89/19)+33/8*sin(2*t+49/16)+43/14*sin(3*t+33/13)+3/10*sin(5*t+26/11)+3/10*sin(6*t+4/11)+9/17*sin(7*t+94/27)+1/5*sin(9*t+35/11)+1/4*sin(11*t+20/7)+2917/15)*theta(15*pi-t)*theta(t-11*pi)+(949/15*sin(t+11/3)+63/11*sin(2*t+19/9)+26/7*sin(3*t+22/5)+7/8*sin(4*t+28/13)+3715/23)*theta(11*pi-t)*theta(t-7*pi)+(658/9*sin(t+107/27)+57/10*sin(2*t+9/5)+56/13*sin(3*t+38/9)+7/6*sin(4*t+10/11)+1681/16)*theta(7*pi-t)*theta(t-3*pi)+(-9/11*sin(13/10-16*t)-14/15*sin(2/7-15*t)-12/7*sin(3/8-12*t)-29/6*sin(5/11-8*t)-80/9*sin(5/14-4*t)+3076/7*sin(t+12/5)+343/18*sin(2*t+13/3)+230/17*sin(3*t+31/8)+21/4*sin(5*t+53/21)+23/10*sin(6*t+1/5)+27/7*sin(7*t+5/12)+60/17*sin(9*t+38/9)+11/8*sin(10*t+49/16)+10/7*sin(11*t+2/3)+4/7*sin(13*t+18/5)+17/12*sin(14*t+9/7)+598/9)*theta(3*pi-t)*theta(t+pi))*theta(sqrt(sgn(sin(t/2))));

plot(x,y);

I changed the amount of points for the plot, now it has 2.3 million points but the plot is not Zoiberg.

A:

I'm not sure if it's the final solution, but it's close:
First thing your functions are all wrong. You need the value of the array, not of elements.
Second, use matlab sign function.
Finally, don't forget to add the dot operator in front of theta.
function main
clc;clear;
t=0:0.0001:(76*pi);
x=((4619/60*sin(t+11/7)+109/8*sin(2*t+11/7)+9/7*sin(3*t+11/7)+89/15*sin(4*t+11/7)+5/11*sin(5*t+11/7)-9839/41).*theta(75*pi-t).*theta(t-71*pi)+(-179/8*sin(11/7-2*t)+2101/20*sin(t+11/7)+5/6*sin(3*t+23/5)+65/9*sin(4*t+33/7)+33/8*sin(5*t+8/5)-698/9).*theta(71*pi-t).*theta(t-67*pi)+(952/15*sin(t+11/7)+116/21*sin(2*t+19/12)+26/5*sin(3*t+11/7)+11/9*sin(4*t+11/7)+25/11*sin(5*t+11/7)+3071/10).*theta(67*pi-t).*theta(t-63*pi)+(-4/11*sin(17/11-4*t)+657/13*sin(t+33/7)+29/11*sin(2*t+47/10)+17/6*sin(3*t+14/9)+2/13*sin(5*t+22/13)+15/8*sin(6*t+33/7)+16/11*sin(7*t+47/10)+5/3*sin(8*t+47/10)+24/13*sin(9*t+33/7)+9/11*sin(10*t+47/10)+6/5*sin(11*t+47/10)+17/18*sin(12*t+47/10)+4/9*sin(13*t+75/16)+1163/3).*theta(63*pi-t).*theta(t-59*pi)+(-11/13*sin(11/7-6*t)-17/10*sin(11/7-4*t)+261/7*sin(t+11/7)+17/3*sin(2*t+33/7)+44/19*sin(3*t+11/7)+7/9*sin(5*t+14/9)+259/3).*theta(59*pi-t).*theta(t-55*pi)+(-9/11*sin(26/17-23*t)-287/9*sin(11/7-5*t)-271/9*sin(17/11-3*t)+1551/13*sin(t+17/11)+685/8*sin(2*t+17/11)+535/11*sin(4*t+14/9)+311/11*sin(6*t+14/9)+1141/60*sin(7*t+61/13)+19/9*sin(8*t+21/11)+55/8*sin(9*t+77/17)+239/12*sin(10*t+9/2)+7/9*sin(11*t+69/16)+59/6*sin(12*t+13/10)+73/24*sin(13*t+13/11)+17/12*sin(14*t+47/11)+11/16*sin(15*t+22/5)+17/6*sin(16*t+4/3)+7/11*sin(17*t+17/13)+17/9*sin(18*t+11/9)+7/4*sin(19*t+7/5)+5/4*sin(20*t+53/12)+50/13*sin(21*t+12/11)+103/13*sin(22*t+8/7)+13/5*sin(24*t+29/7)+1/2*sin(25*t+16/5)+31/16*sin(26*t+13/3)+8/7*sin(27*t+33/8)+17/14*sin(28*t+123/31)+22/9*sin(29*t+30/7)+2/3*sin(30*t+48/13)+19/12*sin(31*t+89/22)+18/11*sin(32*t+46/11)+417/8).*theta(55*pi-t).*theta(t-51*pi)+(-2/7*sin(14/9-10*t)-9/13*sin(14/9-8*t)-224/11*sin(11/7-3*t)+197/11*sin(t+11/7)+139/14*sin(2*t+11/7)+17/12*sin(4*t+47/10)+43/12*sin(5*t+33/7)+2/5*sin(6*t+47/10)+28/19*sin(7*t+47/10)+34/33*sin(9*t+47/10)+1/4*sin(11*t+14/3)+6/19*sin(12*t+19/12)-955/8).*theta(51*pi-t).*theta(t-47*pi)+(-149/28*sin(11/7-5*t)-65/6*sin(11/7-3*t)-641/12*sin(11/7-t)+265/9*sin(2*t+11/7)+37/5*sin(4*t+11/7)+7931/15).*theta(47*pi-t).*theta(t-43*pi)+(1810/9*sin(t+11/7)+1904/5*sin(2*t+11/7)+481/24*sin(3*t+61/13)+181/30*sin(4*t+11/7)+277/10*sin(5*t+19/12)+292/11*sin(6*t+19/12)+25/7*sin(7*t+47/10)+38/5*sin(8*t+8/5)+74/11*sin(9*t+8/5)+75/13*sin(10*t+8/5)+18/11*sin(11*t+19/12)+3109/13).*theta(43*pi-t).*theta(t-39*pi)+(-19/9*sin(11/7-12*t)-21/8*sin(11/7-10*t)-1/11*sin(17/11-8*t)-32/19*sin(14/9-6*t)+4137/22*sin(t+11/7)+177/14*sin(2*t+33/7)+173/14*sin(3*t+11/7)+3/2*sin(4*t+19/12)+5/8*sin(5*t+14/9)+21/8*sin(7*t+11/7)+19/10*sin(9*t+11/7)+41/15*sin(11*t+11/7)+2104/3).*theta(39*pi-t).*theta(t-35*pi)+(-5/6*sin(17/12-11*t)-7/15*sin(5/12-10*t)-32/13*sin(7/13-3*t)-139/7*sin(2/7-2*t)+2224/15*sin(t+9/10)+103/10*sin(4*t+23/5)+45/44*sin(5*t+7/3)+35/9*sin(6*t+23/8)+21/10*sin(7*t+25/11)+10/11*sin(8*t+4/5)+23/15*sin(9*t+5/7)+4/5*sin(12*t+9/2)+1339/11).*theta(35*pi-t).*theta(t-31*pi)+(1069/6*sin(t+18/13)+643/28*sin(2*t+11/7)+255/16*sin(3*t+11/15)+247/29*sin(4*t+45/13)+53/6*sin(5*t+9/11)+14/29*sin(6*t+31/7)+21/5*sin(7*t+19/7)+53/20*sin(8*t+3/14)+24/13*sin(9*t+24/11)+sin(10*t+27/14)+7/8*sin(11*t+11/9)+1/3*sin(12*t+7/4)+4512/25).*theta(31*pi-t).*theta(t-27*pi)+(-73/8*sin(1/9-11*t)-101/7*sin(7/8-3*t)+3221/13*sin(t+4/5)+389/8*sin(2*t+36/11)+368/11*sin(4*t+80/27)+107/4*sin(5*t+1/4)+29/2*sin(6*t+13/4)+237/19*sin(7*t+1/6)+263/17*sin(8*t+10/3)+79/9*sin(9*t+5/14)+68/9*sin(10*t+67/22)+43/5*sin(12*t+29/9)-3139/7).*theta(27*pi-t).*theta(t-23*pi)+(-7/9*sin(9/10-17*t)-22/13*sin(86/85-11*t)-43/10*sin(1/33-7*t)-64/7*sin(2/9-5*t)-19/10*sin(7/10-4*t)+2327/9*sin(t+19/5)+46*sin(2*t+7/4)+52/7*sin(3*t+31/9)+44/13*sin(6*t+17/11)+35/13*sin(8*t+23/8)+45/17*sin(9*t+9/2)+35/17*sin(10*t+34/9)+17/10*sin(12*t+17/8)+3/5*sin(13*t+41/10)+15/13*sin(14*t+41/14)+10/19*sin(15*t+139/35)+7/9*sin(16*t+24/11)+7/8*sin(18*t+3/5)+9/8*sin(19*t+6/7)+7/9*sin(20*t+25/14)+17/18*sin(21*t+7/11)+9/8*sin(22*t+22/15)+3/7*sin(23*t+11/4)+7/12*sin(24*t+26/9)+3/14*sin(25*t+26/7)+12/25*sin(26*t+62/25)+7/11*sin(27*t+64/15)+1/4*sin(28*t+95/24)+7/20*sin(29*t+3)+4/9*sin(30*t+14/5)+1/9*sin(31*t+4)+1/11*sin(32*t+9/11)+3/13*sin(33*t+8/5)+1/8*sin(34*t+20/11)+2/5*sin(35*t+2/7)-16257/22).*theta(23*pi-t).*theta(t-19*pi)+(-3/8*sin(2/7-5*t)-51/19*sin(1/28-3*t)-34/7*sin(3/8-2*t)+20/9*sin(t+155/52)+16/17*sin(4*t+25/7)+4/9*sin(6*t+24/7)+3/10*sin(7*t+3/7)+3/11*sin(8*t+41/11)+2/11*sin(9*t+9/19)+1/8*sin(10*t+389/97)+1/6*sin(11*t+2/7)+1/6*sin(12*t+47/16)+5910/19).*theta(19*pi-t).*theta(t-15*pi)+(-4/15*sin(12/23-7*t)+24/7*sin(t+21/8)+15/4*sin(2*t+3/2)+31/9*sin(3*t+7/5)+8/5*sin(4*t+25/7)+13/17*sin(5*t+1/4)+2/3*sin(6*t+46/15)+5/13*sin(8*t+3)+3/7*sin(9*t+2/5)+3/10*sin(10*t+53/15)+2/7*sin(11*t+2/5)+1/3*sin(12*t+25/7)+109/2).*theta(15*pi-t).*theta(t-11*pi)+(-53/14*sin(18/13-4*t)+592/7*sin(t+21/10)+107/27*sin(2*t+17/4)+29/13*sin(3*t+41/11)+859/12).*theta(11*pi-t).*theta(t-7*pi)+(287/3*sin(t+19/9)+16/5*sin(2*t+43/13)+57/10*sin(3*t+21/8)+33/17*sin(4*t+31/7)+1877/6).*theta(7*pi-t).*theta(t-3*pi)+(-5/8*sin(2/3-15*t)-17/8*sin(11/10-12*t)-11/6*sin(9/13-9*t)-507/10*sin(2/9-3*t)-69/13*sin(41/27-2*t)+1813/5*sin(t+11/3)+63/13*sin(4*t+25/8)+63/4*sin(5*t+23/5)+122/11*sin(6*t+49/16)+32/7*sin(7*t+19/9)+37/8*sin(8*t+12/7)+20/9*sin(10*t+17/8)+43/17*sin(11*t+1/69)+31/14*sin(13*t+21/5)+5/3*sin(14*t+32/11)+66/65*sin(16*t+53/14)+760/3).*theta(3*pi-t).*theta(t+pi)).*theta(sqrt(sign(sin(t/2))));
y=((-13/5*sin(11/7-5*t)-51/8*sin(11/7-3*t)-28*sin(11/7-t)+97/6*sin(2*t+11/7)+124/25*sin(4*t+11/7)-7811/8).*theta(75*pi-t).*theta(t-71*pi)+(-76/7*sin(13/9-4*t)-69/4*sin(43/29-3*t)-50*sin(17/11-2*t)+229/12*sin(t+17/11)+13/8*sin(5*t+4/5)-2538/7).*theta(71*pi-t).*theta(t-67*pi)+(-17/4*sin(11/7-3*t)-217/11*sin(11/7-t)+79/7*sin(2*t+11/7)+11/6*sin(4*t+11/7)+15/14*sin(5*t+33/7)-79/6).*theta(67*pi-t).*theta(t-63*pi)+(-164/9*sin(11/7-2*t)+845/12*sin(t+11/7)+7/8*sin(3*t+18/11)+89/10*sin(4*t+33/7)+34/23*sin(5*t+47/10)+105/26*sin(6*t+33/7)+8/11*sin(7*t+14/9)+1/8*sin(8*t+17/11)+25/12*sin(9*t+11/7)+13/9*sin(10*t+11/7)+33/16*sin(11*t+14/9)+13/27*sin(12*t+14/9)+2/3*sin(13*t+14/9)+2671/13).*theta(63*pi-t).*theta(t-59*pi)+(-64/65*sin(14/9-6*t)-25/9*sin(14/9-5*t)-34/9*sin(14/9-4*t)-57/14*sin(14/9-3*t)-19/14*sin(11/7-2*t)+21/2*sin(t+11/7)+3133/11).*theta(59*pi-t).*theta(t-55*pi)+(-25/24*sin(23/15-27*t)-5/14*sin(14/11-25*t)-2/3*sin(16/11-17*t)-55/9*sin(40/27-8*t)-352/13*sin(14/9-5*t)-1519/38*sin(14/9-3*t)+3329/32*sin(t+47/10)+297/4*sin(2*t+14/9)+1939/38*sin(4*t+14/9)+239/9*sin(6*t+32/21)+34/9*sin(7*t+19/15)+107/6*sin(9*t+10/7)+271/10*sin(10*t+40/9)+693/13*sin(11*t+86/19)+160/7*sin(12*t+13/9)+289/16*sin(13*t+7/6)+385/48*sin(14*t+9/7)+44/9*sin(15*t+5/4)+41/11*sin(16*t+13/10)+12/13*sin(18*t+12/5)+46/9*sin(19*t+40/9)+10/9*sin(20*t+38/25)+46/31*sin(21*t+75/16)+37/16*sin(22*t+41/10)+35/11*sin(23*t+43/10)+10/13*sin(24*t+63/16)+2/3*sin(26*t+47/13)+19/7*sin(28*t+6/5)+13/10*sin(29*t+59/13)+3/2*sin(30*t+4/3)+11/10*sin(31*t+5/7)+17/13*sin(32*t+15/4)-11101/75).*theta(55*pi-t).*theta(t-51*pi)+(-3/10*sin(14/9-12*t)-29/12*sin(11/7-6*t)-38/9*sin(11/7-4*t)-59/8*sin(11/7-t)+183/7*sin(2*t+11/7)+125/13*sin(3*t+11/7)+31/16*sin(5*t+19/12)+4/9*sin(7*t+11/7)+3/13*sin(8*t+47/10)+64/63*sin(9*t+14/9)+3/13*sin(10*t+33/7)+1/2*sin(11*t+19/12)-11360/13).*theta(51*pi-t).*theta(t-47*pi)+(-60/11*sin(11/7-4*t)-528/31*sin(11/7-3*t)-661/55*sin(11/7-2*t)-623/3*sin(11/7-t)+39/8*sin(5*t+33/7)-5871/8).*theta(47*pi-t).*theta(t-43*pi)+(-43/13*sin(14/9-11*t)-45/8*sin(11/7-9*t)-41/15*sin(14/9-8*t)-57/11*sin(14/9-7*t)-157/6*sin(11/7-5*t)-1813/6*sin(11/7-t)+1997/15*sin(2*t+11/7)+89/6*sin(3*t+47/10)+19/6*sin(4*t+23/15)+191/8*sin(6*t+11/7)+191/17*sin(10*t+19/12)-7307/9).*theta(43*pi-t).*theta(t-39*pi)+(-15/8*sin(11/7-12*t)-72/73*sin(14/9-11*t)-19/9*sin(11/7-10*t)-35/11*sin(11/7-9*t)-7/11*sin(14/9-8*t)-60/11*sin(11/7-7*t)-191/13*sin(11/7-5*t)-184/5*sin(11/7-3*t)-109/10*sin(11/7-2*t)-609/2*sin(11/7-t)+1/6*sin(4*t+5/4)+11/5*sin(6*t+47/10)-6582/11).*theta(39*pi-t).*theta(t-35*pi)+(-11/15*sin(6/7-9*t)-47/13*sin(26/25-5*t)-67/27*sin(13/12-4*t)-633/8*sin(3/10-t)+251/7*sin(2*t+9/8)+123/8*sin(3*t+64/15)+23/8*sin(6*t+22/13)+26/9*sin(7*t+23/6)+14/9*sin(8*t+3/5)+19/12*sin(10*t+9/7)+25/19*sin(11*t+13/3)+11/17*sin(12*t+7/12)-5757/11).*theta(35*pi-t).*theta(t-31*pi)+(-50/3*sin(3/4-3*t)+263/10*sin(t+83/28)+669/13*sin(2*t+11/5)+17*sin(4*t+13/7)+67/11*sin(5*t+19/8)+11/3*sin(6*t+1/12)+38/17*sin(7*t+9/5)+51/14*sin(8*t+5/3)+49/25*sin(9*t+41/10)+17/12*sin(10*t+7/12)+53/54*sin(11*t+24/7)+5/7*sin(12*t+7/4)-10661/26).*theta(31*pi-t).*theta(t-27*pi)+(-127/10*sin(16/17-7*t)-119/9*sin(11/9-5*t)-1191/4*sin(1/3-t)+735/11*sin(2*t+2/9)+287/8*sin(3*t+61/16)+504/19*sin(4*t+17/9)+73/9*sin(6*t+9/5)+62/7*sin(8*t+14/5)+32/5*sin(9*t+1/6)+7/2*sin(10*t+19/7)+19/7*sin(11*t+1/44)+167/56*sin(12*t+51/14)-12878/17).*theta(27*pi-t).*theta(t-23*pi)+(-5/12*sin(14/15-32*t)-1/18*sin(17/13-31*t)-23/11*sin(1/6-19*t)-11/9*sin(38/25-18*t)-243/61*sin(25/17-8*t)-35/9*sin(11/21-7*t)-87/7*sin(4/5-6*t)-2249/15*sin(1/10-2*t)+1997/10*sin(t+23/12)+725/13*sin(3*t+1)+67/8*sin(4*t+9/4)+216/11*sin(5*t+23/5)+18/11*sin(9*t+32/31)+48/13*sin(10*t+19/8)+211/35*sin(11*t+16/5)+36/13*sin(12*t+64/15)+30/29*sin(13*t+8/13)+20/11*sin(14*t+28/13)+11/17*sin(15*t+37/16)+5/8*sin(16*t+23/14)+4/7*sin(17*t+14/9)+91/45*sin(20*t+14/27)+47/31*sin(21*t+8/5)+6/7*sin(22*t+29/15)+8/9*sin(23*t+53/20)+13/10*sin(24*t+89/30)+8/9*sin(25*t+39/10)+7/20*sin(26*t+97/24)+4/9*sin(27*t+18/13)+7/8*sin(28*t+45/14)+2/7*sin(29*t+42/13)+3/11*sin(30*t+22/5)+8/17*sin(33*t+4/11)+5/9*sin(34*t+18/13)+3/14*sin(35*t+12/5)-3384/11).*theta(23*pi-t).*theta(t-19*pi)+(-1/38*sin(2/11-7*t)-35/11*sin(9/14-t)+341/85*sin(2*t+25/14)+34/11*sin(3*t+22/21)+42/43*sin(4*t+223/56)+14/15*sin(5*t+3/4)+12/23*sin(6*t+7/2)+1/7*sin(8*t+4)+2/11*sin(9*t+9/8)+2/11*sin(10*t+73/29)+1/7*sin(11*t+1/4)+2/11*sin(12*t+74/25)+2961/20).*theta(19*pi-t).*theta(t-15*pi)+(-3/11*sin(13/25-12*t)-1/3*sin(15/29-10*t)-1/9*sin(4/3-8*t)-16/9*sin(12/13-4*t)+35/18*sin(t+89/19)+33/8*sin(2*t+49/16)+43/14*sin(3*t+33/13)+3/10*sin(5*t+26/11)+3/10*sin(6*t+4/11)+9/17*sin(7*t+94/27)+1/5*sin(9*t+35/11)+1/4*sin(11*t+20/7)+2917/15).*theta(15*pi-t).*theta(t-11*pi)+(949/15*sin(t+11/3)+63/11*sin(2*t+19/9)+26/7*sin(3*t+22/5)+7/8*sin(4*t+28/13)+3715/23).*theta(11*pi-t).*theta(t-7*pi)+(658/9*sin(t+107/27)+57/10*sin(2*t+9/5)+56/13*sin(3*t+38/9)+7/6*sin(4*t+10/11)+1681/16).*theta(7*pi-t).*theta(t-3*pi)+(-9/11*sin(13/10-16*t)-14/15*sin(2/7-15*t)-12/7*sin(3/8-12*t)-29/6*sin(5/11-8*t)-80/9*sin(5/14-4*t)+3076/7*sin(t+12/5)+343/18*sin(2*t+13/3)+230/17*sin(3*t+31/8)+21/4*sin(5*t+53/21)+23/10*sin(6*t+1/5)+27/7*sin(7*t+5/12)+60/17*sin(9*t+38/9)+11/8*sin(10*t+49/16)+10/7*sin(11*t+2/3)+4/7*sin(13*t+18/5)+17/12*sin(14*t+9/7)+598/9).*theta(3*pi-t).*theta(t+pi)).*theta(sqrt(sign(sin(t/2))));

plot(x,y,'.');
end

% function result=sign(in)
%
% if in<0
%     result=-1;
% else
%     result=1;
% end
%
% end

function result=theta(in)

result = (in>0);
end

Edit: use dot in the plot function to remove ugly lines


Q:

Send image through http in C

So, im making a webserver in C that display a sensor temperature and also a plot made with gnuplot in png format.
Im having problem sending the http template and the png image. I can send the http template with all the data but cant attach the image in the end.
static const char response_http_template[] = {
    "HTTP/1.1 200 OK \
Date: Mon, 27 Jul 2009 12:28:53 GMT \
Server: Apache/2.2.14 (Win32) \
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT \
Content-Length: %lu \
Content-Type: text/html \
Connection: Closed \
\n\n \
%s \
%s"
};

static const char response_page_template[] = {
    "<!DOCTYPE html> \
<html> \
<head> \
    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> \
    <meta charset=\"utf-8\" /> \
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> \

more html code with some %s
}

void send_response_data(uint32_t sock_client,
                        const char *student_name,
                        last_temp_t *last_temp)
{
    char write_buf[8192] = { 0 };
    char out_buf[8192] = { 0 };

    struct stat filestat;
    char filesize[7];
    int fd;
    char file_buf[1024] = {0};
    char result;
    FILE *fp;

    if ( ((fd = open ("./sup/data.png", O_RDONLY)) < -1) || (fstat(fd, &filestat) < 0) ) {
        printf ("Error in measuring the size of the file");
    }

    sprintf (filesize, "%zd", filestat.st_size);
    printf("File size %s\n", filesize);

    fp = fopen ("./sup/data.png", "r");
    if (fp == NULL)
    {
        perror("fopen error");
        exit(EXIT_FAILURE);
    }

    fread(file_buf, sizeof(char), filestat.st_size + 1, fp);
    fclose(fp);

    sprintf(
      write_buf, response_page_template, student_name, last_temp->timestamp, last_temp->temp);
    sprintf(out_buf, response_http_template, strlen(write_buf) + strlen(file_buf), write_buf, file_buf);
    write(sock_client, out_buf, strlen(out_buf));

}

When i start a client with chrome, i see the http code correct, but the image is not showed, only text like this: �PNG
Any ideas on how to send the binary data? Or if i need to change something in the http templates?
Thanks

A:

There are two possible paths here:

Check the request URL, and based on the URL either send the HTML page, or the image, OR
Combine both using data URL

For option #1, the 'main' server will have to check if the URL points to /image/ (or other folder that will represent the images).
For option #2, Data URL (google it, or look at: https://en.wikipedia.org/wiki/Data_URI_scheme
img src="data:image/png;base64,iVBORw0KGgoAAA
ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU
5ErkJggg==" alt="Red dot" />

You will need base64 encoder to convert the file from binary to text.


Q:

Stringify first level macro expansion C

Is it possible to stringify this C macro:
 #define GPIO_INT_PIN (GPIO_PORT_D|GPIO_PIN_IRQ_RISING|GPIO_PIN5)

using something like
 MY_STRINGFY(GPIO_INT_PIN)

to get
"(GPIO_PORT_D|GPIO_PIN_IRQ_RISING|GPIO_PIN5)" ?

A:

Yes it is possible. Read about stringizing in GCC cpp documentation.
 #define STRINGIFY(It) #It
 #define MY_STRINGIFY(It) STRINGIFY(It)

I corrected my answer thanks to Wojtek Surowka's one
then use MY_STRINGIFY(GPIO_PORT_D|GPIO_PIN_IRQ_RISING|GPIO_PIN5) which would work much better if you use an enum to define the constants, e.g.
enum Gpio_stuff_en {
     GPIO_PORT_D=5,
     GPIO_PIN_IRQ_RISING=17,
     GPIO_PIN5=23
};

Of course that won't work as you want if you need GPIO_PORT_D to be a macro, .e.g. because it expands to some non-constant-literal expression (like a variable, or an access to a field of some global structure, etc....)
As a counter-example:
#define FOO 1
#define BAR 2
#define STRINGIFY(s) #s
#define MY_STRINGIFY(s) STRINGIFY(s)

MY_STRINGIFY(FOO|BAR)

is expanded to "1|2"  not to "FOO|BAR", if your remove the two #define-s for FOO and for BAR and replace them with
enum {
  FOO=1,
  BAR=2 };

you really get the expansion "FOO|BAR" as you want. Check with gcc -C -E ...
Also:
enum {FOO=1, BAR=2};
#define FOOORBAR (FOO|BAR)
#define STRINGIFY(s) #s
#define MY_STRINGIFY(s) STRINGIFY(s)

MY_STRINGIFY(FOOORBAR)

is expanded as "(FOO|BAR)" . But if you use #define for FOO and for BAR you get the "(1|2)" expansion.
Maybe you could add in your own header, after including the external header defining GPIO_PORT_D etc... as a literal constants, something like :
enum {en_GPIO_PORT_D= GPIO_PORT_D,
      en_GPIO_PIN_IRQ_RISING= GPIO_PIN_IRQ_RISING,
      en_GPIO_PIN5= GPIO_PIN5};
#undef GPIO_PORT_D
#undef GPIO_PIN_IRQ_RISING
#undef GPIO_PIN5
#define GPIO_PORT_D en_GPIO_PORT_D
#define GPIO_PIN_IRQ_RISING en_GPIO_PIN_IRQ_RISING
#define GPIO_PIN5 en_GPIO_PIN5

and then you'll get more readable stringified constants (but not exactly what you dream of).


Q:

Is there a linspace() like method in Math.Net

Is there function in Math.Net like (MatLab/Octave/numpy)'s linspace() which takes 3 parameters (min, max, length) and creates an vector/array of evenly spaced values between min and max? It is not hard to implement but if there was a function already I would prefer to use that.

A:

There is none exactly like linspace, but the signal generator comes quite close and creates an array:
SignalGenerator.EquidistantInterval(x => x, min, max, len)

I'm not fresh on the VB.net syntax, but I guess it's very close to C#.
In case you need a vector:
new DenseVector(SignalGenerator.EquidistantInterval(x => x, min, max, len))

Or you could implement it e.g. using the static Create function (in practice you may want to precompute the step):
DenseVector.Create(len, i => min + i*(max-min)/(len - 1.0))

Update 2013-12-14:
Since v3.0.0-alpha7 this is covered by two new functions:

Generate.LinearSpaced(length, a, b) -> MATLAB linspace(a, b, length)
Generate.LinearRange(a, [step], b) -> MATLAB a:step:b


Q:

long.Parse and new IPAddress behavior while parsing hexadecimal value to IPAddress C#

I asked a question yesterday regarding converting HEX string to IP and got the answer here: C# convert hex into ip
The problem is, when I'm using the function
var ip = new IPAddress(long.Parse(ipString, NumberStyles.AllowHexSpecifier));

it does return a valid IPAddress but does it in a reverse way. For example:
Hex String:
c0a8000a

and it should be parsed to:
192.168.0.10

The long.Parse() function returns
3232235530

But my IP after calling the IPAddress constructor is
10.0.168.192

instead of the right one. Online tools, like http://www.smartconversion.com/unit_conversion/IP_Address_Converter.aspx are working fine. Is it a thing with a little or big endian? Do I have to flip the string myself or is there a simpler answer?

A:

So a little research yielded, that you guessed correctly. It has something to do with endianness.
The constructor: IPAddress(long newAddress) expects the value to be in network byte order which is defined to be big-endian.
I am assuming that your system architecture uses little-endian (as most intel systems do)
.NET uses the endianness of the underlying system, so when you parse a long on such a system it is stored little-endian.
Thats why when you parse the integers string via IPAddress.Parse, the result is correct.

As for a solution.
Eigther you parse your IPAddress as such (by string):
IPAddress ip = IPAddress.Parse(uint.Parse(ipString, NumberStyles.AllowHexSpecifier).ToString());

Or to be more 'correct' you could check for the BitConverter.IsLittleEndian field and flip the byte order if nescessery:
    static IPAddress ParseHexIPAddress(String szIPAddress) {
        uint uiIP = uint.Parse(szIPAddress, System.Globalization.NumberStyles.AllowHexSpecifier);
        IPAddress ip = null;
        if (BitConverter.IsLittleEndian) {
            uint uiIPRev = BitConverter.ToUInt32(BitConverter.GetBytes(uiIP).Reverse().ToArray(), 0);
            ip = new IPAddress(uiIPRev);
        } else {
            ip = new IPAddress(uiIP);
        }
        return ip;
    }


Q:

Limits with trigonometric functions, where denominator approaches zero

I got problem with my limit problem. I don't know what I should to do next. There are two numbers that I can't find. Please help me to do this.

$\displaystyle \lim_{x \to \pi/2} \frac{1-\cos 2x}{2\cos x}$
$\displaystyle \lim_{x \to 0} \frac{1 -2\cos x + \cos 2x}{x^2}$

A:

Presumably the idea is to use De L'Hôpital's Rule (see here - particularly Corollary 1).
I could help you further if you have trouble differentiating.
EDIT: Of course, $\cos \pi = -1$, so that the first limit does not exist (denominator diverges). My apologies.
EDIT 2: While I see others are making errors in the application of De L'Hôpital's Rule (HR from now), let me apply it to the second case:
We have that $1-2\cos 0 +\cos 2\cdot 0 = 1 -2 +1=0 = 0^2$, so that HR yields:
$$\lim_{x\to 0} \frac{1-2\cos x+\cos2x}{x^2} = \lim_{x\to0} \frac{2\sin x-2\sin2x}{2x}$$
We see that it is required to apply HR again, this time yielding:
$$\lim_{x\to0} \frac{2\sin x-2\sin2x}{2x} = \lim_{x\to0} \frac{2\cos x-4\cos 2x}{2}$$
This latter limit we can simply evaluate by continuity of the involved functions; it follows that the limit is $-1$. In summary, we conclude:
$$\lim_{x\to 0} \frac{1-2\cos x+\cos2x}{x^2} = -1$$


Q:

How to Get Unspent Transaction Outputs from Node

There is one API called listunspent, however it doesn't return any outputs, and some threads say that it may be because the address is not imported into the node's wallet.
Then how to retrieve the unspent outputs for any address?

A:

listunspent will list all unspent outputs of addresses the wallets controls, it will not work for any arbitrary address.
You can importaddress to add any address as a watch-only address, but this may take some time as your node will need to rescan the blockchain to find all associated transactions. Also note that when you use importaddress, you will not be able to spend any funds held at that address, since your wallet will not hold the private keys for it.


Q:

Angular JS - Enable and disable button

I have a condition and it is only on selecting a image among the optional images the next button needs to get enabled and also next should not get enabled on last outer select. The problem here is on selecting first image the button is getting enabled and the scope is assigning the value to false and it is not getting true for second iteration of images. Please let me know any idea for this issue.

<button type="button" class="btn btn-info" ng-disabled="outer_index == outers.length -1 || disableNext" ng-click="getNext()">Next</button>

In JS code,to activate the button only if,
$scope.disableNext=true;
    $scope.process = function() {
    $scope.disableNext=false;
 }

 $scope.getNext = function (){
     $scope.outer_index = $scope.outer_index + 1;
    $scope.datas = $scope.outers[$scope.outer_index];
 }

NOTE: I tried
ng-click="process();disableNext=false;" for this condition won't work within ng-repeat.

A:

just set the disableNext to true after selecting next and it works!!!
  $scope.getNext = function (){
          $scope.disableNext=true;
          $scope.outer_index = $scope.outer_index + 1;
          $scope.datas = $scope.outers[$scope.outer_index];
     }


Q:

Is it possible to configure an iOS device to remember credentials for a Wifi SSID but NOT auto-join it?

I want to:

leave Wifi enabled on the device
Make iOS remember the password for SSID A (e.g. Private corporate network)
Make iOS never connect to SSID A silently

This allows the following flow:

Manually connect to SSID A from the Wifi menu
Upon disconnecting from SSID A, require step 4 prior to re-connecting to SSID A

Example: By default, upon entering the range of SSID A, using the iOS device continues to use either built in cellular or SSID B. After step 4 above and until the end of the day, the device will be on the network.
For now the workarounds are:

Switch Wifi off when at work. Failure point: Forget to do it in the morning, leading to use of the network when not intending to. Further cons: consumes LTE bandwidth unnecessarily, and disables Wifi (which would disable e.g. tethering)
Forget SSID A in the menu. Dealbreaking pain point: have to use a clipboard manager or other insecure tools or brain power to restore the password for SSID A when actually required to connect.

A:

So it seems like my phone (i now have an iPhone X) now provides an 'Auto-Join' option for a wifi network.
So just switching this to off should in theory implement what I want (a saved network that will not get auto-joined).


Q:

help figuring out math formula for performance gains

I'm trying to write a report to recommend moving transaction logs to a separate physical drive but I need to provide some numbers. I have some queries from a profile that was done last month. I'm trying to determine the reduction % of the duration. I know that it can't be 100% exact but a very close numbert will suffice.
Query 1
Reads: 325229284
Writes: 85989
Duration: 840732
Query 2
Reads: 558955611
Writes: 87066
Duration: 1015697
Query 3
Reads: 422966141
Writes: 85087
Duration: 918225
currently reads and writes happen on the same drive. I want to move them so reads are one drive and writes are another. I tried to figure it out assuming writes are 20% slower than reads but didn't average in seek times. I was getting between 7%-15% but have no idea if those figures are correct. Assuming drive seek time is avg 1ms.

A:

Thoughts:

The read/write correlation is usually nothing to do with logs. It's sorting in tempdb, spools etc.
You'd need one extra volume per database LDF: otherwise you still have massive head movement and many databases write to one volume
If you aren't using a SAN, then to do this you'll have less disks per volumes.
What could be beneficial is moving tempdb to separate volumes. SQL Server 2005+ really spank tempdb compared to older versions (eg triggers use tempdb rather than the logs)
MDF/LDF split is often for recovery: you can back up the tail of the log if the data volume fails
If a query has 422,966,141 reads then fix your code and indexes. A separate log drive is re-arranging deck chairs on the titanic.


Q:

CDF for combination of discrete and continuous random variables

Let $X \sim \mathcal{N}(\bar{x}, \sigma_{x}^2)$, $W \sim \mathcal{N}(0, \sigma_{w}^2)$, and $A$ has Bernoulli distribution with parameter $p_1$.
How to calculate CDF $F(z)$ of random variable $Z=AX+W$? Can this be answered without use of Lebesgue integral?
This question is related to calculation of minimum mean square estimator (MMSE) of random variable $x$. For that calculation one needs to evaluate $E[x|z]$. Evaluating the conditional mean one must among other things evaluate $p(z)$.
$$E[x|z] = \int x p(x|z) dx =\int x \frac{p(z|x)p(x)}{p(z)} dx = \frac{1}{p(z)} \int x p(z|x)p(x)dx$$
(integral limits are assumed)

A:

Note: this calculation is to get the pdf, using convolution, rather than Fourier transform.
To save tedium in Latex, I simplifying symbols. $m=\bar{x}$, $v=\sigma^2$, $p=p_1$.
$f_Z(x)=\int_{-\infty}^\infty \frac{e^{-\frac{(x-u)^2}{2v_w}}}{\sqrt{2\pi v_w}}(p\frac{ e^{-\frac{(u-m)^2}{2v_x}}}{\sqrt{2\pi v_x}}+(1-p)\delta(u))du=pf_1(x)+(1-p)f_2(x)$
$f_2(x)=\frac{1}{\sqrt{2\pi v_w}}e^{-\frac{x^2}{2v_w}}$
Calculation of $f_1(x)$ is tedious, but straightforward.
$f_1(x)=\frac{1}{\sqrt{2\pi(v_x+v_w)}}e^{-h(x)}$  where $h(x)=\frac{1}{2v_xv_w}(\frac{(xv_x+mv_w)^2}{v_x+v_w}-v_wx^2-v_xm^2)=\frac{(x-m)^2}{2(v_x+v_w)}$


Q:

Which encryption method would produce this result

I am doing a security review on a system.
From one part of the system to another, information is sent using an encrypted string.
This string is over 400 characters long, but within it are 4 sets of 10 identical characters. I am assuming that the data that was encrypted also has this pattern, for example the word "parameters".
I have tested encrypting a string containing several identical strings with DES, but do not get the same pattern.
Question is: Is there an encryption method that would produce this result. Or have the parts been encrypted seperatly and conncatinated?

A:

An encryption system with short key length and no correlation between blocks (e.g. ECB mode) would encrypt short runs of identical plain text identically. It could also just be coincidence, of course.


Q:

Which dialect of C is Objective-C a "strict superset" of?

I frequently hear that Objective-C is a "strict superset" of the C programming language. There are several dialects/standards of C (ie. K&R, ANSI C, C90, C99, GNU extensions...); Objective-C was first developed in the early 1980s, so it has to predate these standards. However, Objective-C 2.0 is from around 2006 or 2007, so it could be based on a more modern C dialect. So, which "C" is Objective-C a superset of?

A:

There's a corresponding "dialect" of Objective-C for all the standard dialects of C.


Q:

How to return an entity-based result using RawSQL?

I have an older project where some of the code is in VB .NET.
Does anyone know the syntax for returning an entity-based result using VB .NET with RawSQL? I do this all the time in C#, but the syntax is different and I haven't been able to get it working.
This is the VB .NET code:
Dim Students As Entities.Students
Students = dbContext.Database.SqlQuery(Of Entities.Students)("select ....").FirstOrDefault()

A:

Found an answer.
Dim Students As Entities.Students
Students = dbContext.Database.SqlQuery(Of Entities.Students)("select ....").FirstOrDefault()

The C# for the above would be something like (I didn't compile, so it may not be exactly the right syntax):
EntitiesStudents Students;
Students = dbContext.Students.SqlQuery("select ....").FirstOrDefault();


Q:

How to reference only one attribute as a foreign key from a primary key composited of two attributes

CREATE TABLE Performances (
    DT Datetime NOT NULL,
    Name varchar(20) NOT NULL,
    Start_Time time NULL,
    Min_price integer NOT NULL,
    Max_price integer NOT NULL,
    Location Varchar (20) NOT NULL,
    PRIMARY KEY (DT, Name),

create Table [TYPE OF SHOWS] (
    Name Varchar (20) NOT NULL ,
    Type_of_show Varchar (20),
    PRIMARY KEY (Name),
    CONSTRAINT  fk_PerformanceName  FOREIGN KEY (Name)
    REFERENCES Performances (Name),
)

I'm unable to set the foreign key only to Name, how can I implemnt this?

A:

I suspect that you actually want the relation the other way around, with Performances referencing Type of Shows, like:
create Table [TYPE OF SHOWS] (
    Name Varchar (20) NOT NULL ,
    Type_of_show Varchar (20),
    PRIMARY KEY (Name)
);

CREATE TABLE Performances (
    DT Datetime NOT NULL,
    Name varchar(20) NOT NULL,
    Start_Time time NULL,
    Min_price integer NOT NULL,
    Max_price integer NOT NULL,
    Location Varchar (20) NOT NULL,
    PRIMARY KEY (DT, Name),
    CONSTRAINT  fk_PerformanceName FOREIGN KEY (Name) REFERENCES [TYPE OF SHOWS](Name)
);


Q:

Oracle SQL Order By with XML and Union ALL

I wrote a select statement like this:
Select
 xmlagg(xmlelement( "Species",
                  xmlelement("Type",Type),
                  xmlelement("Name",Name),
                  xmlforest(case when Tail is not null then Tail else null end "Trait")))
From Table_Animals
Order By Name;

This is my input

The query runs fine, but when I added an UNION ALL like so:
 Select
 xmlagg(xmlelement( "Species",
                  xmlelement("Type",Type),
                  xmlelement("Name",Name),
                  xmlforest(case when Tail is not null then Tail else null  end "Trait")))
 From Table_Animals

UNION ALL

 Select
 xmlagg(xmlelement( "Species",
                  xmlelement("Type",Type),
                  xmlelement("Name",Name),
                  xmlforest(case when Teeth is not null then Teeth else null end "Trait")))
 From Table_Animals
 Where Prey is not null
 Order By Name;

I got the error : ORA-00904: "Name": invalid identifier
How do I use Order By correctly in the above example?
My desired output is:
    <Species>
    <Type>Bird<Type>
    <Name>Eagle<Name>
    <Species>
    <Species>
    <Type>Mammal<Type>
    <Name>Fox<Name>
    <Trait>Sharp<Trait>
    <Species>
    <Species>
    <Type>Plant<Type>
    <Name>Lettuce<Name>
    <Species>
    <Species>
    <Type>Mammal<Type>
    <Name>Rabbit<Name>
    <Trait>Short<Trait>
    <Species>
    <Species>
    <Type>Mammal<Type>
    <Name>Rabbit<Name>
    <Trait>Dull<Trait>
    <Species>
    <Species>
    <Type>Amphibian<Type>
    <Name>Snake<Name>
    <Trait>Long<Trait>
    <Species>
    <Species>
    <Type>Amphibian<Type>
    <Name>Snake<Name>
    <Trait>Sharp<Trait>
    <Species>

Notice that Snake and Rabbit shows up twice in the output

A:

You can order the result of XMLAgg using the order_by_clause of XMLAgg.
In the first step perform a simple UNION ALL(without XML) to duplicate the data as required.
Finalyy use the  order_by_clause of XMLAgg
example data
create table Table_Animals as
select 'T1' type, 'dog' name, 'tai1' tail, 'Y' prey, 'tee1' teeth from dual union all
select 'T1' type, 'elephant' name, 'tai2' tail, 'Y' prey, 'tee2' teeth from dual union all
select 'T2' type, 'cat' name, 'tai3' tail, null prey, 'tee3' teeth from dual;

The query
with ua as (
select TYPE, NAME, TAIL, PREY, TEETH, Tail as trait from Table_Animals union all
select TYPE, NAME, TAIL, PREY, TEETH, Teeth  as trait from Table_Animals where Prey is not null)
Select
 xmlagg(xmlelement( "Animal",
                  xmlelement("Type",Type),
                  xmlelement("Name",Name),
                  xmlelement("Trait",Trait)) order by name) xml_col
From ua
;

*note the definition of the column trait in teh subquery.
note the order by name near the xml_col
gives
<Animal>
  <Type>T2
  </Type>
  <Name>cat
  </Name>
  <Trait>tai3
  </Trait>
</Animal>
<Animal>
  <Type>T1
  </Type>
  <Name>dog
  </Name>
  <Trait>tai1
  </Trait>
</Animal>
<Animal>
  <Type>T1
  </Type>
  <Name>dog
  </Name>
  <Trait>tee1
  </Trait>
</Animal>
<Animal>
  <Type>T1
  </Type>
  <Name>elephant
  </Name>
  <Trait>tai2
  </Trait>
</Animal>
<Animal>
  <Type>T1
  </Type>
  <Name>elephant
  </Name>
  <Trait>tee2
  </Trait>
</Animal>


Q:

mySQL count occurances of value on multiple fields. How?

I have a table with 5 fields. Each field can store a number from 1 - 59.
Similar to countif in Excel, how do I count the number of times a number from 1 - 59 shows up in all 5 fields?
Here's an example for the count of occurances for the number 1 in all five fields:
SELECT SUM(pick_1 = 1 OR pick_2 = 1 OR pick_3 = 1 OR pick_4 = 1 OR pick_5 = 1) AS total_count_1
FROM tbldraw

Hopefully I made sense.

A:

There was an answer here that had a solution.  I think this is just a variation.
Step1:  Create a numbers table (1 field, called id, 59 records (values 1 -59))
Step2:
SELECT numbers_table.number as number
  , COUNT(tbldraw.pk_record)
FROM numbers_table
LEFT JOIN tbldraw
 ON numbers_table.number = tbldraw.pick_1
   OR numbers_table.number = tbldraw.pick_2
   OR numbers_table.number = tbldraw.pick_3
   OR numbers_table.number = tbldraw.pick_4
   OR numbers_table.number = tbldraw.pick_5
GROUP BY number
ORDER BY number


Q:

How to list all row of sql?

Hy!
I want to list all row of my table, but it is not works :(
My function.php:
function getCharacterAdminJails($account_id) {
    global $connection;
    $stmt = $connection->pdo->prepare("SELECT * FROM adminjails WHERE jailed_accountID = :account_id");
    $stmt->bindParam(":account_id", $account_id);
    $stmt->execute();
    $adminjail_data = $stmt->fetch(PDO::FETCH_ASSOC);
    return $adminjail_data;
}

My example.php, where I list my rows:

            Admin neve:
            Indok:
            Perc:
            Időpont:

            <?=$adminjail_data["jailed_admin"];?>
            <?=$adminjail_data["jailed_reason"];?>
            <?=$adminjail_data["jailed_ido"];?>
            <?=$adminjail_data["jailed_idopont"];?>

How can I list all rows of my table?

A:

I would suggest you change this line of code in your php function from
$adminjail_data = $stmt->fetch(PDO::FETCH_ASSOC);

To this:
$adminjail_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

As fatchAll will return an array of all the results from your query and then in your html page do this:

        Admin neve:
        Indok:
        Perc:
        Időpont:

  <?php foreach($adminjail_data as $row) :?>

        <?=$row["jailed_admin"];?>
        <?=$row["jailed_reason"];?>
        <?=$row["jailed_ido"];?>
        <?=$row["jailed_idopont"];?>

  <?php endforeach; ?>

This is from PHP.net documentation about fetchAll:
PDOStatement::fetchAll — Returns an array containing all of the result set rows

You can refer to the full php documentation about PDOs fetchAll here: https://secure.php.net/manual/en/pdostatement.fetchall.php


Q:

getting the C python exec argument string or accessing the evaluation stack

In my python debugger I have a way of remapping a string to a filename so that when you are stepping through an exec'd function inside the debugger you can list lines pygmentized, or view them along inside an editor like Emacs via realgud.
So I'd like to be able to extract the string in an exec statement when CPython is stopped inside evaluating that.
I already have a mechanism that can look back in the call frame to see if the caller was an EXEC_STMT and I can look back one instruction to see if the previous instruction was say DUP_TOP. So I'd be home free if I could just figure out a way to read the stack entry at the time of the call and that gives the string evaluated. There is probably a way to drop into C to get this, but my knowledge of CPython internals lacking, and would prefer not to do this. If there's a package out there, maybe I could include that optionally.
CPython already provides access to function arguments, and local variables but of course since this is a built-in function this isn't recorded as a function parameter.
If there are other thoughts at how to do the same thing, that'd be okay too. I feel a less good solution would be to somehow try to overload or replace exec since debuggers can be brought in late in the game.
I understand that CPython2 and CPython3 may be a little bit different here, but to start off either would do.

A:

I think I've now found a way.
Inside the debugger I go up the call stack one level to get to the exec statement. Then I can use uncompyle6 to get a syntax tree of the source code. (A change may be needed in uncompyle6 to make this easier.)
The tree at the point of call will have something like exec_stmt -> expr .... That expression will have the text of the expression which is not necessarily the value of the expression. The expression could be a constant string value, but it could be something complex like "foo" + var1.
So then the debugger can evaluate that string in the context of the debugger which knows how to evaluate expressions up the call stack.
This still has a problem of the reevaluating the expression may have side effects. But that's bad programming practice, right? ;-)
So instead what I do is just decompile the code from the bytecode if the source isn't there. This has a disadvantage in that the line numbers mentioned in the bytecode don't always line up with those in the bytecode. For that the method of recreating the string above is better.
In closing, I hope to give some idea why writing a really good debugger is hard and why the vast number of debuggers have a number of limitations on even simple things like getting the source text at the point you are currently stopped.
A totally different approach would be to stop early and switch to an sub-interpreter like byterun (or some suitably modified Python C module) which would have access to a stack.


Q:

For any given function $f\colon [0,1]\to\Bbb R$, what is $\int_0^1\frac{f(x)}{f(x)+f(1-x)}dx$?

I have a general function assuming the following integral does exist
$$\int_0^1\frac{f(x)}{f(x)+f(1-x)}dx.$$
How do I solve it? I have tried to split it up from $0$ to $0.5$ and from $0.5$ to $1$, but I don't know what to do next.
Thanks for help.

A:

Hint. Set $\displaystyle I=\int_0^1\frac{f(x)}{f(x)+f(1-x)}dx$. By the change of variable $x \to1-x$ you get that
$$
I=\int_0^1\frac{f(1-x)}{f(x)+f(1-x)}dx.
$$
Then observe that
$$
I+I=\int_0^1\frac{f(x)}{f(x)+f(1-x)}dx+\int_0^1\frac{f(1-x)}{f(x)+f(1-x)}dx=\int_0^1\frac{f(x)+f(1-x)}{f(x)+f(1-x)}dx=1
$$ giving easily $$I=\frac12.$$


Q:

Bash-change directories in for loop

When you do a for loop, how do you change directories in the output?
Example:
for f in ./test/Sample1_out/*coords
do
    ./test/sort.pl --in1 "$f" --in2  "./test/Sample1_out/count.txt" --out "${f/.coords/.sorted}"
done

If I wanted to move up a directory to save the file in the "./test/" directory,  how would I do it?
If I wanted to have the loop iterate through all Sample folders, how could I do it?  (I tried for f in ./test/*out/*coords; do ./test/sort.pl --in1 "$f" --in2 "./test/*out/count.txt" --out "${f/.coords/.sorted} but my --in2 was emptied)

A:

To handle multiple directories, I would just add another loop:
for dir in ./test/*_out/; do
    for file in "$dir"/*.coords; do
        ./test/sort.pl --in1 "$file" --in2 "$dir/count.txt" \
                       --out "${file/.coords/.sorted}"
    done
done

Or you could use the glob on both levels at the same time, and use dirname or ${file%/*} to get the name of directory the current file is in:
for file in ./test/*_out/*.coords; do
    ./test/sort.pl --in1 "$file" --in2 "${file%/*}/count.txt" \
                   --out "${file/.coords/.sorted}"
done

(--in2 "./test/*out/count.txt" won't work, the wildcard isn't expanded in quotes, you get a path with a literal asterisk.)
As for the output file, I'm not exactly sure what it is you want, but if you want all the output files in some other directory, then something like this:
outfile=${file##*/}       # remove directory part of path (or use basename)
                          # stick new path in, and change extension
outfile=/path/to/output/${outfile/.coords/.sorted}
./test/sort.pl --in1 "$file" --in2  "$dir/count.txt" \
               --out "$outfile"

or if you want the "go up one directory", you could use "${file%/*/*}/${file##*/}" to transform /foo/bar/abc.txt to /foo/abc.txt.


Q:

Or statement in switch/case ?

Is it possible to use an OR statement in a switch/case structure? Suppose I want to do the same thing when clicking on two different items.
I tried
(case R.id.bOne || case R.id.tvOne):

and
case (R.id.bOne || R.id.tvOne):

But none of them seem to work..

A:

This will work:
case R.id.bOne:
case R.id.tvOne:
  // do your stuff

A:

Try this:
switch(id){
    case R.id.bOne:
    case R.id.tvOne:
        // do your stuff here
        break;
    case R.id.x:
        // do your stuff here
        break;
    default:
        // do your stuff here
}


Q:

Why do I get a segmentation fault when the code tries to find a key in a STL Map?

Given an array A[] of integers. The task is to display the ordered pairs of
positive integers (X, Y) such that X occurs in A[] at least Y times
and Y occurs in A at least X times
e.g.input A[] = { 1, 1, 2, 2, 3 } -- the program runs fine with this input.
Ordered pairs are -> { [1, 1], [1, 2], [2, 1], [2, 2] }
e.g. Input : A = { 3, 3, 2, 2, 2 } -- the program crashes with segmentation fault with this
Ordered pairs are -> { [3, 2], [2, 2], [2, 3] }
In function getDesiredSet(), at the below lines, the find fails with segmentation error.
it1 = freqMap.find(itr->first);
it2 = freqMap.find(itr->second);
# include "iostream"
# include "map"
# include "iterator"
# include "set"

using namespace std;
typedef pair<int, int> pairs;

map<int,int> getFreqMap(int arr[], int n){
map<int,int> freqMap;
map<int, int>::iterator it;
for (int i=0; i<n; i++){
    //if( freqMap.find(arr[i]) != freqMap.end()){
    if (freqMap.count(arr[i])){
        it = freqMap.find(arr[i]);
        it->second = freqMap.count(arr[i]) + 1;
        freqMap[arr[i]] = freqMap.count(arr[i]) +1;
    }
    else{
        freqMap.insert(pair<int,int> (arr[i], 1) );
    }
}
cout << "\nFrequency Map - Element : Freq\n";
for (it = freqMap.begin(); it!= freqMap.end(); it++){
    cout << it->first << " : " << it->second << endl;
}
return freqMap;
}

/* getPairSet finds out all the possible ordered pairs with the input numbers*/
/* and stores them in a set(so that there are no repeatation) */
set<pair<int,int> > getPairSet(int arr[], int n){
    set <pairs> s;//setOfPairs ;
    for (int i=0; i<n; i++){
        for (int j=0; j<n-1; j++){
            pairs p = make_pair(arr[i],arr[j]);
            s.insert(p);
        }
    }
    set< pairs >:: iterator itr;
    cout << "\nPossible Pairs out of the given numbers in the array:\n";
    for (itr = s.begin(); itr != s.end(); itr++){
        cout <<"(" <<(*itr).first << "," << (*itr).second <<") " ;
    }
    return s;
}

/* getDesiredSet removes those order pairs which do match the criteria*/
/* in other words, it removes those order pairs in which */
/* either the frequency of 1st item is less than 2nd item */
/* or frequency of 2nd item is less than 1st item */
set<pairs > getDesiredSet(set<pairs > pairSet, map<int, int> freqMap){
    set<pairs > ::iterator itr, itrEnd;
    map<int, int>:: iterator it1, it2;
    for (itr = pairSet.begin(); itr != pairSet.end(); itr++){
        it1 = freqMap.find(itr->first);
        it2 = freqMap.find(itr->second);
        if ((it1->second < itr->second) || (it2->second < itr->first)){
            itrEnd = itr;
            std::advance(itrEnd , 1);
            pairSet.erase(itr, itrEnd);
        }
    }
    return pairSet;
}

int main(){
map<int, int> freqMap;
int arr[] = { 3, 3, 2, 2, 2 };
cout << "\nInput Array Elements:\n";
int n = sizeof(arr)/sizeof(arr[0]);
for (int z=0; z< n; z++)
    cout << arr[z] << " ";
freqMap = getFreqMap(arr, n);
set<pair<int,int> > pairSet = getPairSet(arr,n);
set<pair<int,int> > desiredSet = getDesiredSet(pairSet, freqMap);
set<pair<int,int> > :: iterator itr;
cout << "\n\nDesired order pairs\n";
for (itr = desiredSet.begin(); itr != desiredSet.end(); itr++){
    cout <<"(" <<(*itr).first << "," << (*itr).second <<") " ;
}
return 0;
}

A:

after the erase the iterator is invalid but you use it next loop turn, here :
for (itr = pairSet.begin(); itr != pairSet.end(); itr++){
    it1 = freqMap.find(itr->first);
    it2 = freqMap.find(itr->second);
    if ((it1->second < itr->second) || (it2->second < itr->first)){
        itrEnd = itr;
        std::advance(itrEnd , 1);
        pairSet.erase(itr, itrEnd); << itr is invalid now
    }
}

To detect invalid memory accesses or memory leap valgrind is a very practical free tool, if you can use it.


Q:

Can an internal class have public functions and variables in Swift/Xcode 9?

It might sound a trivial question but I am newbie in Swift, I was wondering whether an internal class can have public methods and variables that I would like to use from that class.
Let's say something like this( as example)
internal class myService: InheritService {

public var x : Int32 = 0

public func sum (_ a: Int32, _b: Int32) -> Int32 {

 return (a + b)

}}

Can I sue then function sum and variable x from outside?
Thanks in advance

A:

No it can't. Any access modifiers of properties or methods contained in a first class citizen such as a class, struct, protocol or enum will always be overwritten by that of the containing definition.
Think about it this way, if you can't see a dog, how can you check how many legs it has?
struct Dog {
    public var legCount: Int = 3
}


Q:

XML to custom Class

So, I'm retrieving data from one vShield Manager via the API and building a database to syncronize with another...  I'm successfully retreiving XML from the API (yay) and I can parse it just fine, but it's a bit tedious.  I'm trying to create custom classes for the various objects in the vShield (virtual firewalls, global address objects, service definitions, etc.) so I can reference the data in my script in a sane manner, and this is where I'm running into a problem (sort of)...
I get xml back that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<scopingObjects>
  <object>
    <objectId>datacenter-2</objectId>
    <type>
      <typeName>Datacenter</typeName>
    </type>
    <name>virtualDataCenter-01</name>
    <revision>5</revision>
    <objectTypeName>Datacenter</objectTypeName>
    <scope>
      <id>group-d1</id>
      <objectTypeName>Folder</objectTypeName>
      <name>Datacenters</name>
    </scope>
    <extendedAttributes/>
  </object>
  <object>
    <objectId>globalroot-0</objectId>
    <type>
      <typeName>GlobalRoot</typeName>
    </type>
    <name>Global</name>
    <revision>460</revision>
    <objectTypeName>GlobalRoot</objectTypeName>
    <extendedAttributes/>
  </object>
</scopingObjects>

And I itterate through that using ElementTree:
# Get the list of scoping objects
scopeObjects = [] # Declare an empty list
r = sendRest("getScopes")
xml = et.fromstring( r.text )
for object in xml.iter("object"):
    try:
        o = scope()
        o.create(et.tostring(object))
        scopeObjects.append(o)
    except Exception, e:
        print "Exception: " + repr(e)

Where I use the following class definition:
class scope:
    def __init__(self):
        self.id = ""
        self.name = ""
        self.type = ""
    def create(self, xmlString):
        try:
            xml = et.fromstring(xmlString)
            if xml.find("objectId") is not None: self.id = xml.find("objectId").text
            if xml.find("name") is not None: self.name = xml.find("name").text
            if xml.find("type/typeName") is not None: self.type = xml.find("type/typeName").text
        except:
            print "Error constructing scope object from:\n%s" % xmlString
            return False

Which all works a treat... until I come across the more complicated XML structures... then it's an orgy of "if xml.find("blah/blah/blah") is not None: variable = xml.find("blah/blah/blah").text" over and over again...
I'd like to do something like:
class scope:
  def __init__(self):
    self.id = ""
    self.name = ""
    self.type = ""
  def create(self, xmlString):
    xmlPaths = { "id" : "objectId", "name" : "name", "type" : "type/typeName" }
    for key in xmlPaths.keys():
      element = xml.find(xmlPaths[key])
      if element is not None:
        # Set the class property named by "key" to the value of element.text
        locals()[key] = element.text
        # For example, if the key is "id", then it sets "self.id" to the text of the element in XML tag "<objectId>"

Basically, I want to be lazy when it comes to constructing the objects... I don't want to have to type loads of "if xml....".  It will become much more important when I start dealing with the more complicated objects returned by the API, with scores of elements to deal with.
My basic question: what's the best way to do this?
Cheers!
My Solution:
Many thanks to Larsks for the answer.  Cheers mate!
class scope:
    xmlPathMap = {
        "id" : "objectId",
        "name" : "name",
        "type" : "type/typeName"
    }
    def __init__(self, element):
        self.element = element
        self.create()
    def create(self):
        try:
            for key, path in self.xmlPathMap.items():
                res = self.element.find(path)
                if res is not None:
                    setattr(self, key, res.text)
        except:
            print "Error constructing scope object:\n\tkey: %s\n\tpath: %s\n\tvalue: %s" % (key, path, res.text)
            return False
# End of scope class definition

A:

What about something like this?  This is basically what you're doing in your "I'd like to do something like..." example.  Attributes on scope objects default to None, and then get set using the attribute/xpath dictionary xmlPaths.  There's some stuff going on in your code that I'm not sure about (for example, I'm not sure what you're doing with locals() there), but I think this is doing what you want.
from lxml import etree

class scope(object):
    xmlPaths = {'id': 'objectId',
                'name': 'name',
                'type': 'type/typeName'}

    def __init__(self, element):
        self.id = None
        self.name = None
        self.type = None
        self.element = element

        self.parse()

    def parse(self):
        for attr, path in self.xmlPaths.items():
            res = self.element.xpath(path)
            if res:
                setattr(self, attr, res[0].text)

    def __repr__(self):
        return '<scope id=%s name=%s type=%s>' % (
            self.id, self.name, self.type)

  with open('data.xml') as fd:
      doc = etree.parse(fd)

  scopeObjects = []
  for object in doc.iter('object'):
      o = scope(object)
      scopeObjects.append(o)

  print scopeObjects


Q:

Can I set a char or DateTime to null?

Can I set null into char data type? and also DateTime in C#? thanks guys!

A:

It is impossible, it is a value type. Use
char? myChar = null;
DateTime? myDate = null;

which is equivalent to
Nullable<char> myChar = null;
Nullable<DateTime> myDate = null;


Q:

list is not sorting correctly

i'm trying to set a list by desc order, setting the highest to the front of the list, but it is not doing it, here is the struct i am using
struct  datalist
{
    short   index;
    int nNumber;

    bool operator > (const datalist& a) const
    {
        return (nNumber > a.nNumber);
    }
};

and i am doing
datalist* pAR = new datalist;
pAR->index = 1000;
pAR->nNumber = 10;
m_SomeList.push_back(pAR);

pAR = new datalist;
pAR->index = 1005;
pAR->nNumber = 30;
m_SomeList.push_back(pAR);

pAR = new datalist;
pAR->index = 0;
pAR->nNumber = 20;
m_SomeList.push_back(pAR);

m_SomeList.sort(greater<datalist*>());

after the sort, it is outputting 20, 30, 10, i am using VS 6.0, and before i get comments of i need to upgrade, i know that is an old compiler but in my case i need it, so please keep that in mind when answering, the best descriptive, helpful answer gets the vote.

A:

You are sorting a container of pointers, so the container uses std::greater on the pointers so they are sorted by address in non-descending order.
You want to do something like this:
struct Comp {
    bool operator()(const datalist* a, const datalist* b) {
        return *a > *b;
    }
};

m_SomeList.sort(Comp());

or
m_SomeList.sort([](const datalist* a, const datalist* b) {
    return *a > *b;
}); // for C++11

Also as chris mentioned, you might want to be storing these objects by value instead of by pointers so you don't have to clean them up.


Q:

How to Capture a Heap Dump from a Running JVM

I have an Elasticsearch cluster running on ec2 amazon server. As described in this article the way to capture a heap dump from a running JVM is to use jmap:
sudo jmap -dump:format=b,file=heap.hprof {processID}

error:
  {processID}: well-known file is not secure

Jmap requires the user that run the process so I have to execute the command like:
sudo -u elasticsearch jmap -dump:format=b,file=heap.hprof {processID}

error:
Dumping heap to /home/ubuntu/heap.hprof ...
Permission denied

So I guess I have to use jmap like this:
sudo -u elasticsearch sh -c "sudo jmap -dump:format=b,file=heap.hprof {processID}"

[sudo] password for elasticsearch:

What is the elasticsearch user password? Is there some default value? I didn't find any solution to this...

A:

You need to make the directory you will write to, writable as the user which will do the writing, or you can use a directory every user can write to e.g.
sudo -u elasticsearch jmap -dump:format=b,file=/tmp/es-heap.hprof {processID}


Q:

Finding a Liapunov function for a two dimensional system.

I need to find a Liapunov function to determine the stability of a point. Given the system $$\frac{du}{dt} = v, \ \frac{dv}{dt} = -u - u^4$$
Find a suitable Liapunov function to determine the stability of the point $(0,0)$.
Orginally, I was thinking of a Liapunov function $$V = au^2 + buv + cv^2.\ a,b,c \in \mathbb{R}$$
However, filling this in gives $$\dot{V} = V_u \frac{du}{dt} + V_v \frac{dv}{dt}$$
$$\dot{V} = (2au + bv)\cdot v + (bu + 2cv)\cdot(-u - u^4)$$
$$\dot{V} = a\cdot(2uv) + b \cdot (v^2-u^2-u^5)+c\cdot(-2uv-2uv^4)$$
And I cannot find any constant $a,b,c$ such that either $\dot{V} \leq 0$, $\dot{V} < 0$, $\dot{V} > 0$ holds, but I am unable to.
Can anyone help me out? Thanks in advance!

A:

Your equation is a particular case of an Hamiltonian system so for example the Hamiltonian:
$$H(u,v)=v^2+\frac{1}{2} u^2+\frac{1}{5} u^5$$
is such that:
$$ \frac{d }{dt}H(u(t),v(t)) =0$$.


Q:

Append multiple arrays to a hash in ruby

I'm trying to create an array of members who have registered for an event, but rather than creating an a array of multiple hashes, the code only stores the last member to be registered into the hash. I can't seem to figure out why.
total = 0
def registration
  members = []
  event = {}
  puts "First Name: ";            members << gets.chomp
  puts "Last Name: ";             members << gets.chomp
  puts "Date of Birth: ";         members << gets.chomp
  puts "Number of Events(1-4): "; members << gets.chomp.to_i
  total = '%.2f' % [(members[3] * 35.00)]
  puts "TOTAL DUE:  $#{total}"
  event = {
    :first_name => members[0],
    :last_name => members[1],
    :dob => members[2],
    :events => members[3],
    :paid => total
  }
  puts "Would you like to register another student?"
  answer = gets.chomp.downcase
  if answer == "yes"
    registration
  elsif answer == "no"
    puts "Thank you for registering.  We look forward to seeing you at the event."
    p event
  else
    puts "Please enter 'yes' or 'no'."
  end
end
registration

A:

This right here:
event = {:first_name => members[0],
         :last_name => members[1],
         :dob => members[2],
         :events => members[3],
         :paid => total}

is going to re-assign the hash each time you iterate.
What you want to do is add a new key / value pair to the hash instead. It's up to you to determine the key you want to use (possibly members full name?):
event[:member_name] => {...}


Q:

It's possible change a settings.settings file without recompiling in .NET?

SCENARIO:
A junior development team deployed a WCF service in production that is using a reference to a project (in the same solution) that is compiled as DLL. This DLL has an application settings file with the following configuration:

And the code of the settings file is:
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="DLL-NAME.Properties" GeneratedClassName="Settings">
  <Profiles />
  <Settings>
    <Setting Name="URL-TO-CHANGE" Type="(Web Service URL)" Scope="Application">
      <Value Profile="(Default)">VALUE-WE-NEED-TO-CHANGE</Value>
    </Setting>
  </Settings>
</SettingsFile>

QUESTION:
Is there any way to change the value (in the example, VALUE-WE-NEED-TO-CHANGE) without recompiling?
We tried making a DLL-NAME.dll.config file but it doesn't work. Also we can't use svcconfigtool because the config file is attached to the DLL, not the WCF. Related search is hard because we only found answers like "is not possible, answer is for an exe/wcf/web project, etc."
We are out of options, indeed change the hexa from the compiled file is not an option because this means a redeploy.
Thanks in advance.

A:

No, is not posible, the best approach to make this is setting your configuration inside a Database so you won't recompile if you need change the file, or you can create your own read file method.


Q:

Python - Does the string contain a specific string within brackets?

I am trying to find out if a string contains [city.----] and where the ---- is, any city could be in there. I just want to make sure it's formatted correctly. I've been searching for how I can ask Python to ignore that ---- but with no luck. Here is an example on how I would like to use this in the code:
if "[city.----]" in mystring:
    print 'success'

A:

You can use str.startswith() and str.endswith():
if mystring.startswith('[city.') and mystring.endswith(']'):
    print 'success'

Alternatively, you can use python's slice notation:
if mystring[:6] == '[city.' and mystring[-1:] == ']':
    print 'success'

Lastly, you can use regular expressions:
import re
if re.search(r'^\[city\..*?\]$', mystring) is not None:
    print 'success'


Q:

mozilla extension for transliteration of devanagri to gujarti

i have created an extension for mozilla firefox button,which will transliterate a particular webpage.
the button code is pasted in %appdata% of mozilla.the code for button.js is as follows
function doSomething()
{
    let url = "http://localhost/aaa/trial.asp";
  let request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest);
   request.onload = function(aEvent) {

    doc=gBrowser.contentDocument;
    doc.body.innerHTML = "
" + gBrowser.contentDocument.body.innerHTML  + "
";
    doc.body.innerHTML = "
" + aEvent.target.responseText + "
"   + gBrowser.contentDocument.body.innerHTML;
    doc.body.innerHTML = gBrowser.contentDocument.body.innerHTML + "
click here  to see the original page
" ;
    doc.getElementById("in_trans_overlay").style.left="0px";
    doc.getElementById("in_trans_overlay").style.top="0px";
    doc.getElementById("in_trans_overlay").style.position="fixed";
    doc.getElementById("in_trans_overlay").style.backgroundColor="blue";
    //doc.getElementById("in_trans_overlay").style.opacity="0.4";
    doc.getElementById("in_trans_overlay").style.width="100%";
    doc.getElementById("in_trans_overlay").style.zIndex="10";
    doc.getElementById("in_trans_lnk").style.color="white";
    //doc.getElementById("in_trans_lnk").style.opacity="1.0";

    doc.body.childNodes[1].style.display="none";

    hd=doc.getElementsByTagName("head");
    scpt=doc.createElement("script");
    scpt.setAttribute("type", "text/javascript");
    scpt.setAttribute("charset", "UTF-8");
    scpt.setAttribute("src", "http://localhost/aaa/hide.js");
    hd[0].appendChild(scpt);
   };
   request.onerror = function(aEvent) {
        window.alert("Error Status: " + aEvent.target.status );
   };

   request.open("POST", url, true);
   request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   params = gBrowser.contentDocument.body.innerHTML;

   params = "inTransContent=" + encodeURIComponent(params);
   request.setRequestHeader("Content-length", params.length);
   request.setRequestHeader("Connection", "close");

   request.send(params);

}

this code sends an xmlhttprequest and it will execute trial.asp code.
trial.asp contains the following code
<% Dim xmlDoc
Dim objNodeList
    Dim count

    set xmlDoc = Server.CreateObject("Msxml2.DOMDocument.6.0")

    xmlDoc.validateOnParse = False
    xmlDoc.async = False

    xmlDoc.loadXML("
" & Request.Form("inTransContent")   & "
")

    If (xmlDoc.parseError.errorCode <> 0) Then
        Dim myErr
        Set myErr = xmlDoc.parseError
        Response.Write("

" & myErr.reason & "
" & myErr.line & "
" & myErr.srcText & "
")
    Else
          Set objNodeList = xmlDoc.documentElement.selectNodes("//text()")
          count = objNodeList.length

          For i = 1 To count
               objNodeList(i-1).insertData 0, "XYZ "
               objNodeList(i-1).insertData objNodeList(i-1).length, " XYZ"
          Next

          Response.Write(xmlDoc.documentElement.xml)
   End If

%>

this code will send only the text nodes which are to be transliterated,since i havent progressed much in the for loop so i have replaced it with dummy..which appends xyz before and at the end. i need to convert this asp code because i am going to asp.net. i need to convert this to vb.net or c# code..i will come back to the for loop later..this code should become the default.aspx file in asp.net.
the next thing which is asp.net is that i need a global.asax file
the global.asax file contains this code
    protected void Application_Start(object sender, EventArgs e)
    {
        sbyte[,] a = new sbyte[100, 100];
        sbyte[,] b = new sbyte[100, 100];
        int count = 0;
        XDocument docA = XDocument.Load("dev.xml");
        XDocument docB = XDocument.Load("guj.xml");
         var devanagriKeys = (from d in docA.Descendants("mapping")
                                              select new {
                                                  Key = d.Descendants("itrans").FirstOrDefault().Value,
                                                  Character = d.Descendants("character").FirstOrDefault().Value
                                              }).ToArray();
        var gujrathiKeys = (from g in docB.Descendants("mapping")
                                              select new {
                                                  Key = g.Descendants("itrans").FirstOrDefault().Value,
                                                  Character = g.Descendants("character").FirstOrDefault().Value
                                              }).ToArray();
        var crossReference = (from d in devanagriKeys
                              join g in gujrathiKeys on d.Key equals g.Key
                              select new {
                                    d.Key,
                                    Devanagri = d.Character,
                                    Gujrathi = g.Character
                                }).ToList();

this code will take characters from devanagri script and gujrathi script and create a list using itrans as one medium for eg अ in itrans is a while અ in gujarati has same itrans a
so a list will be created storing अ and અ because they are having same itrans.
here i need to store this list thing in a session var so that i can use it in the default.asp..
i cant figure that one out properly though.
i had told that i will come back to the for loop of default.aspx, so now in this default.aspx i have to search and replace every text node of devanagri to gujarati and vice versa..
i am also confused because i am using a iis server so i am i supposed to copy all the project files of asp.net in the wwwroot folder of inetpub of iis.
i will be thankful if anyone guides me to this!! i am sorry for lots of code..i am stuck badly so i really needed help, if any queries regarding this please feel free to post thanks!!!

A:

It sounds like you want to share items in session variables between your ASP page and your .NET .ASPX page. Did I understand that correctly?
Consider this article: How to Share Session State Between Classic ASP and ASP.NET
You'd probably be better off converting your .asp to a .NET .aspx. Consider the maintainability of your solution.


Q:

ASP.NET - Does streaming file to the client occupy server memory?

I have a requirement to make the files in a file server available for download through an application running on a web server. Users would be clicking on the links available on the application page and a save as dialog would appear. This kind of a use case is pretty common and I might be talking about a basic thing, but I would appreciate if someone can confirm if my following assumptions are correct.
1) With files on file server, virtually mapped via a virtual directory in the web server to be accessible to the application (as links), it is possible to stream it directly to the client using content-disposition (with code similar to the answer here), meaning without involving any code to process or chunk the file for the purpose of streaming it.
2) Since the file is directly streamed from the file server, the web server is in NO WAY impacted in terms of memory or disk usage (CPU would be used of course).
Thanks

A:

Since you want to write files directly and keep you memory footprint to a minimum, consider using HttpResponse.TransmitFile

Writes the specified file directly to an HTTP response output stream,
  without buffering it in memory.

This to my knowledge is the most efficient method to send a file in the response if you have to write it through asp.net.
Response.AppendHeader("Content-Disposition", "attachment; filename="+ fileName );
Response.TransmitFile(fullPath);
Response.Flush();
Response.End();


Q:

Javascript - Changing an image with variables

I'm trying to create a slide show but I'm having some difficulty. I've googled the problem and read loads of pages but I still can't get it to work. I'm doing this all in my header, then the header.php will be included on whichever page. I've tried setting the source to a string containing the location, creating an image before and then setting it to that image's source, and just trying odd things trying to get it to work.
The strange thing is when I call the updateSlider() function, the source of my image is null even though I can see it on the screen, and afterwards when I set it, it says there is a source but the image is the same.
But at the moment I'm just trying to change the image when I click a button and then I'm going to try and make the slide show. Here is the header.php code, you can see some of the different things I've tried in it:
<!DOCTYPE html>

        <button type="button" onclick="updateSlider()">Update Slider</button>

            Home
            About
            Gallery
            Programs

Thank you in advance for any help!
==================================================================================
UPDATED CODE:
<!DOCTYPE html>

        <button type="button" onclick="updateSlider()">Update Slider</button>

A:

Simple. You're trying to give an anchor a image attribute. Give your img an id and fix it in the Javascript. For example, if you give it an "currentSlideImage" id:
$('#currentSlideImage').attr('src', url2);

BTW, I'd suggest you take a read on Unobstrusive Javascript.


Q:

Trouble accessing dictionary item in Swift 2.0

I'm experienced in Obj-C, but fairly new to Swift. I have a simple function that takes a Set and a Dictionary as parameters:
func buildSource(dataToParse:Set<String>, lookupData:Dictionary<String,AnyObject>) {
    for item in dataToParse {
        for dict in lookupData {
            let nameID = dict["name"] // compile error
        }
    }
}

The passed in parameter lookupData is a dictionary containing nested dictionaries. I know that each of these dictionaries contains a key called name but when I try to access that key using the following syntax:
let nameID = dict["name"]

I get the following comile error:
Type '(String, AnyObject)' has no subscript members

If I know that a key exists, how do I access it? Thanks!

A:

import Foundation

func buildSource(dataToParse:Set<String>, lookupData:Dictionary<String,AnyObject>)->[AnyObject] {
    var ret: Array<AnyObject> = []
    for item in dataToParse {
        for (key, value) in lookupData {
            if key == item {
                ret.append(value)
            }
        }
    }
    return ret
}

let set = Set(["alfa","beta","gama"])
var data: Dictionary<String,AnyObject> = [:]
data["alfa"] = NSNumber(integer: 1)
data["beta"] = NSDate()
data["theta"] = NSString(string: "some string")

let find = buildSource(set, lookupData: data)
dump(find)

/* prints
▿ 2 elements
- [0]: 28 Nov 2015 18:02
▿ [1]: 1 #0
▿ NSNumber: 1
▿ NSValue: 1
- NSObject: 1
*/

in your code
for dict in lookupData {
    let nameID = dict["name"] // compile error
}

dict is not a dictionary, but (key, value) tuple!


Q:

CSS id and classes

I have an id right now which I call on different pages, but never on the same page so it works. Would the best practice be to make it a class because its being called on different pages, but not more than once on the different page.
For example, say I have my home page. I call the id test once there. then maybe on my about page I call the id test there again. I will never need to call the id test more than once on a page. Should I use an id or class?

A:

Syntactically, there is nothing wrong with using ID so long as you only use that ID once per page.  For CSS, that is the purpose of an ID.  However, I don't know if there's any point unless you intend to also use that ID in JavaScript.
If you instead use a class, it will provide more flexibility down the road if you end up using the "test" ID more than once per page.  I know you don't intend to now, but you might later.