Modular equations admitting a solution

Question: In a finite Field $\mathbb{F}_q$ with $q = p^n$ and $p$ a prime numbers I am interested in the modular equation
$$
x^2+3 \equiv 0 \pmod p.
$$
More precisely I would like to ask whether there is a closed formula for the pairs $(p,n)$ such that the above equation has a solution in $\mathbb{F}_{p^n}$.
Comment: There is a root of $x^2+3=0$ in $\mathbb F_{p^n}$ iff $n$ is even, or if $-3$ is a square modulo $p.$ $-3$ is a square modulo $p$ iff $p\equiv 1\pmod 6$ or $p=2,3.$
Comment: You don't need modular notation in $\mathbb F_q.$ The modular notation is built in.
Answer: If there is a root in $\mathbb F_p,$ there is a root in $\mathbb F_{p^n}.$ There is a root in $\mathbb F_p$ iff $-3$ is a square modulo $p,$ which, via a quadratic reciprocity calculation, would mean if $p=2,3$ or $p\equiv 1\pmod 6.$
If $n$ is even, then $\mathbb F_{p^n}$ contains $\mathbb F_{p^2}.$ But $\mathbb F_{p^2}\cong\mathbb F_p[x]/\langle x^2+3\rangle$ if $-3$ is not a square modulo $p,$ so $\mathbb F_{p^2}$ has a root of the polynomial.
You need to finally deal with the case $p\equiv 5\pmod 6$ and $n$ odd to show that in that case, $-3$ is not a square in $\mathbb F_{p^n}.$
If $p^n\equiv 5\pmod 6,$ and $u\in \mathbb F_q$ is a root of $x^2+3,$ then we must have $$1 =u^{q-1}=(-3)^{(p^n-1)/2}=\left((-3)^{(p-1)/2}\right)^{1+p+\cdots +p^{n-1}}.$$
But since $-3$ is not a square modulo $p,$ $(-3)^{(p-1)/2}=-1$ and since $p$ is odd and $n$ is odd, then $1+p+\cdots p^{n-1}$ is odd, so:
$$u^{p^n-1}=-1$$
So no such $u$ can exist.
Comment: I got it, you used it to conclude that $(-3)^{\frac{p-1}{2}} = -1$.
Comment: In the last part where did you use the fact that $p\equiv 5$ $\mod 6$? Just to say that $p$ is odd?

Modular equations admitting a solution


Get value from ref - Indicates constantly Can not read property 'value' of undefined

Question: That's how I try to get in the ref area. But when I try to write content into the input then when I have to show it in console.log it just indicates that my mailRef is

Can not read property 'value' of undefined

import React from 'react';

class Signup extends React.Component {
    mailRef = React.createRef();

handleSubmit = (event) => {
    event.preventDefault();
    console.log('heyyyyyyyyyyyyyyy');
    console.log('Submit: ' + this.mailRef.value.value);
}
..

html:
<input type="text" name="email" ref={this.mailRef} className="form-control" placeholder="Email" />

If I just have to write "heyyyyyyyyy" into console.log I'll get it out but as soon as I get the content I've written, it will not grab it.
Answer: You should put the declaration in the constructor like this:
import React from 'react';

class Signup extends React.Component {
   constructor(props){
      super(props);
      this.mailRef = React.createRef();  //fixed
   }

   handleSubmit = (event) => {
      event.preventDefault();
      console.log('heyyyyyyyyyyyyyyy');
      console.log('Submit: ' + this.mailRef.current.value); //fixed
   }

For more information: Uncontrolled Components
Comment: I read myself to do just that. then it was resolved. `this.mailRef.current.value`


Gap between top and bottom divs - how to get rid of it?

Question: How do I get my "TextDiv" to sit right below the "TopDiv"? There's a weird gap between the two divs, is there a CSS reason why it's like that? Thank you
[sorry, had to had to add this extra comment or my thread wouldn't post.]
Comment: You can wrap your `TopRightDiv` and `TopDiv` into one div having `display:flex;`. It would make its child of equal heights.
Comment: Adding display: flex was a little confusing, but I eventually fixed the code, Thanks for your help!
Answer: You have three separate divs all floating left. The third one is pushed down by the height of the second one.
Try putting the first and third in a div together, and floating a second one next to that.

Comment: Finally got it to work using your code, thank you! Containing the top and third divs together worked. I also needed to surround the TopDiv with a div element. Thanks for your help, much appreciated!!
Answer: Try the following css
.OuterBorder {
    border: 1px solid black;
    width: 120px;
    height: 140px;
    float: left;
}
.TopDiv {
    width: 80px;
    height:80px;
    border: 1px solid black;
    float: left;
}
#TextDiv {
    border: 1px solid black;
    width: 80px;
  position: absolute;
  top: 90px;
}
.TopRightDiv {
    float: left;
}
.Minibox {
    border: 1px solid black;
    width:20px;
}
.MiniImg {
    width: 20px;
    height: 20px;
}

Answer: The height of TopRightDiv pushing TextDiv to down. Make TopRightDiv right align and set the position with margin-right.
.TopRightDiv {
    float: right;
    margin-right:16px;
}

.OuterBorder {
 border: 1px solid black;
 width: 120px;
 height: 140px;
 float: left;
}
.TopDiv {
 width: 80px;
 height:80px;
 border: 1px solid black;
 float: left;
}
#TextDiv {
 border: 1px solid black;
 width: 80px;
 float: left;
}
.TopRightDiv {
 float: right;
  margin-right:16px;
}
.Minibox {
 border: 1px solid black;
  width:20px;
}
.MiniImg {
 width: 20px;
 height: 20px;
}

Text

Comment: Thanks, I wanted to refrain from using the margin property. I got it to work by containing the top and bottom in a single div
Answer: Try this:
.TopRightDiv {
    float: right;
    margin-right: 15px;
}

Answer: This code can help
.OuterBorder {
    border: 1px solid black;
    width: 120px;
    height: 140px;
    float: left;
    }
.TopDiv {
    width: 80px;
    height:80px;
    border: 1px solid black;
    float: left;
}
#TextDiv {
    border: 1px solid black;
    width: 80px;
    position: absolute;
    left: 80px;
}
.TopRightDiv {
    float: left;
}
.Minibox {
    border: 1px solid black;
    width:20px;
}
.MiniImg {
    width: 20px;
    height: 20px;
}


How does rune combiner work?

Question: I got Level 28, but I've never used runes before. I have now some IP and can buy some Tier 3 runes.
How does the rune combiner work in League of Legends? Which Tier 3 runes should I combine? Are there any recipes to build better runes, or is combination result random?
Answer: Combining two runes will give you a random rune of the same tier. Combining 5 runes will give you a random rune of the next highest tier. You cannot combine 5 tier 3 runes at once (as there is no tier 4).
The rune combiner is random. It doesn't matter whether you combine marks, glyphs, seals, or quintessences -- they all work with each other, and the output can be anything.
The idea is that, generally, runes themselves are priced such that it is slightly cheaper to generate a tier 3 runeset from your old runes than by buying the tier 3 runes on their own. For instance, the level 1 +AD rune is 15 ip, while the level 2 +AD rune is 80 ip -- if you bought 5 of the level 1 runes, combined them, and wound up with a level 2 +AD rune, you would have saved yourself IP.
Unfortunately, as mentioned earlier, this process is completely random. If you have tier 1 and 2 runes, by all means, combine them to higher levels; the rune combiner is just a way to possibly recoup the IP you spent on runes you no longer find useful, but it cannot be counted on to give you what you want. You might luck out and combine 2 random runes into a +Dodge quintessence (very expensive!) -- or you might get a mana/5 Mark (with a tertiary stat, and probably not worth the IP cost of your combined runes).
It's very much a gamble, and you don't get anything exclusive from it, so use it if you need to get rid of T1 / T2 runes, and safely ignore it otherwise.
Comment: As recently brought up on a linked question, the Rune Combiner does not care if you already have 9 runes of a particular type - it will give you a 10th just as soon as it will give you a rune you have only 3 of.
Comment: Is that confirmed or just an extrapolation of "the combiner is random?"  I ask because the store prevents you from buying more than 9 of any rune, so it's reasonable to wonder if Riot also coded the combiner to respect a 9-rune cap.  Could the combiner  be "randomly selected from the set of runes that you don't have 9 of?"
Comment: @EricGrunzke It prevents you from *buying* more than 9 at once, but it doesn't prevent you from *owning* more than 9. The combiner is much older than the "buy multiple runes at once" addition (which was not available initially), so it's unlikely to do such check, unless they went back and adjusted it (since there's no benefit to owning more than 9 runes, I find it feasible they may have just left it alone). Testing this is impractical, however, without some real-world investment (money -> RP or time).
Answer: As answered by Raven it all comes down to chance. I myself found if you do this at the start when your level 1 you gain a tremendous advantage over the rest of the players until later level.
The reason for this is that the Tier 2 and Tier 3 runes have a level requirement you have to reach in order to purchase them from the shop. If you use the Rune Combiner you can get the better Tier 2 to Tier 3 runes much sooner and actually place them into your rune page. Early on just hold onto the good Tier 2's you get and use them but hold onto the ones you won't use until you save up 5 of them for making the Tier 3 runes you'll always use later on - just buy the cheapest Tier 1 runes from the shop early (duplicates don't matter, just the absolute cheapest Tier 1's in the shop) and use 5 of them to create a Tier 2 rune.
For the ones you don't see yourself using save them until you have enough to create a Tier 3. Continue doing this until you reach the level requirement to buy the Tier 3 runes straight from the shop.
By this point you should have a nice amount of Tier 3 runes that will aid you tremendously. My last tip is that you should stop using the Rune Combiner when you reach around 40% maximum completion of having every single rune with the maximum set amount.
I found if you try to go push beyond that point you waste IP because you get Tier 3 duplicates which do you no good at all.
Answer: This does have potential if you invest in runes before level 20 (i.e. tier 3, which is not a good idea) For example: I have currently 3 tier 2 runes that I need to get rid of. The cheapest available tier 2 runes are 80 ip, so for 160 ip I may get something for my AP carry as awesome as a greater quint of CDR or something as horrible as a greater glyph of armor.

How does rune combiner work?


A question on python GIL

Question: Does the presence of python GIL imply that in python multi threading the same operation is not so different from repeating it in a single thread?.
For example, If I need to upload two files, what is the advantage of doing them in two threads instead of uploading them one after another?.
I tried a big math operation in both ways. But they seem to take almost equal time to complete.
This seems to be unclear to me. Can someone help me on this?.
Thanks.
Answer: Python's threads get a slightly worse rap than they deserve. There are three (well, 2.5) cases where they actually get you benefits:

If non-Python code (e.g. a C library, the kernel, etc.) is running, other Python threads can continue executing. It's only pure Python code that can't run in two threads at once. So if you're doing disk or network I/O, threads can indeed buy you something, as most of the time is spent outside of Python itself.

The GIL is not actually part of Python, it's an implementation detail of CPython (the "reference" implementation that the core Python devs work on, and that you usually get if you just run "python" on your Linux box or something.
Jython, IronPython, and any other reimplementations of Python generally do not have a GIL, and multiple pure-Python threads can execute simultaneously.

The 0.5 case: Even if you're entirely pure-Python and see little or no performance benefit from threading, some problems are really convenient in terms of developer time and difficulty to solve with threads. This depends in part on the developer, too, of course.
Comment: There's also Unladen Swallow, which is Google's project to build a fast replacement for CPython.
Comment: Sure, the GIL is only a problem in CPython. Though I can't really imagine somebody moving to Jython or IronPython just because of that when there are better ways to get around it.
Answer: It really depends on the library you're using. The GIL is meant to prevent Python objects and its internal data structures to be changed at the same time. If you're doing an upload, the library you use to do the actual upload might release the GIL while it's waiting for the actual HTTP request to complete (I would assume that is the case with the HTTP modules in the standard library, but I didn't check).
As a side note, if you really want to have things running in parallel, just use multiple processes. It will save you a lot of trouble and you'll end up with better code (more robust, more scalable, and most probably better structured).
Comment: Should also mention that multiprocessing is the gateway to scaling across multiple machines anyway.  Threads cannot get you there.
Answer: It depends on the native code module that's executing. Native modules can release the GIL and then go off and do their own thing allowing another thread to lock the GIL. The GIL is normally held while code, both python and native, are operating on python objects. If you want more detail you'll probably need to go and read quite a bit about it. :)
See:
What is a global interpreter lock (GIL)? and Thread State and the Global Interpreter Lock
Answer: Multithreading is a concept where two are more tasks need be completed simultaneously, for example, I have word processor in this application there are N numbers of a parallel task have to work. Like listening to keyboard, formatting input text, sending a formatted text to display unit. In this context with sequential processing, it is time-consuming and one task has to wait till the next task completion. So we put these tasks in threads and simultaneously complete the task. Three threads are always up and waiting for the inputs to arrive, then take that input and produce the output simultaneously.
So multi-threading works faster if we have multi-core and processors. But in reality with single processors, threads will work one after the other, but we feel it's executing with greater speed, Actually, one instruction executes at a time and a processor can execute billions of instructions at a time. So the computer creates illusion that multi-task or thread working parallel. It just an illusion.

A question on python GIL


isFinishing() is false although application is being destroyed

Question: According to the API:

public boolean isFinishing ()
Added in API level 1 Check to see whether this activity is in the
  process of finishing, either because you called finish() on it or
  someone else has requested that it finished. This is often used in
  onPause() to determine whether the activity is simply pausing or
  completely finishing.

But isFinishing() does not work as excepted. Here's the output I'm getting from my app:

D/com.example.operator.app.MainActivity: onPause() [13513] isFinishing
  false  D/com.example.infra.providers.operator.ExampleProvider: pause()
  D/com.example.infra.messaging.MessageHandler: stop()
  D/com.example.infra.messaging.MessageHandler$1: onDisconnectEvent()
  D/com.example.operator.app.MainActivity: onSaveInstanceState()
  D/com.example.operator.app.MainActivity: onStop() [13513] isFinishing
  false  D/com.example.operator.app.screens.MainStackView:
  onDestroyView()  D/com.example.operator.app.MainActivity: onDestory()

so isFinishing() returns FALSE although the application IS being destroyed. This is wrong and does not reflect what the API says.
What am I missing?
Comment: Your understanding of [finish](http://developer.android.com/reference/android/app/Activity.html#finish%28%29) is wrong. Activities that are finished are gone from the task stack: http://developer.android.com/guide/components/tasks-and-back-stack.html (often naviation backwards) - when it's saving instance state then because it's coming back later.
Comment: Activity class source needed
Comment: isFinishing() will only be called if the activity has been finished using finish() method I think.
Answer: You call isFinishing to early if you call it in onDestroy method it will return true.


How can I match and output the elements from the result of the .predict(x) method with the elements from another array?

Question: I have the following code:
# Load model
with open('text_classifier.pkl', 'rb') as f:
    countVec, model = pickle.load(f)

#Convert to bag of words
results = countVec.transform(commentsInput)

# predict converted text with the trained model
predictionsNew = model.predict(results)

print(predictionsNew)

The output from the print(predictionsNew) is as follows: [[1 0 1 0 1 0]]
When I do type(predictionsNew) it returns the type of output as numpy.ndarray
Each value in that array corresponds to a label from my dataset, and tells me if the input matches that label. For example, lets say each value corresponds to this array labels = ['a','b','c','d','e','f'].
I would like to loop through the first array and second array and produce an output as follows:
a = 1
b = 0
c = 1
d = 0
e = 1
f = 0

What is the easiest way I can achieve this?
UPDATE:
I believe the array of numbers contains just one element. So basically I would like to split this single element into 6 different elements which correspond to my labels array.
Comment: Variable and function names should follow the `lower_case_with_underscores` style. Can you be more specific about what you're struggling with?
Comment: Does this answer your question? [Zip lists in Python](https://stackoverflow.com/questions/13704860/zip-lists-in-python)
Answer: You are looking for the zip function.
a = ["a", "b", "c", "d", "e"]
b = np.ndarray((5,), buffer=np.array([0, 1, 0, 1, 0]), dtype=int)

for x, y in zip(a, b):
    print(f"{x} = {y}")

Outputs:
a = 0
b = 1
c = 0
d = 1
e = 0

Comment: Yup, glad it did. :)


At least probability of two students

Question: I have been trying to view this problem for a while and I have come unstuck, because of the at least at least part.

Calculate the probability that at least one of two students A and B, who independently attend each lecture of physics with a probability of 0.9 will fail to be present during at least 1 lecture of the 10 lecture series.

So I have tried to think about this several ways. Here is a few.
I first started to look at the probability of at least one of the students turning up to a lecture.
So this can be done two way.
1) I can look at the probability of both students turning up
$P(A\: and \: B)=\frac{81}{100}$ and then looking at the individual $P(A\: not \:  B)=\frac{9}{100}$ and $P(B \: not \: A)=\frac{9}{100}$ so I can sum all these to get the probability of atleast 1 to be $P(At\:least \: 1)=\frac{99}{100}$
or
2) I can use the venn approach where $P(A \cap B)=P(A)+P(B)-P(A \cup B)=\frac{99}{100}$ if I sub in the given probabilities.
So then I thought if I could look at say two lectures and I get both methods to agree then I must be on to the right track. The issue is I can get either method to agree.
So I used a spread sheet as displayed below to calculate the probabilities for two lectures where A and B turn up individually or as a pair.

The last number is the sum of all the probabilities so then I make the probability of A and B being at least 2 lectures is $0.9639$.
I then used the following to confirm this $P(Atleast \: 1)=(0.9)^2+(0.9)^2-(0.81)^2=0.9639$
Now the two results do confirm however I am not quite convinced that it is correct at is you did it for 10 lectures the I have a probability that of $(Atleast \: 1)=0.58$.
I then did a little research and could not find anything that would confirm my results or how I have carried out the calculation. So I then came across the Bernoulli method where you have a given set of experiments and the probability is the same for each trails i.e like flipping a coin, so I decided to try and apply this method to the problem.
so according to the Bernoulli method I make the probability $(Atleast \: 1)=1-(1-\frac{1}{100})^10=0.0951$ which dose not line up with the preceding.
Could someone may shed light on where I am going wrong, and explain how I should approach.
Comment: What is the negation of "At least one student will fail to be present at at least one of the ten lectures?"
Comment: Could you expand on that beacuse it that not what i have done using the bernouli method
Comment: I wrote an answer.  See if it clarifies matters for you, and ping me if it doesn't.
Answer: You are starting out okay, but you're making the problem more difficult than it really is.  When you have trouble calculating a probability it's often worthwhile whether it would be easier to calculate the complementary probability: the probability that the event does not occur. Then you just subtract from $1$ to get the probability you're really interested in.
The negation of "At least one of the students is not present at at least one of the lectures," is "Both students are present at all the lectures."  Since you've already calculated that the probability that both are present at a given lecture is $.81,$ I'm sure you'll see how to proceed from here.
Comment: Ah I see now, at the time I was too intrested in looking at the complicated view and trying to find all the possible outcomes.

At least probability of two students


Could we solve $\int_{0}^{\infty}\sin(x)dx$ and what does it say about $\lim_{x\to\infty}\cos(x)$?

Question: As the title states: Could we solve $\int_{0}^{\infty}\sin(x)dx$ and what does it say about $\lim_{x\to\infty}\cos(x)$?
It is clear we can't solve this using the fundamental theorem of Calculus, but I thought it would be solvable as a summation.
$$\int_{0}^{\infty}\sin(x)dx=\lim_{u\to\infty}\lim_{v\to\infty}\sum_{i=1}^{u}\frac{v\sin(\frac{vi}u)}{u}$$
I figured this would be hard to solve, so I went a different path:
Noting that $$\int_{0}^{\pi}\sin(x)dx=2$$$$\int_{n}^{n+\pi}\sin(x)dx=-\int_{n-\pi}^{n}\sin(x)dx$$For $n=m\pi$, $m=0,1,2,3,\cdots$
Trying to put this all together, I arrive at
$$\int_{0}^{\infty}\sin(x)dx=\sum_{i=0}^{\infty}(-1)^i2=2-2+2-2+\cdots$$This summation evaluates to equal:
$$2-2+2-2+\cdots=1$$So, I argue that
$$\int_{0}^{\infty}\sin(x)dx=1$$
Furthermore, going back to the fundamental theorem of Calculus, we have:
$$\int_{0}^{\infty}\sin(x)dx=\lim_{p\to\infty}-\cos(p)-[-\cos(0)]$$$$=-\lim_{p\to\infty}\cos(p)+1=1$$
Therefore, we have
$$-\lim_{p\to\infty}\cos(p)=0=-0=\lim_{p\to\infty}\cos(p)$$
Am I wrong?  If so, what does the indefinite integral evaluate to and what does it mean for $\lim_{p\to\infty}\cos(p)$?
Comment: How do you get to $2-2+2-2+\ldots =1$? That is not the value of this sum in the general sense as value of a series.
Comment: The series $\sum (-1)^n$ is Cesàro-summable to $\frac{1}{2}$. We can do something analogous for integrals, and say that (the locally integrable function) $f$ is C-integrable to $a$ if $$\lim_{x\to +\infty} \frac{1}{x}\int_0^x F(t)\,dt = a,$$ where $F(t) = \int_0^t f(u)\,du$. In that sense, since $\int_0^t \sin u\,du = 1 - \cos t$, $\sin$ is C-integrable to $1$.
Comment: @Hirshy It is oscilating and similar to $1-1+1-1+\dots=.5$, I'm looking up what the summation method is called.
Comment: Also $1-1+1-1+\ldots=0.5$ is not the value of the series. This can be achieved e.g. by [Ramanujan summation](https://en.wikipedia.org/wiki/Ramanujan_summation) which has nothing to do with integrals and riemann sums. You can assing a value to this sum which makes sense to some extent, but you can't expect to use this value in other applications.
Comment: @Hirshy Really?  Then what's the point of being able to "evaluate" something like that?  (probably nothing?)
Comment: @DanielFischer Is there anything more we can do with that?  And could you post it as an answer?
Comment: Let us not worry at this point about unusual notions of summation. What we can observe for sure is that *it is not true* that $\lim_{p\to\infty}\cos(p)=0$.   For $\cos(2n\pi)=1$ for all natural numbers $n$.
Comment: @AndréNicolas I am not disagreeing, but $\lim_{p\to\infty}\cos(p)=0$ is at least reasonable in my defense.
Comment: @SimpleArt: Not from the usual definition of limit. Nor from a casual glance at  a picture of the curve, which bounces back and forth from $-1$ to $1$ forever.
Comment: @AndréNicolas Yes, that is true.  I agree, the limit probably doesn't exist.
Answer: No. The integral doesn't convergent and the limit doesn't exist given the periodicity of the functions involved.
Answer: It is clear that neither $\int_0^{+\infty}\sin x\,dx$ nor $\lim\limits_{x\to+\infty}\cos x$ exist in the conventional meanings of these symbols. But similar to how one can assign more or less reasonable values to some divergent series, one can also assign more or less reasonable values to some divergent integrals.
Recall that a series $\sum_n a_n$ is Cesàro-summable if the sequence of arithmetic means of the partial sums converges,
$$(a_n)\quad\text{Cesàro-summable } :\mspace{-5mu}\iff \lim_{n\to\infty} \frac{1}{n+1}\sum_{k = 0}^n \sum_{m = 0}^k a_m\quad\text{exists.}$$
Analogously, we might call a locally integrable function $f\colon [0,+\infty) \to \mathbb{R}$ C-integrable if the limit of the arithmetic means of the partial integrals,
$$\frac{1}{x}\int_0^x \biggl(\int_0^t f(u)\,du\biggr)dt,$$
exists. If $L := \lim\limits_{x\to +\infty} \int_0^x f(t)\,dt$ exists, then $f$ is C-integrable, and the C-integral equals $L$, so C-integrability is compatible with integrability, like Cesàro-summability is compatible with summability.
Since $\int_0^t \sin u\,du = 1 - \cos t$, we have
$$\frac{1}{x}\int_0^x \biggl(\int_0^t \sin u\,du\biggr)dt = \frac{1}{x}\int_0^x 1 - \cos t\,dt = 1 - \frac{\sin x}{x} \to 1,$$
so $\sin$ is C-integrable to $1$.
There are other ways than Cesàro-summation to assign values to (some) divergent series, and we can also use other means to assign values to divergent integrals. For example, if $f$ is (locally integrable and) of at most polynomial growth, then
$$I_{\varepsilon}(f) := \int_0^{+\infty} e^{-\varepsilon t}f(t)\,dt$$
exists for every $\varepsilon > 0$, and if $\lim\limits_{\varepsilon \searrow 0} I_{\varepsilon}(f)$ exists, we can assign that value to the integral. If $f$ is Lebesgue-integrable (improperly Riemann-integrable), the limit exists and equals the Lebesgue integral by the dominated convergence theorem (resp. it equals the improper Riemann integral).
For $\sin$, we find
\begin{align}
\int_0^{+\infty} e^{-\varepsilon x}\sin x\,dx &= \frac{1}{2i}\int_0^{+\infty} e^{(i -\varepsilon)x} - e^{-(i+\varepsilon)x}\,dx\\
&= \frac{1}{2i}\biggl[\frac{1}{\varepsilon - i} - \frac{1}{\varepsilon + i}\biggr]\\
&= \frac{1}{\varepsilon^2 + 1},
\end{align}
so also this method leads to the value $1$.
Comment: Near the end/middle was a funky diagonal arrow in a limit.  I am unsure if you meant to use a regular arrow.
Comment: It's meant to indicate that $\varepsilon$ decreases towards $0$. It's also written $\varepsilon \downarrow 0$ with a vertical arrow, $\varepsilon \to 0^+$ means the same thing. Since I've explicitly restricted $\varepsilon$ to strictly positive values, writing $\lim\limits_{\varepsilon \to 0}$ would probably also have been legitimate.
Comment: Does not it simply assume that $\cos(\infty)=0$, and then it comes to $-\cos(\infty)-(-\cos(0))=1$?
Comment: @Anixx No. What gave you that idea?
Comment: @Daniel Fischer if your answer is 1 and we know that $-\cos(0)$=-1, it follows that you count $\cos(\infty)$ as 0.
Comment: Nonsense, @Anixx. I don't use anything like $\cos (\infty)$ at all. While one could give meaning to that expression [we could simply define it as meaning $\frac{43\pi}{60}$, why not?], I don't see a way to give a meaning to it that makes using it in any way helpful here. If $\lim_{x\to +\infty} f(x)$ exists, then it can be quite useful to define $f(\infty)$ as that limit. But the limit doesn't exist for $f = \cos$.
Comment: @Daniel Fischer I see, the sequence of integrals over semi-periods seems to be 2,0,2,0,2,0... This intuitively implies the sum should be 1 (as an average). The problem with it is that the distance between the semi-periods is not the same as from the mid of the first semi-period and zero. Also, the semi-periods are not separated by intervals of one (which is lesser problem).
Comment: http://m.wolframalpha.com/input/?i=%5Cint_%7B0%7D%5E%7B%5Cinfty%7D%5Csin+x+dx+&x=11&y=4
Comment: @TehRod Yes, the integral doesn't exist in the classical sense. I say that in the first sentence of the answer. But like for divergent series, there are methods to assign values to certain divergent integrals. Sometimes some of these methods are sensible.
Comment: Hmm interesting, I had no idea
Answer: By definition of the improper integral,
$$\int_0^\infty \sin(x)\,dx=\lim_{t\to\infty}\int_0^t\sin(x)\,dx.$$
By the fundamental theorem, this is also
$$\lim_{t\to\infty}(1-\cos(t)).$$
Hence the requested relation is
$$\int_0^\infty \sin(x)\,dx=1-\lim_{t\to\infty}\cos(t),$$ which is perfectly undefined.


Proving differentiability at x0 using continuity at x0

Question:
This is a question I haven't been able to complete for some time now. I have shown below what I have tried so far and I need to know the following,
1.Am I on the right track?
2.How do I show that f' is differentiable at x0?

Also I would appreciate some hints on how I could complete part (b) of the question.Thanks in advance.
Comment: I think there is a mistake in the question. That should be $f$ is differentiable at $x_0$.
Comment: Your third implication means that $f'(x_0)=0$.
Comment: $\displaystyle\lim_{x \to x_0} [f(x)-f(x_0)] = 0$ doesn't imply that $\displaystyle\lim_{x \to x_0} \frac{f(x)-f(x_0)}{x-x_0}=0$. Why? Well, what happens if $f(x) = |x|$ and $x_0=0$?
Answer: Consider any $\epsilon > 0$. Then, there exists a $\delta > 0$ such that if $0 < |x-x_0| < \delta$, then
$$\frac{|f(x)-a_0 - a_1(x-x_0)|}{|x-x_0|} < \epsilon$$
i.e.
$$|f(x)-a_0 - a_1(x-x_0)| < \epsilon |x-x_0| < \epsilon \delta$$
Then
$$|f(x)-a_0| - |a_1(x-x_0)| < |f(x)-a_0 - a_1(x-x_0)| < \epsilon\delta$$
So
$$|f(x)-a_0| < \epsilon \delta + |a_1| \delta$$
Now we may take $\delta$ to be smaller than $\frac{\epsilon}{|a_1|}$, so we see that
$$|f(x)-a_0| < 2\epsilon$$
That is, $\lim_{x \to x_0} f(x)-a_0 = 0$. Thus $f(x_0) = a_0$ by continuity.
Now that we have this, we see that
$$\lim_{x \to x_0} \frac{f(x)-a_0 - a_1(x-x_0)}{x-x_0} = \lim_{x \to x_0} \frac{f(x)-f(x_0)}{x-x_0} - a_1 = 0$$
i.e.
$$\lim_{x \to x_0} \frac{f(x)-f(x_0)}{x-x_0} = a_1$$
The left-hand side is $f'(x_0)$, which exists and is equal to $a_1$.


loading php page only when the div containing him becomes visible

Question: i make some sort of a shopping cart that when i press on a table line it suppose to open some details about the item, for this purpose i used a div which is at height 0 and hidden at first which contains the details, the problem is that i think that the browser will load the the info pages regardless of if the line was pressed or not. is there any way to make the browser load the page only when his DIV is visible?
    $int = 0;
            echo "
";
    foreach($types as $data){
        echo "
";
        echo "";
        echo $data['number'];
        echo "	";
        echo "";
        echo $data['item_name'];
        echo "	";
        echo "";
        echo $data['amount'];
        echo "	";
        echo "";
        echo "17";
        echo "
";
        echo "

            <object type=\"text/html\" data=\"page.php\"            style=\"width:100%; height:100%; margin:0%;\">

";
        $int++;
    }
    echo "</form>
";

the css for the row
.info_row{
    visibility:hidden;
}

the JS:
function present(item_id){
    var div = document.getElementById("div_num_"+item_id);

    if(div.style.visibility=="visible"){
        div.style.visibility = 'hidden';
        div.style.height= '0';
    } else {
        div.style.visibility = 'visible';
        div.style.height= "200px";
    }
}

as you can see all the info loads with the page but are invisible.
other good ways of tackling this problem will be appritiated especially if it does not include jquery because i am not really strong in it.
thanks in advance.
Comment: Look into jQuery AJAX requests.
Answer: Firstly, if there isn't much info to load, preloading the data is probably more sensible anyway. Users want a responsive UI, even if it means a few extra milliseconds of initial download time for data they'll never see.
But, if you insist on loading the data separately, you could use an xmlhttprequest to load a representation of the data (such as in JSON), and use a templating solution to output the result into the info div.
The page that might generate the JSON representation of the data might look something like this:
<?php
    $result = array();

    // ... Code that defines type ... //

    $int = 0;
    foreach($types as $data){

        $result[] = array(
            "int"       => $int,
            "number"    => $data["number"],
            "item_name" => $data["item_name"],
            "amount"    => $data["amount"]
        );

        $int++;
    }

    echo json_encode($result);
?>

So, when a user clicks a link, the above page would load in an xmlhttprequest. You could then parse the result with JSON.parse(req.responseText), and apply an HTML template to the result (check out the above link, plus this one, for more info on how to do that).
Again, you're probably fine just loading all the data in one go. Extra HTTP headers actually make pages take longer to completely load.
Comment: thank you for your response in my case i want to load a whole php page with connections to sql to retrieve data so it will really slow the connection to load all the pages. i am kinda new to all of this and dont have knowlege of JSON so i will look into your links for learning purposes since the other comment solved my problem.
Answer: You can use an ajax call:
with javascript

with jquery
$.ajax({
  url: "info.txt",
  context: document.body,
  success: function(text){
    //where text will be the text returned by the ajax call
    $(".result_table).append(text);
  }
});


Domain and range of composite function

Question:
Suppose $f(x) = e^{3x-2}, x \geq 3$ and $g(x) = x + 3, x \in \mathbb{R}$.

I Want to find the domain of $fg(x)$.
My logic:
Now $f(x)$ can only take values of $x \geq 3$, so I must restrict $x + 3 \geq 3$ so $x \geq 0$. Hence the domain of $fg(x)$ is $x \geq 0$.
Is this correct?
Answer: To find the domain of the composite function
$$( f \circ g )(x)=f(g(x))$$
one can follow these two steps

Find the domain of the inside (input) function.
Construct the composite function. Find the domain of this new function. If there are restrictions on this domain, add them to the restrictions from Step 1. If there is an overlap, use the more restrictive domain (or the intersection of the domains).

In your case, the domain of the inside function $g(x)=x+3$ is all real numbers while the domain of $f(x)$ is $x\geq 3$. Therefore, the domain of the composition $f(g(x))=f(x+3)$ is $x+3 \geq 3$ which after subtracting $3$ from both sides forms $x\geq 0$.
Answer: That's right since $f$ is defined only for arguments greater than $3.$
Comment: But f cannot take values less than 3?? So how does f(2) make sense coming from fg(-1)
Comment: @PhysicsMathsLove See edit.

Domain and range of composite function


How to search in all attributes using DSL query?

Question: How to check the value contain a string
Below is sample data. I need to search the any attributes which is Thomas

You can see I only have Thomas in first document. So first document has to return. Basically one document if any search field exists i need to retrieve that document

   {
       "id": "Accounting 101",
       "dataproduct": "E3",
       "professor": {
           "name": "Thomas Baszo",
           "department": "finance",
           "facutly_type": "part-time",
           "email": "email@example.com"
           },
       "students_enrolled": 27,
       "course_publish_date": "2015-01-19",
       "course_description": "Act 101 is a course from the business school on the introduction to accounting that teaches students how to read and compose basic financial statements"
   }

   PUT /data/test/2
   {
       "name": "Accounting 101",
       "room": "E3",
       "professor": {
           "name": "Sachin Baszo",
           "department": "finance",
           "facutly_type": "part-time",
           "email": "email@example.com"
           },
       "students_enrolled": 27,
       "course_publish_date": "2015-01-19",
       "course_description": "Act 101 is a course from the business school on the introduction to accounting that teaches students how to read and compose basic financial statements"
   }

Answer: You can use query string to search on any field.
GET /_search
{
  "query": {
    "query_string": {
      "query": "Thomas"
    }
  }
}

default_field
(Optional, string) Default field you wish to search if no field is provided in the query string.

Defaults to the index.query.default_field index setting, which has a default value of *. The * value extracts all fields that are eligible for term queries and filters the metadata fields. All extracted fields are then combined to build a query if no prefix is specified.


Using Dapper with BLOBs and SQL Server CE

Question: When using BLOBs with more than 8000 bytes of data, you need to specifically set Parameter.SqlDbType = SqlDbType.Image to make it work (as explained here).
Dapper, when it sees a byte[] field, defaults to a SqlDbType.Binary, which means for larger blobs, the inserts and updates will fail with a data truncation error.
Is there an elegant solution to this problem? Only option I can see is to code the entire transaction with ADO.NET methods.
Comment: Ooh, that's a pain; I suspect you might be better logging this as a bug against dapper, though
Comment: If you take a look at the dapper source ( http://code.google.com/p/dapper-dot-net/source/browse/Dapper/SqlMapper.cs ) you could add a special case in the function "LookupDbType" returning the appropriate SqlDbType. No clue if it breaks something else though.
Comment: Thanks!
I think I'll modify the static SqlMapper constructor and modify the following line:
typeMap[typeof(byte[])] = DbType.Binary;
Answer: I had the same problem. Resolved as follows:
private static IDbCommand SetupCommand(IDbConnection cnn, IDbTransaction transaction,
                                       string sql, Action<IDbCommand, object> paramReader,
                                       object obj, int? commandTimeout,
                                       CommandType? commandType)
{
    var cmd = cnn.CreateCommand();
    var bindByName = GetBindByName(cmd.GetType());
    if (bindByName != null) bindByName(cmd, true);
    if (transaction != null)
        cmd.Transaction = transaction;
    cmd.CommandText = sql;
    if (commandTimeout.HasValue)
        cmd.CommandTimeout = commandTimeout.Value;
    if (commandType.HasValue)
        cmd.CommandType = commandType.Value;
    if (paramReader != null)
    {
        paramReader(cmd, obj);
    }
    //CODTEC SISTEMAS
    foreach (System.Data.SqlServerCe.SqlCeParameter item in cmd.Parameters)
    {
        if (item.SqlDbType == System.Data.SqlDbType.VarBinary)
            item.SqlDbType = System.Data.SqlDbType.Image;
    }
    //CODTEC SISTEMAS
    return cmd;
}


Safe & chemical free way to clean AC coils?

Question: My ac system last had regular maintenance/inspection 9 months ago. Normally I have it done every 6 months but due to coronavirus the company I have a warranty with isn't honoring their warranty.  And now my electrical usage is about 2x what it should be (according to the power company comparing my usage to my neighbors) and I think the AC is why. I'm located in Florida where it's usually 90+ degrees almost every day. I did an experiment where I covered the sun facing windows in my home and the electrical usage went down by half.
My concern with cleaning the coils is I was told by a tech to never use any chemicals in the AC, not even bleach. Most techs in the past told me you can use bleach or vinegar but this guy told me not to listen to them because any chemicals can damage the coil.
I suppose it's possible that the tech is both right and wrong. Maybe chemicals are always bad but you have to use them to clean the thing?
Can I just toss a lot of boiling water on it and let the gunk go down the condensation drain? I know how to clean a clogged drain line but are there any problems with using boiling water? Or do you have other suggestions?
Comment: I've never used anything from water from the hose.  Perhaps some mild soap like dish soap might help.  I don't think I'd use a pressure washer either as those can damage the soft metal.
Comment: I can't give you a product name, but they have "no rinse" evaporator coil cleaner. You spray on the coil and walk away, the condensate the coils create will rinse the product away. It's good for preventative maintenance. You can find it on amazon or big box home centers. NEVER use condenser coil cleaner on evaporator coils...
Comment: Define "chemical". Water is a chemical. _You_ are chemicals. Are you asking specifically how to do it with only water?
Comment: @gunner maybe this: Nu-Calgon 4171-75 Evap Foam No Rinse Evaporator Coil Cleaner
Comment: @isherwood chemical meaning chemicals harmful to the equipment in this context.
Comment: From a corrosion perspective, both bleach and vinegar are  very corrosive to the aluminum evaporator coil. . My coil did not leak  and worked well for 23 years; A couple times I used a spray cleaner  form the  AC supply shop. Changing filters is important to protect  the coil.
Comment: I use high pressure water. Aluminum in the cooling fins will be corroded by anything that is acid or base. I expect dish soap in the water would be OK, but would not go beyond that.
Answer: Never say never or always because that will always get you in trouble.
Vinegar is an acid--it will eat the galvanized off the drip pan and can attack the fins so vinegar or acid-based cleaners are bad.
I don't like bleach because it stinks and if not completely rinsed will have your house smelling like a swimming pool for days.
No boiling water the thermal shock can crack fittings.
Now that we talked about what you can't or shouldn't do... There are special chemical cleaners made for coils I use a foaming cleaner made by NU-Calgon called NU-brite. You will find coil cleaners at the big box stores made for coils these also clean the dust and grime out of the coil& fins.
Mild dishwashing soap can be used with water but getting all the soap out can be the fun part there.
Never use a pressure washer on a coil or the fins can be permanently damaged. Same with compressed air. A gentle wash with a hose on the outside unit may be the best bet if you do not have the proper chemicals.
Simple green and water sprayed in with a pump sprayer similar to what you use for killing weeds (never use a sprayer that has been used with weed killer on the inside unit).
I have tried many things and found the best option is commercial cleaner. My 2nd choice simple green and water followed with a good clear water rinse.
Yes I have HVAC licenses and your advice is mostly good not to use chemicals that will react poorly with aluminum, or galvanized materials. I usually power down the system to clean them this allows the chemicals we do use to do there job breaking down tree sap, dust, oil dog/cat pee (on outside units) that will damage the fins also. Once I treat the coil I flush it with clear water sometimes a 2nd treatment is needed but not usually on a well maintained system as yours has been.
I use 2 different sprayers on inside units one for the chemical and one with clear water. Making sure the drain stays clear and doesn't overflow the pan.
This should help return your system to peak performance. And don't forget about your filter. Always a good time to change the filter after a coil clean.
Comment: Are you saying you use NU-Brite indoors or only outside? I read that it is recommended for outside only. So that would just leave soap and water then?
Comment: NU brite is a foaming coil cleaner They don't recommend for indoor use because of the foam overflows the pan a small shop vac takes care of that and is what the factory rep suggested I have been using for both for several years I think my wet dry shop vac is 3 gallon but I only vacuum as it gets to the drain sometimes a little clear water spray and it goes down the drain , if not I suck it up before it makes a mess.
Comment: I also found this (based on a comment above): Nu-Calgon 4171-75 Evap Foam No Rinse Evaporator Coil Cleaner. Seems you can use this one inside or out. Maybe I will try nu-brite on the outside and this one on the inside. Thanks
Comment: I really like the foaming cleaner , simple green did a good job but took multiple cleanings. You can see the foam pushing out the dirt then it goes white you know you got it all but I have used several of their products and hav been pleased with the results, I found out about nu-brite in a training class ( 4 hour sales pitch) for a particular brand of ac unit the rep came in and gave samples I used the sample on my unit I thought I had cleaned it well , I purchased a gallon and told him if it worked inside I would buy the 2 or 2-1/2 gallon totes that's when he told me about the vacuum.
Comment: Just in case anybody cares: Been using the nu-calgon evap foam no rinse both inside and out for years now. Pricey but worth it. Works like magic. If it's not shooting out of the can like a laser beam you probably didn't shake the can enough.


Initializer fails to determine size of character array

Question: Whenever I run the code below (Yes that's all the code) the compiler gives me an error:
error: initializer fails to determine size of 'path'
What I want to do is copy the contents of argv[0], which is the path of the application as a character array, into the path variable.
int main(int argc, char** argv) {
    int offset = 0;
    int pathSize = 0;
    while(argv[0][pathSize] != '\0')
        pathSize++;

    char path[] = new char[pathSize];
    delete &path;
    return 0;
}

Comment: @JustinMeiners - just to be clear, there are no variable length arrays here.
Comment: Variable length arrays aren't valid in C++?
Comment: @JustinMeiners, Not until C++14
Comment: @PeteBecker ok i knew they aren't available, but were not sure if this was the problem. I asked for my own learning :)
Comment: @JustinMeiners - a variable length array looks like a local named object with a runtime size: `void f(int i) { int vla[i]; }`. The code here uses `new char[pathSize]`, which allocates from the free store.
Comment: @PeteBecker I was just confused about the array new char[pathSize]; syntax.
Comment: @JustinMeiners - that's the `new` operator.
Comment: @JustinMeiners - sorry, just trying to guess at what needs to be said. ``
Answer: Your error is in the below part of your code:
char path[] = new char[pathSize];
delete &path;

Change it to...
char *path = new char[pathSize];
delete[] path;

Comment: Honestly, the proper advice is to use `std::string` instead of this problematic `new` and `delete` nonsense.
Comment: I will need to convert the string to character array anyways because I  am preparing the path to send to another function which requires a character array.
Answer: First, char path[] should be char* path. Second, its delete[] path;. If you new[] you delete[] if you new you delete.
There is an extension for gcc (which is not standard mind you) which allows you to do this:
int main(int argc, char* argv[])
{
    int size = 34;
    char path[size];

    return 0;
}

However this will work only in gcc as this is a gcc extension.
Comment: Yeah sorry. It's some left-over from what I had first.  :)
Answer: You should use a dynamic array.
char* path = new char[pathSize];

and as others have mentioned delete is only needed for new, therefore you do need it, but the way your code was written is not how you would normally want to use delete


Need a quick fix for leaking door frame. During flood

Question: We are in the middle of tropical storm and there is flooding on one side of house.
The side door seems to be leaking from under the frame (not the actual door) its too wet to duct tape.
Any suggestions until the storm passes and we can fix it properly?
Comment: sandbags for the door?
Comment: jam newspapers into the cracks
Comment: You can use caulking designed for gutters to apply at the base between the door and its base. It can be applied from a tube directly in wet conditions. Underwater I'm not sure of. May not be 100% but it'll help.
Answer: IF you can drive during this event  then stuff something in it  for now and go get sandbags, or supplies for making them if they are available.  If you can NOT drive, there may assistance available from your local municipality to have officials or  volunteers bring you sandbags.
You can apply caulking to the gap  under the threshold on the exterior, (this should have been done at the time the door was installed) this will only keep the water out if the water is not higher then the threshold. Most caulking can not be applied on a wet surface,I have read that Lexel by Sashco can be applied in/on wet surfaces.
Doors are not designed to stop water intrusion from flooding caused by tropical storms. They may stop driving rain but if the water outside is not flowing away and is accumulating faster then it can be absorbed into the ground, flooding, then it will make its way in where ever it can and door are perfect for that. Typical  entry doors will not stop that amount of water unless they are designed to do so, such as a ship or submarine door.
The usual way of keeping water out of houses during extreme weather events is to build a structure that stops the water from reaching the structure or diverting it away from the structure. (Or building the house above the high water mark, such as on pilings)  Sandbag walls are used in emergency's or in places where permanent structures are not in place.
Sandbags are not 100% effective at stopping all water but they will reduce the impact of flooding.
In some locations on the planet these events warrant a permanent structure to deal with the repeated events. In others it may be a "hundred year event" or an anomaly and sandbags or other temporary solutions are applied.  As the planets weather changes, the frequency of these events can increase.
In your case you need to stop the water from reaching the door now, not modify the door. Stuffing something in the gap under the threshold may help to keep the intrusion to a  minimum.
A sandbag wall is the best solution until the storm passes. Then you can determine if it is prudent to plan for future events and how best to do so.
Sandbagging Demonstration.
Answer: Can you remove the threshold and use a ton of caulking under the frame and between the door frame and the wall? You could then reset the threshold by setting it in caulking.


How to take the resulting object of a function called from another module?

Question: The idea is this - say I have a function in module2.py called def run(example): which has a data-frame object as the result of running it, let's call it df_1. If I call module2.run(example) inside module1.py will I be able to continue to use the result, df_1, inside module1.py and manipulate the data the way I want? Would I need to put the function in a class inside module2.py to do this? Or how should I structure my code if this was the plan?
Answer: Yes, you can do exactly the way you have said,
in module1.py, you just have to import module2.py like "import module2" or if the function is inside a class,
you can import it like "from module2 import classname"
Then you can create the object of the class and then call the method. You need to return the dataframe object from run function in order to use it. You may keep it global too, but recommended way of doing things.
for example if you have class
from module2 import MyClass
my_obj1 = MyClass()
df1 = my_obj1.run(param1,param2 etc)

Answer: When module2.run(example) was called, it created an object that occupies space in ram and returned a pointer to that object.
# Inside module2.py
import pandas as pd

def run(example):
    return pd.DataFrame(1, range(10), range(10))

# Inside module1.py
import module2

df_1 = module2.run(example)
df_1.loc[:] = 2

print(df_1)

   0  1  2  3  4  5  6  7  8  9
0  2  2  2  2  2  2  2  2  2  2
1  2  2  2  2  2  2  2  2  2  2
2  2  2  2  2  2  2  2  2  2  2
3  2  2  2  2  2  2  2  2  2  2
4  2  2  2  2  2  2  2  2  2  2
5  2  2  2  2  2  2  2  2  2  2
6  2  2  2  2  2  2  2  2  2  2
7  2  2  2  2  2  2  2  2  2  2
8  2  2  2  2  2  2  2  2  2  2
9  2  2  2  2  2  2  2  2  2  2


How can I cause Zombie Pigmen to drop their golden swords?

Question: Is it possible to acquire a Zombie Pigman's golden sword without killing them (Something like trading with them by throwing another weapon to their feet, such as a wooden sword for example)?
Comment: @Unionhawk It would be easy to gain golden swords if you could give zombie pigmen wooden swords.
Comment: For what purpose are you wanting to do this?
Comment: @Unionhawk: So that the Zombie Pigmen can have wooden swords, which as stated are better than gold ones.
Comment: To which, I reiterate, for what purpose? Mapmaking would be the only purpose I could see to this, in which case, yes, it is possible. In a survival context, absolutely not.
Answer: Yes, you can trade swords with Zombie Pigman, as per the wiki states, however I just spent almost 20 minutes attempting the act and I could not replicate it, so I am unsure of the truth to the wiki article.
Comment: So, can you at least give them iron or stone swords?
Comment: Can you at least bribe them?
Comment: @Ender check the minecraft wiki,if you throw down,lets say, a diamond sword in inventory form towards a zombie pigman,he will drop his golden sword and take the diamond one.He will deal more damage to you if you attack him then.
Comment: @Ender That **is** interaction, since you are doing *something* to affect them *somehow*. In that case, the answer would be "There is **no** way to interact with zombie pigmen *besides throwing down better swords at their feet and cause them to switch a bad weapon for a better one*"
Comment: I **guess** you cannot trade with Zombie Pigman...
Answer: NO trading with zombie pigmen unless you die and the pigman picks up your stuff. It works the same way as wither skeletons. (If you want a golden sword, just keep on killing zombie pigmen because they have a rare chance of dropping one.)
Comment: It will be easier to obtain gold swords if you could drop a wooden sword and they drop their gold one and take the wooden sword.Check my comment to Ender above.
Answer: Yes I have seen a pigman drop his gold sword for a stone one. However I tried for ages and had picked up several about a chest full from killing them in the process.
I was playing 1.9


What is the best way to return multiple values from django views.py to a template

Question: What would be the best way of returning multiple values in a Django views.py to the template?
For example, I want people to access any user's public profile by entering their username in the URL:
views.py
def public_profile(request, username_in_url):
    #Get appropriate user data from database
    user = User.objects.get(username = username_in_url)
    username = user.username
    first_name = user.first_name
    last_name = user.last_name
    date_joined = user.date_joined
    bio = user.userprofile.bio
    matchday_rating = user.userprofile.matchday_rating
    following = user.userprofile.following
    followers = user.userprofile.followers
    ..
    ..
    [return render_to_response..?]
    [use a Class instead and store values in a context?]

public_profile.html

 {{username}}

       First Name: {{first_name}}

       Last Name: {{last_name}}

       Date Joined: {{date_joined}}

       Matchday Rating: {{matchday_rating}}

       Following: {{following}}

       Followers: {{followers}}

 User Bio:

{{bio}}

urls.py
url(r'^(?P<username>\s)/$', 'fantasymatchday_1.views.register_success'),

Comment: There's no need to create another class when you already have a class you can pass: the User.
Comment: @DanielRoseman good point, I am also unsure of my URL pattern as it does not seem to recognise the string as a parameter. Could you offer any help on this? :)
Comment: You should have asked a new question. However it is completely broken: `\s` matches only a single space. You probably want `\w+` for multiple alphanumeric characters, or `[\w-_]+` if you also want dashes and underscores.
Answer: You can store the user fields in a dictionary and pass it as context to render_to_response:
def public_profile(request, username_in_url):
    user = User.objects.get(username = username_in_url)
    context = {
        'first_name': user.first_name,
        # ...
    }
    return render_to_response('public_profile.html', context)

It may be simpler to just pass the user object to the template:
def public_profile(request, username_in_url):
    user = User.objects.get(username = username_in_url)
    context = {
        'user': user,
    }
    return render_to_response('public_profile.html', context)

The  template would then need to reference the fields of user:
First Name: {{user.first_name}}

Answer: I think your url matching pattern is not right:
Try this:
urls.py
(r'^(?P<username_in_url>\w+)$', 'fantasymatchday_1.views.register_success')

I'm also not sure that you are pointing to your view the right way (register_success is the function you call in urls.py but in your example above you call the function public_profile).
Comment: support for `\s` is not appropriate, `[\w-_]+` will be better


How to resolve class cast exception when two same classes having same name, package and content?

Question: I am having same class with everything including package name and content same. still getting class cast exception while accessing two web application hosted on same tomcat. How to resolve the same ?
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/CourtForms] threw exception
    java.lang.ClassCastException: com.ibm.courts.sec.UserProfile cannot be cast to com.ibm.courts.sec.UserProfile
        at web.clerk.courtforms.servlet.FilterAuthentication.doFilter(FilterAuthentication.java:157)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1629)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)

Comment: Don't post images of errors, and post the full stack trace please. As text.
Comment: Based on the information provided, there is no reason to believe or disbelieve your diagnosis.
Comment: added stack trace and updated description. Please help
Comment: How can I help? Exactly?
Comment: How to resolve above exception ? I am having same class with everything including package name and content same. still getting class cast exception while accessing two web application hosted on same tomcat. How to resolve the same ?
Answer: Usually, having two classes with the same package and name is not a problem since the class loader will always just pick one (i.e. the first in the classpath).
It is more likely that your classes were loaded by different classloaders. In Java, classes loaded by different classloaders are not compatible and assigning them will result in a ClassCastException. This is by design.
From your stack trace it looks that you are using Tomcat; in many cases this is caused by having a library in both shared libs as well as deployed with web application. Again, this is not because of a duplicate class but because of ClassLoader design. If this is the case, either remove this library from shared libs or from .war you are deploying.
Comment: As I said, you have two choices: either (a) give each project a copy of this library and remove it from shared classes, or (b) move this library to shared classes and remove it from both projects. Option (a) is usually safer as it prevents one application to corrupt the other, but it will increase your memory footprint.
Comment: ok. How can I make my applications use same class loaders ? I am using tomcat 8.5. Both web application are deployed on same tomcat.
Comment: Issue has been resolved by adding  in context.xml of tomcat.
Comment: @Rahul Be aware that this is not the proper solution, but merely a workaround to avoid the problem. The problem is still there waiting for you.
Comment: Then how to resolve it ? Because I am not using war file to run application in tomcat. I am using context path in server.xml to run application and running two different project in same tomcat. I am facing UserProfile class and this class present in both project and I am getting userProfile data from one project and storing in another project's userProfile.


Date picker don't show proper date

Question: i am new to iPhone application development. i am creating simple application with using of datepicker. i have a date picker and a button. simply i want to print selected date and time when i click on button. bellow is my code.
<code>- (IBAction)showSelectedDate:(id)sender {
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSDate *pickerDate = [m_datePicker date];

    NSLog(@"%@", pickerDate);
}
</code>
In log date is print but it is wrong. i am select "2012-03-28 03:26 PM" this date from picker and in log i get the date "2012-03-28 09:50".
Thanks in adv....
Comment: The apple document says that "The default is the date when the UIDatePicker object is created." So I think you are getting the default date.
Comment: [m_datePicker date]; This 'm_datepicker' belongs to which class??, coz the 'date' it returns is being displayed in your log.!
Comment: check out the answer here [http://stackoverflow.com/questions/4272953/uidatepicker-strange-behaviour-not-setting-date-and-wrong-date-being-selected][1]

  [1]: http://stackoverflow.com/questions/4272953/uidatepicker-strange-behaviour-not-setting-date-and-wrong-date-being-selected
Answer: Try this code... It may work fine for you.
<code>- (IBAction)showSelectedDate:(id)sender
{
        NSDate *selectedDate = myPicker.date;

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"DD-MM-YYYY"];

    NSString *str = [formatter stringFromDate:selectedDate];
    NSLog(@" %@",selectedDate);
}
</code>
If u want time replace
<code>[formatter setDateFormat:@"DD-MM-YYYY"];
</code>
with this line
<code>[formatter setDateFormat:@"day, MMM HH:mm:ss Z"];
</code>
Hope this helps you.
Comment: this code print only date. but i don't have problem with date. i am having a problem with time. see my original post on upside.
Comment: [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
This is work for me...but when i going to convert string to date it's show wrong again.
Comment: please post your code.So that i can check where you making mistake.
Comment: - (IBAction)showSelectedDate:(id)sender {
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSDate *pickerDate = [m_datePicker date];
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
    [formatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    NSString *str = [formatter2 stringFromDate:pickerDate];
    NSLog(@"%@", str);
Comment: NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init];
    [formatter3 setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    [formatter3 setTimeZone:[NSTimeZone localTimeZone]];
    NSDate *finalDate = [formatter3 dateFromString:str];
    NSLog(@"%@",finalDate);
}
Comment: Man learn how to Add comment and how to add code.Check stak overflow guidelines.
Comment: `NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];`
    `[formatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];`
    `NSDate *str = (NSDate *)[formatter2 stringFromDate:pickerDate];`
    `NSLog(@"%@", str);`

    `NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init];`
    `[formatter3 setTimeZone:[NSTimeZone localTimeZone]];`
    `[formatter3 setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];`
    `NSDate *finalDate = [formatter3 dateFromString:str];`
    `NSLog(@"%@",finalDate);`
Answer: You are using GMT rather than local time so that it just looks wrong. Use
<code>datePicker.timeZone = [NSTimeZone localTimeZone];
</code>
Comment: @BhavinMakadia: did you set your picker's timezone ?

Date picker don't show proper date


why this Diophantine equation $2ks=(5t+3)(16t+9)$ has always a solution for every $k$?

Question: I would like to solve the following Diophantine equation and show that it has always a solution; i.e. for every positive integer $k$, there exists an integer $t$ such that the fraction is an integer:
$$
\frac{(5t+3)(16t+9)}{2k}
$$
Any hint will be grateful.
P.S.: Without considering cases for $k\equiv 0,1,2,3,4(\mod5)$.
Answer: Note that $t$ will have to be odd, say $2w+1$, so we want $(5w+4)(32w+25)$ to be divisible by $k$. Let $k=2^a5^b l$ where $l$ is divisible neither by $2$ nor by $5$.
We will succeed if we can find a value of $w$ such that $5w+4$ is divisible by $2^a$ and $32w+25$ is divisible by $5^bl$. So we want to solve the system of congruences
$$5w\equiv -4\pmod{2^a},\qquad 32w\equiv -25\pmod{5^b l}.$$
By multiplying the first congruence through by the inverse of $5$ modulo $2^a$, and the second congruence by the inverse of $32$ modulo $5^bl$, we obtain a system of congruences of the shape $w\equiv c\pmod{2^a}$, $w\equiv d\pmod{5^bl}$.
By the Chinese Remainder Theorem, this system has a solution.
Comment: Thanks. I think $q$ must be replaced by $l$.
Comment: Thanks for telling me. Midway through I changed my mind about what letter to use! Fixed.


I have an issue with PES 2020 for Android

Question: I just downloaded the game and finished the tutorials and played my first match (I think this first match is the last part of the tutorial).
Then, a white message appeared taking most of screen space. I'm not sure if it's supposed to be an ad, or if I received a reward, or it's an information message. But it's totally white blank.
I clicked on the (X) button to hide it. It goes then appears again.
How can I get rid of it?
Answer: Well,  the message looks exactly like when you open a notification message but it's blank.
The solution is to clear the data, and cash to do a fresh start and select the the language and the team...etc again. I selected a different team this time ;)
It might be useful to skip the tutorial to avoid any notifications or pop up messages.
This should solve the problem but when you open the notification, you will find them blank too but at least you will be able to close the blank notification and continue gaming normally and it won't open again automatically.


ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis

Question: I'm trying to implement a special type of neural network with Keras functional API, as seen below:

But I'm having a problem with the concatenate layer:

ValueError: A "Concatenate" layer requires inputs with matching shapes
  except for the concat axis. Got inputs shapes: [(None, 160, 160, 384),
  (None, 160, 160, 48)]

Notice: From my research I assume that this question is not duplicate, I've seen this question, and this post (translated with Google), but they don't seem to work (instead, they make problems even slightly "worse").

Here's the code of the neural network before concat layer:
from keras.layers import Input, Dense, Conv2D, ZeroPadding2D, MaxPooling2D, BatchNormalization, concatenate
from keras.activations import relu
from keras.initializers import RandomUniform, Constant, TruncatedNormal

#  Network 1, Layer 1
screenshot = Input(shape=(1280, 1280, 0), dtype='float32', name='screenshot')
# padded1 = ZeroPadding2D(padding=5, data_format=None)(screenshot)
conv1 = Conv2D(filters=96, kernel_size=11, strides=(4, 4), activation=relu, padding='same')(screenshot)
# conv1 = Conv2D(filters=96, kernel_size=11, strides=(4, 4), activation=relu, padding='same')(padded1)
pooling1 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(conv1)
normalized1 = BatchNormalization()(pooling1)  # https://stats.stackexchange.com/questions/145768/importance-of-local-response-normalization-in-cnn

# Network 1, Layer 2

# padded2 = ZeroPadding2D(padding=2, data_format=None)(normalized1)
conv2 = Conv2D(filters=256, kernel_size=5, activation=relu, padding='same')(normalized1)
# conv2 = Conv2D(filters=256, kernel_size=5, activation=relu, padding='same')(padded2)
normalized2 = BatchNormalization()(conv2)
# padded3 = ZeroPadding2D(padding=1, data_format=None)(normalized2)
conv3 = Conv2D(filters=384, kernel_size=3, activation=relu, padding='same',
               kernel_initializer=TruncatedNormal(stddev=0.01),
               bias_initializer=Constant(value=0.1))(normalized2)
# conv3 = Conv2D(filters=384, kernel_size=3, activation=relu, padding='same',
#               kernel_initializer=RandomUniform(stddev=0.1),
#               bias_initializer=Constant(value=0.1))(padded3)

# Network 2, Layer 1

textmaps = Input(shape=(160, 160, 128), dtype='float32', name='textmaps')
txt_conv1 = Conv2D(filters=48, kernel_size=1, activation=relu, padding='same',
                   kernel_initializer=TruncatedNormal(stddev=0.01), bias_initializer=Constant(value=0.1))(textmaps)

# (Network 1 + Network 2), Layer 1

merged = concatenate([conv3, txt_conv1], axis=1)

This is how interpreter evaluates variables conv3 and txt_conv1:
>>> conv3
<tf.Tensor 'conv2d_3/Relu:0' shape=(?, 160, 160, 384) dtype=float32>
>>> txt_conv1
<tf.Tensor 'conv2d_4/Relu:0' shape=(?, 160, 160, 48) dtype=float32>

This is how the interpreter evaluates txt_conv1 and conv3 variables after setting image_data_format to channels_first:
>>> conv3
<tf.Tensor 'conv2d_3/Relu:0' shape=(?, 384, 160, 0) dtype=float32>
>>> txt_conv1
<tf.Tensor 'conv2d_4/Relu:0' shape=(?, 48, 160, 128) dtype=float32>

Both of the layers have shapes which are not actually described in the architecture.

Is there any way to solve this problem? Maybe I didn't write the appropriate code (I'm new to Keras).
P.S
I know that the code above is not organized, I'm just testing.
Thank you!
Answer: You should change the axis to -1 in the concatenate layer since the shapes of the two tensors that you want to concatenate only differ in their last dimension. The resulting tensor will then be of shape (?, 160, 160, 384 + 48).
Comment: Well that was a quick fix, what's strange is that Caffe based neural network definitions use `axis=1` for concatenation layer, which is the reason for why I picked it. But regardless, dimension of the new shape is 432 as described in the architecture. Thank you!


Unnamed parameter with commander.js (positional arguments)

Question: I am currently taking a look at commander.js as I want to implement a CLI using Node.js.
Using named parameters is easy, as the example of a "pizza" program shows:
program
  .version('0.0.1')
  .option('-p, --peppers', 'Add peppers')
  .option('-P, --pineapple', 'Add pineapple')
  .option('-b, --bbq', 'Add bbq sauce')
  .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
  .parse(process.argv);

Now, e.g., I can call the program using:
$ app -p -b

But what about an unnamed parameter? What if I want to call it using
$ app italian -p -b

? I think this is not so very uncommon, hence providing files for the cp command does not require you to use named parameters as well. It's just
$ cp source target

and not:
$ cp -s source -t target

How do I achieve this using commander.js?
And, how do I tell commander.js that unnamed parameters are required? E.g., if you take a look at the cp command, source and target are required.
Answer: With the present version of commander, it's possible to use positional arguments. See the docs on argument syntax for details, but using your cp example it would be something like:
program
.version('0.0.1')
.arguments('<source> <target>')
.action(function(source, target) {
    // do something with source and target
})
.parse(process.argv);

This program will complain if both arguments are not present, and give an appropriate warning message.
Answer: You get all the unnamed parameters through program.args. Add the following line to your example
console.log(' args: %j', program.args);

When you run your app with -p -b -c gouda arg1 arg2 you get
you ordered a pizza with:
- peppers
- bbq
- gouda cheese
args: ["arg1","arg2"]

Then you could write something like
copy args[0] to args[1] // just to give an idea

Comment: Yes, of course, but my question is whether commander.js has built-in support for this, including coercion and all its other nice features.
Comment: Basically, this is a fine option, but - how do I specify that the arguments are mandatory?
Comment: you could do something like `if (!program.args.length) console.log('Please use the following syntax: cp source destination')`
Comment: @Golo Roden you can make the arguments mandatory by specifying them  with angled brackets -e.g. ``, and optional by using squared brackets -e.g. `[arg2]`.
Comment: Unfortunately not, so I'm still looking for an answer, too :-/
Answer: program.argument('<myarg>') + program.namedArgs as of 9.4.1 for positional arguments
Tested as of commander 9.4.1 the best option for positional arguments seems to be the .argument function.
This method achieves the basic features you'd expect from a decent library:

gives an error if mandatory arguments are not passed
allows you to set defaults and do custom parsing/checks e.g. integer conversion
give an error if there are too many positional with program.allowExcessArguments(false) (shame not the default)

We use program.namedArgs because program.args ignores myParseInt or defaults.
TODO built-in way to

access positional arguments by their name (e.g. program.processedArgs.arg1) rather than by index (program.processedArgs[0])

Sample usage:
positional.js
function myParseInt(value, dummyPrevious) {
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new commander.InvalidArgumentError('Not a number.');
  }
  return parsedValue;
}

const commander = require('commander');
const program = commander.program
program.option('-m --myopt <myopt>', 'doc for myopt', 'myopt-default');
program.argument('<arg1>', 'doc for arg1');
program.argument('<arg2>', 'doc for arg2');
program.argument('[arg3]', 'doc for arg3', myParseInt, 1);
program.allowExcessArguments(false);
program.parse(process.argv);
const [arg1, arg2, arg3] = program.processedArgs
const opts = program.opts()

// Use the arguments.
console.error(`arg1: ${arg1} (${typeof arg1})`);
console.error(`arg2: ${arg2} (${typeof arg2})`);
console.error(`arg3: ${arg3} (${typeof arg3})`);
console.error(`myopt: ${opts.myopt} (${typeof opts.myopt})`);

Sample calls:
$ ./positional.js
error: missing required argument 'arg1'
$ ./positional.js a
error: missing required argument 'arg2'
$ ./positional.js a b
arg1: a (string)
arg2: b (string)
arg3: 1 (number)
myopt: myopt-default (string)
$ ./positional.js a b c
error: command-argument value 'c' is invalid for argument 'arg3'. Not a number.
$ ./positional.js a b 2
arg1: a (string)
arg2: b (string)
arg3: 2 (number)
myopt: myopt-default (string)
$ ./positional.js a b 2 c
error: too many arguments. Expected 3 arguments but got 4.
$ ./positional.js -m c a b 2
arg1: a (string)
arg2: b (string)
arg3: 2 (number)
myopt: c (string)
$ ./positional.js a b 2 -m c
arg1: a (string)
arg2: b (string)
arg3: 2 (number)
myopt: c (string)
$ ./positional.js -h
Usage: positional [options] <arg1> <arg2> [arg3]

Arguments:
  arg1                doc for arg1
  arg2                doc for arg2
  arg3                doc for arg3 (default: 1)

Options:
  -m --myopt <myopt>  doc for myopt (default: "myopt-default")
  -h, --help          display help for command

Comment: `program.args` has the plain text arguments. See `program.processedArgs` for the arguments after custom processing.
Comment: Yes: `program.allowExcessArguments(false)`
Comment: @shadowspawn nice, updated. Any way to make commander check if there are too many positional arguments besides manual `program.args` check?


ffmpeg doesn't detect the subtitle format (webvtt) and refuses to copy it

Question: I am trying to re-encode the audio on some video files.
I want to copy the video and subtitles without touching them, however, ffmpeg doesn't detect the format of the subtitle (which is webvtt) and refuses to do anything.
fmpeg -copy_unknown -analyzeduration 2000M -probesize 2000M -i input.mkv -map_metadata 0 -map 0 -c copy -c:a:0 aac -b:a 384k output.mkv
[matroska,webm @ 0x5597558e4040] Unknown/unsupported AVCodecID S_TEXT/WEBVTT.
[matroska,webm @ 0x5597558e4040] Could not find codec parameters for stream 2 (Subtitle: none): unknown codec
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Guessed Channel Layout for Input Stream #0.1 : 5.1
Input #0, matroska,webm, from 'input.mkv':
  Metadata:
    encoder         : libebml v1.3.9 + libmatroska v1.5.2
    creation_time   : 2020-03-05T09:03:02.000000Z
  Duration: 00:56:33.26, start: 0.000000, bitrate: 3597 kb/s
    Stream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 23.98 fps, 23.98 tbr, 1k tbn, 47.95 tbc (default)
    Metadata:
      BPS-eng         : 3340067
      DURATION-eng    : 00:56:33.140000000
      NUMBER_OF_FRAMES-eng: 81354
      NUMBER_OF_BYTES-eng: 1416664616
      _STATISTICS_WRITING_APP-eng: mkvmerge v38.0.0 ('The Silent Type') 64-bit
      _STATISTICS_WRITING_DATE_UTC-eng: 2020-03-05 09:03:02
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
    Stream #0:1: Audio: eac3, 48000 Hz, 5.1, fltp (default)
    Metadata:
      BPS-eng         : 256000
      DURATION-eng    : 00:56:33.248000000
      NUMBER_OF_FRAMES-eng: 106039
      NUMBER_OF_BYTES-eng: 108583936
      _STATISTICS_WRITING_APP-eng: mkvmerge v38.0.0 ('The Silent Type') 64-bit
      _STATISTICS_WRITING_DATE_UTC-eng: 2020-03-05 09:03:02
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
    Stream #0:2(eng): Subtitle: none (default)
    Metadata:
      BPS-eng         : 38
      DURATION-eng    : 00:54:47.388000000
      NUMBER_OF_FRAMES-eng: 514
      NUMBER_OF_BYTES-eng: 15766
      _STATISTICS_WRITING_APP-eng: mkvmerge v38.0.0 ('The Silent Type') 64-bit
      _STATISTICS_WRITING_DATE_UTC-eng: 2020-03-05 09:03:02
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES

Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (eac3 (native) -> aac (native))
  Stream #0:2 -> #0:2 (copy)

[aac @ 0x5597b06ae000] Using a PCE to encode channel layout "5.1(side)"
[matroska @ 0x5597b06ab540] Subtitle codec 0 is not supported.
Could not write header for output file #0 (incorrect codec parameters ?): Function not implemented
Error initializing output stream 0:1 --
[aac @ 0x5597b06ae000] Qavg: -nan
Conversion failed!

VLC shows it as WebVTT and displays the subtitles correctly:

MediaInfo also detects properly as webvtt:
Text
ID                                       : 3
Format                                   : S_TEXT/WEBVTT
Codec ID                                 : S_TEXT/WEBVTT
Duration                                 : 54 min 47 s
Bit rate                                 : 38 b/s
Count of elements                        : 514
Stream size                              : 15.4 KiB (0%)
Language                                 : English
Default                                  : Yes
Forced                                   : No

My ffmpeg was built with webvtt:
$ ffmpeg -codecs | grep VTT
ffmpeg version n4.2.2 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 9.3.0 (Arch Linux 9.3.0-1)
  configuration: --prefix=/usr --disable-debug --disable-static --disable-stripping --enable-fontconfig --enable-gmp --enable-gnutls --enable-gpl --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libdav1d --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libiec61883 --enable-libjack --enable-libmfx --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libv4l2 --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxcb --enable-libxml2 --enable-libxvid --enable-nvdec --enable-nvenc --enable-omx --enable-shared --enable-version3
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
 DES... webvtt               WebVTT subtitle

How can I tell ffmpeg "this is webvtt, just copy it please!"?
EDIT: RESOLVED (thanks @Gyan)
To force the decoder, -c:s webvtt must be set before the input:
fmpeg -analyzeduration 50M -probesize 50M -c:s webvtt -i input.mkv ...
Comment: Then you can force the decoder: `fmpeg -analyzeduration 50M -probesize 50M -c:s webvtt -i input.mkv ... `
Comment: Forcing the decoder worked! I had tried ```-c:s webvtt``` but it was trying to convert it. I think that the order matters as I had added it at the end. Adding it before the input worked. Thanks @Gyan
Comment: (Note that you can add your own answer and select it as the correct one :) )
Comment: Share full log. It seems your subtitle track may be sparse in the beginning e.g. initial subtitle may have a timing of a minute or more.
Comment: Good point, I missed the notice just above the part I pasted initially. Added to the original message. I think the important point was ```Consider increasing the value for the 'analyzeduration' and 'probesize' options```
Comment: Unfortunately, even with ```ffmpeg -analyzeduration 10000M -probesize 10000M``` it doesn't work... same error. The file is only 1.4GB and less than one hour.
Answer: To force the decoder, -c:s webvtt must be set before the input: ffmpeg -analyzeduration 50M -probesize 50M -c:s webvtt -i input.mkv ...


GMAIL API Service Account - Validate a user

Question: When using Service Account to get domain wide access, is it possible to validate if the user is a valid user in the domain for which the Service Account is trying to access the data?
Comment: I didn't understand your use case clearly. So, do you want to check whether  users in the domain or valid or not? If this is the case, i don't think there can be invalid users in the domain. When service account wants to access data of user in domain, for the first time, user should allow you and provide their details where google validates user details to check whether they are valid or not. If user details are not correct, then google will throw an error. Let me know if you usecase is different.
Comment: Basically, in my application, before I try to fetch a user's data, I want to verify if the configured user is correct so that I can validate any misconfiguration
Answer: Use the Admin SDK Directory API users.get() request against the admin user who installed your app and the user in question. If the value of the customerId attribute is the same for both users, they're in the same Google Apps instance. If its not or if you get an error on the user in question, they're not.
Comment: I want to use the service account and b able to verify if the configured user is a valid one


How to return a promise with ngresource post

Question: Been trying to figure out how to return a promise with ngresource post. I can do it with $http but cant figure this out. I am getting .then is not defined error.
Controller
  $scope.addLocation = function (model) {
    var model = $scope.model;
    var promise = DocumentLocation.save(model);

    promise.then(function success(model) {
        console.log(model);
        $route.reload();
        $rootScope.close();
        notificationFactory.success();
    },
    function error(error) {
        console.error(error);
        notificationFactory.error();
    }
    )
};

Factory
app.factory('DocumentLocation', function ($resource) {
return $resource('/api/apiDocumentLocation/:id', { id: '@_id' }, {
    get: {
        method: 'GET', isArray: false // this method issues a PUT request
    }
}, {
    stripTrailingSlashes: false
  });
 });

Answer: Resource instances have a $promise attribute, they are not promises themselves. Just prefix your then call with $promise.
var promise = DocumentLocation.save(model);

  promise.$promise.then(function success(model) {
  ....

Comment: I think this is kind of misleading, since your `promise` is not a promise. I would suggest to change it to: `var promise = DocumentLocation.save(model).$promise;` and then just do `promise.then(...`
Answer: I believe you should call .$save() instead of .save()
$scope.addLocation = function (model) {
    var model = $scope.model;
    var promise = DocumentLocation.$save(model);

    promise.then(function success(model) {
        $route.reload();
        $rootScope.close();
        notificationFactory.success();
    },
    function error(error) {
        console.error(error);
        notificationFactory.error();
    }
    )
};

Refer This Link for more details.
Hope this could help you. Thanks.


how to integrate ASIHTTPRequest to iphone project

Question: <code> I am trying to add ASIHTTPRequest library to my iphone project
</code>
i followed these lines
<code>Integrating ASIHTTPRequest

ASIHTTPRequest is a powerful open source library written by Ben Copsey from All-Seeing Interactive (and he's a fellow cocos2d developer too!) It makes it easy to post data and files, and has tons of other great features too like cache support, easy access to HTTP headers, cookie support, and much more.

So let's add ASIHTTPRequest to our project. Take the following steps:

   1. Download the latest version of ASIHTTPRequest.
   2. Back in FBFun, right click FBFun under "Groups & Files", click "Add\New Group", and name the group "ASIHTTPRequest".
   3. Drag all of the files from the "pokeb-asi-http-request-xxx\Classes" to your new group. Make sure "Copy items into destination group's folder (if needed)" is checked, and click "Add".
   4. Repeat the above for the 2 files in "pokeb-asi-http-request-xxx\External\Reachability".
   5. Right click the Frameworks folder, and click "Add\Exisitng Frameworks…". Choose CFNetwork from the list, and click Add.
   6. Repeat the above for SystemConfiguration.framework, MobileCoreServices.framework, CoreGraphics.framework and libz.1.2.3.dylib (at the bottom of the list).
   7. Compile your project. If it works, you're integrated!

We'll explain about how ASIHTTPRequest works when we start to use it. But first, let's integrate the JSON Framework while we're at it.
</code>
but it not worked for me .while building it showing errors
<code>/Classes/Tests/GHUnitTestMain.m:32:26: error: GHUnit/GHUnit.h: No such file or directory
</code>
can anybody help me in this issue
Regards
Thanks
*Edit :
I fixed my problem by following these steps
http://allseeing-i.com/ASIHTTPRequest/Setup-instructions ,
If any one want to integrate ASIHTTPRequest just follow those steps :)*
Answer: You will need to add the XML library (it's missing in the instructions), and also make reference to it in the project header search paths with the following:
$(SDKROOT)/usr/include/libxml2


JavaScript Repetitive RegEx

Question: Consider my few input strings.

http://local.app.com/local/frontend/v12/#/abcde/
http://local.app.com/local/frontend/v12/#/abcde/!/fghij/
http://local.app.com/local/frontend/v12/#/abcde/!/ghijk/!/klmno/

I have written this regex which works fine for input string 1.
<code>(?:([a-zA-Z0-9.://_]*)(/#/(?=([a-zA-Z0-9]{5})/)))

Output:
http://local.app.com/local/frontend/v12/#/,http://local.app.com/local/frontend/v12,/#/,abcde
</code>
But when I extend it to support repetitive !/.../ place holder for input string 1,2 and 3, it doesn't work and gives empty string rather than token.
<code>(?:([a-zA-Z0-9.://_]*)(/#/(?=([a-zA-Z0-9]{5})/))(!/(?=([a-zA-Z0-9]{5})/))*)

Output:
http://local.app.com/local/frontend/v12/#/,http://local.app.com/local/frontend/v12,/#/,abcde,,
</code>
Answer: ?= captures in fact a position defined by what you specify after the ?=
It does not (also) capture whatever may match the specification of the lookaround (?=).
Try
(.+? # (/[a-zA-Z0-9]{5}/) (!/([a-zA-Z0-9]{5})/)* )
(hope I didn't make a typo, can't test it right now.)
This should capture the complete input, but the various captures inside give you access to the captured "tokens".
You can, in addition, give names to the various captures inside, making it easier to identify them in the match:
<code>(.+?#(/(?<tokenFirst>[a-zA-Z0-9]{5})/)(!/(?<tokenMore>[a-zA-Z0-9]{5})/)*)
</code>
Success
Comment: It doesn't return all !/token/ parts but just the last one.
Comment: Because I also don't want slashes. In next comment, I have updated your regex.
Comment: (?:.+?#/([a-zA-Z0-9]{5})/(?:!/([a-zA-Z0-9]{5})/)*)
Comment: I believe that in the named-variety that I suggested, you find the group "tokenFirst" capturing the first 'abcde' and in the 'tokenMore" group you find all the remaining "tokens"; I tested it, unless I've misread the output. (and they don't include the slashes). However, there are other captures in the regex give other parts of the total; it's a matter of just addressing the right groups in the match. Every () pair gives you a group/captures.
Comment: The token regex says "Invalid regular expression: /(.+?#(/(?[a-zA-Z0-9]{5})/)(!/(?[a-zA-Z0-9]{5})/)*)/: Invalid group"
Comment: strange, I've tetsted it again. It may depend on de regex-variety (engine) and settings. I wanted to upload a picture (screenshot), but don't know how to do that (if it's possible at all). I'll try in the response section, rather than here as "comment".
Comment: As should be clear from earlier comments/posts: there are different regex engines. jsregex had, deviating from many others, the FORWARD slash as special character. Any special characters need to be escaped when they are to be used as literals. Therefore, the appropriate adjustment of the expression that I provided is simply to escape the forward slashes.
Comment: I didn't get it. You used slashes to escape characters? But I see this constant there and not for escaping.
Comment: No, I did NOT use a slash as escape character. However, in YOUR regex engine (jsregex), the (forward) slash is a special symbol. I wanted to use it as a literal. In any regex engine where it is a special character, you need to escape it whenever you want to use it as a literal. The escaping is done by prepending it by the escape character (usually the backslash). So, rather than only the '/', one has to put '\/' . This tells the regex engine that it must treat the forward slash as a literal (a character to find in the string). Google on "regex tutorial" and read up, it's easy. [closed]
Answer:
Hope this will clarify my comment and earlier remarks.
Comment: I wrote your regex in jsFiddle so you may see the bug. http://jsfiddle.net/SVL9v/

JavaScript Repetitive RegEx


When you scroll up on my webpage on a phone there is white on the bottom. How can I fix this?

Question: I have a webpage that works fine on web browser, but when I visit the webpage on my phone and scroll my thumb up, I see white content where it shouldn't be.
This is the webpage before touching it:
1
This is webpage when I press the background and move my thumb up:

As you can see on the second image, at the bottom of the page, there is a white space between the footer and background image.
Here is the css:
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">


how to test electric dryer without 240V outlet?

Question: I received an electric laundry dryer that I want to test before installing. The new dryer is outdoors on the back porch, and a working electric dryer is installed in my basement, quite a distance away.
Without moving the dryer, is there any way to verify that it works properly? I have a DMM / continuity tester, access to an outdoor 120V outlet and can disassemble the new dryer. It appears in good condition apart from some lint:

drum and motor spin freely when pushed manually
no obvious physical damage or scorches
buttons and dials work normally

The troubleshooting guides I found explain how to resolve specific problems (replace heating element, change thermostat, change belt) but require connection to a standard 240V outlet. Basically, I'm looking for a way to verify that the dryer works OK before moving it. I don't have a 240V extension cord, and the run would be too long even if I did.
Thanks in advance!
Comment: Without knowing your distances, I think extension cord(s) could work. I'm sure nobody would counsel you to deliberately abuse the generous return policies of various blue or orange big box stores, but if perhaps you bought a few extension cords and then discovered that they weren't exactly to your liking, (and they were still in immaculate condition), then you could return them with a receipt and get a refund. (If you pay with a gift card, it can complicate your return, so cash or credit.)
Comment: You can test the heat element, and the thermal fuses. The heat element will be a low resistance, the thermal fuse should be close to 0 ohms, the motor should have fairly low resistance across the leads and mega ohms from the case to the leads. All this still won't tell you if the controls are functioning. Sounds like more work than taking it down and trying it.
Answer: First, a person selling a dryer without providing a 240V connection to demonstrate its performance, will naturally take a significant hit on his resale value.
Any real effort in this regard is going to require the schematic of the dryer and some electrical chops.  This forum doesn't have the capacity to convey those chops. Know your skill limits and work within them.  With that in mind...
If it has mechanical controls, you could do some "dry" testing by putting an ohmmeter across the various 120V and 240V pins while looking for the expected resistance changes as you operate its controls through their paces. You need to be able scratchpad Ohm's Law a bit to get a sense of what those resistances should be.
If you're willing to open up the controls, you could probe more deeply component by component.
If you want to get "hot", look at the schematic and try to isolate sections that you can test by powering one leg of the 240v, if it makes use of neutral.  Be very careful doing that, and positively ground chassis to actual ground, because on many dryers, especially those using NEMA 10/30 connectors, neutral is bonded to chassis -really! - and if you reverse hot/neutral, you can energize the chassis at 120v.
Or by using a 120/240 power adapting transformer - the 40 lb. transformers sold to Euros so they can run their appliances here.  You must set the dryer to fluff-only and not operate any heat setting.  Transformers are dumb and don't have thermal protection unless it is added, so they would die trying to supply 23A@240V which would be 46A on the 120V side, on wires made for 15A tops.  I'm quite sure you'd get a fuse blow or wire fry before you could shut it off.
All this is as dangerous as it sounds and in any case, seems like a lot of work.  Depending on how you value your time, it may be "cheaper" to buy enough 10/3 for a temporary run to a workable testing location.
Comment: Thanks for your help! the "fluff" setting never occurred to me. the dryer is rated for 120/240V, and the no-heat setting will show whether the motor works. then, I will test the heating element for conductivity after disconnecting the power.  just a bit more disclosure - I got a very good price, as in free :)


Will increasing spawn area increase guardian spawns? [1.11.2]

Question: I've been building this Guardian farm on a Multiplayer server.
I cleared out all the water and removed the temple itself.
Then, I built the glass box in the middle and filled it with water.
Guardians do spawn a bit, but I want to higher the rates if possible.
And yes, I have lit up all nearby caves.
So I was wondering: will making the box bigger affect/improve my spawn rates?
Or does every temple have a set amount of spawns that will be concentrated if the spawning area is smaller than the temple monument.
Thanks.
Screenshots
Answer: Increasing spawn area will increase spawns.
If you increase the spawn area, spawn checks that would normally fail will now succeed, but at a certain point, there will be so many guardians spawning at a time that more will be unable to spawn.
Comment: Okay, thanks.

Just out of curiosity; what sources do you have?
Comment: It was a video by Xisumavoid, don't remember the exact one, but I remember that in general, if you have a larger spawn area, more spawn tries will be successful, up to a point.
Answer: It wil have more than double the spawnrate if you put a roon on it. No direct sunlight is the key.