Q: Conditional Poisson Question b)What is the probability that 4 customers arrive between 8:30 and 9:00 a.m., if exactly 8
customers arrived between 8:00 and 9:00 a.m.?
In the main body of the question, I'm given that the interarrival process is exponentially distributed with mean of 5 minutes. so I found rate ƛ = 1/5 arrivals per min. But for the question, how do I use conditional probability while accounting for the overlap in time overlap? I have found the individual probabilities of 4 customers arriving between 8:30 and 9 and the probability that 8 arrive between 8:00 and 9:00. How would I go about solving the rest? Would I need to adjust the rate of 1/5 that I was using based on the conditional statement or would I completely disregard the condition based on the memoryless property of the Poisson process?
Thanks

A: I’ll assume that you intended to ask about the probability that exactly $4$ (not at least $4$) customers arrived during that half of the hour.
Given the condition, each of the $8$ arrivals has the same independent probability to have arrived in either of the two halves of the hour. Thus the probability that $4$ arrived in the latter half is
$$
\binom84\left(\frac12\right)^4\left(\frac12\right)^4=\binom84\left(\frac12\right)^8=\frac{35}{128}\;.
$$

A: Let $X$ and $Y$ be the random variables corresponding to the number of arrivals from 8:00 to 8:30 and from 8:30 to 9:00 respectively. Let $Z=X+Y$, so $Z$ has a Poisson distribution with $\lambda=12$.
Raikov's theorem states that we can decompose $Z$ into two independent Poisson distributions, each with $\lambda=6$ – which must be $X$ and $Y$. Then the desired probability is
$$\frac{P(X=Y=4)}{P(Z=8)}=\frac{P(X=4)P(Y=4)}{P(Z=8)}=\frac{(6^4e^{-6})^2}{12^8e^{-12}}\binom84=\frac{35}{128}$$

A: Theorem 5.2 from Introduction to Probability Models, Ninth Edition by Sheldon Ross, referring to a Poisson process $\{N(t), t \ge 0\}$, states:

Given that $N(t) = n$, the $n$ arrival times $S_1, \dots , S_n$ have
the same distribution as the order statistics corresponding to $n$
independent random variables uniformly distributed on the interval
$(0,t)$.

So the probability that exactly $4$ out of $8$ Uniform(8:00, 9:00)-distributed random variables will lie in the interval from 8:30 to 9:00 is
$$\binom{8}{4} \left( \frac{1}{2} \right)^4 \left( \frac{1}{2} \right)^4$$


Q: Bitbucket - push a new projet to my bitbucket repo I have the folder in my htdocs and I want to push it to an empty bitbucket repo.
So far I've followed the instructions on bitbuket website
git init
git remote add origin https://andradebuddha@bitbucket.org/musica.git

cd /path/to/my/repo
git remote add origin https://andradebuddha@bitbucket.org/musica.git
git push -u origin --all # pushes up the repo and for the first time

But And I'm getting this error
No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
Everything up-to-date

A: Solved - I've missed a step.
git add -A # to add the brand new folders structure

And
git commit -m 'inicio do projeto'

and finaly
git push -u origin all

A: Try specifying the branch as indicated in the error message.
instead of git push -u origin --all try git push origin master


Q: $(f(X))=f((X))$
Let $A, B$ be two rings and let $f: A \rightarrow B$ be an epimorphism.
Prove that if $f$ is an epimorphism,then for any subset $X \subseteq A,\ f((X))=(f(X))$.

I've been asked to do this exercise, so far I've got this:
Since $(f(X))=\bigcap\{I \trianglelefteq R \mid f(X) \subseteq I\}$ if $f((X))$ is an ideal then $(f(X)) \subseteq f((X)) $ becasue $(f(X))$ is the smallest ideal that contains $f(X)$
To prove that $f((X))$ is an ideal we show that $a+b \in f((X))$ and $ya\in f((X))$
For $a+b \in f((X))$ we take $a^{\prime}, b^{\prime} \in (X)$ such that $f(a^{\prime})=a$ and $f(b^{\prime})=b$. Then, given that f is a homomorphism
$$a+b=f(a^{\prime})+f(b^{\prime})=f(a^{\prime}+b^{\prime})$$
But, since (X) is an ideal,  $a^{\prime}+b^{\prime}\in (X)$. Therefore $a+b\in f((X))$
Now, for $ya\in f((X))$ we have that since f is surjective $\exists x\in (X)$ such that $f(x)=y$, therefore $$ya=f(x)f(a^{\prime})=f(xa^{\prime}) \in f((X))$$
Again, because $(X)$ is an ideal
Is this okay? Also, I'm stuck trying to prove that $f((X)) \subseteq (f(X))$
Can anybody help me?


Q: Does the phrase "orthogonal" mean the same thing when used in the terms "orthogonal function" and "orthogonal vector"? I was reading about Fourier series when I came across the term "orthogonal" in relation to functions.
http://tutorial.math.lamar.edu/Classes/DE/PeriodicOrthogonal.aspx#BVPFourier_Orthog_Ex2
I've never heard of this. The idea that two vectors are orthogonal makes sense to me because I can imagine, for instance, $\vec{a}=(1,0)$ and $\vec{b}=(0,1)$, such that $\vec{a} \cdot \vec{b} = (1)(0) + (0)(1) = 0$.
But no simple picture comes to mind for functions. Wikipedia wasn't very helpful for me.
http://en.m.wikipedia.org/wiki/Orthogonal_functions
Can someone explain what this concept is and give a simple example?
Remark:
My intuition says maybe intersecting lines would be an example of two orthogonal functions.
$f(x) = x$ $g(x) = -x$
But that's just a shot in the dark and I don't think that makes sense because the integral is just $\int -x^2 = - \frac{x^{3}}{3} + C$, which isn't zero.

A: The concept that connects the two notions of orthogonality is an inner product. I'll explain what an inner product is, what it means for orthogonality, and how this more-abstract version of orthogonality relates to the one you're familiar with.
To give a technically correct definition of an inner product I would need to define a vector space, but for this problem that might be overkill. Roughly speaking, a vector space is some collection whose elements can be added, subtracted, and multiplied by real numbers. The set of real-valued functions on $\mathbb R$, for instance, is a vector space, since we know how to add, subtract, and scale real-valued functions.
Note: from now on, when I say vector I'll mean an element of a vector space. So a function is a vector in the vector space of real-valued functions.
An inner product takes in two vectors and returns a scalar; in addition, it must satisfy the following axioms. Think of it as a way to multiply two vectors and return a scalar.

*

*$\langle ax_1+bx_2,y\rangle = a\langle x_1,y\rangle + b\langle x_2,y\rangle$ (linear in first variable [by the next axiom, also linear in the second variable])

*$\langle x,y\rangle=\langle y,x\rangle$ (symmetric)

*$\langle x,x\rangle = 0$ if and only if $x=0$ (positive-definite)

You are already familiar with one type of inner product: the dot product, which is an inner product on the vector space of row vectors. We say that two row vectors $\vec a$ and $\vec b$ are orthogonal if $\vec a\cdot\vec b=0$. This suggests that a way to make sense of orthogonality in general vector spaces:

Two vectors $v$ and $w$ are orthogonal if $\langle v,w\rangle=0$.

Fourier series start to enter the picture when we look at the vector space of continuous, real-valued functions defined on $[-\pi,\pi]$, say. We can make an inner product on this space by defining
$$
\langle f,g\rangle = \int_{-\pi}^{\pi}f(x)g(x)\,dx.
$$
(Do you believe that this is an inner product?) Under this inner product, $\sin(x)$ and $\cos(x)$ are orthogonal functions. All I mean is that
$$
\int_{-\pi}^\pi \cos x\sin x\,dx = 0,
$$
which is true because $\cos x\sin x = \frac12 \sin 2x$. It is possible to show more generally that
$$
\int_{-\pi}^\pi \cos(nx)\cos(mx)\,dx = \int_{-\pi}^\pi \sin(nx)\sin(mx)\,dx = 0
$$
if $n\neq m$, and
$$
\int_{-\pi}^\pi \sin(nx)\cos(mx)\,dx = 0
$$
always. ($m$ and $n$ are integers.)
Here's another example: the functions $1$ and $x$ are orthogonal. So are the functions $x^n$ and $x^m$ whenever $n+m$ is odd (and $n$ and $m$ are nonnegative). Why?

A: Consider two vectors in $3$-dimensional space:
\begin{align}
& (2,3,7) \\[6pt]
& (1,-3,1)
\end{align}
If you draw an accurate picture of two arrows pointing outward from the origin, they look as if they are at right angles to each other, as indeed they are.  But what if we view the same array of numbers as three points in the plane:
$$
\left(\begin{array}{c} 2 \\ 1 \end{array}\right), \left(\begin{array}{c} 3 \\ -3 \end{array}\right), \left(\begin{array}{c} 7 \\ 1 \end{array}\right)
$$
Then they look like this:
$$
\begin{array}{cccccc}
\bullet & & & & & \bullet \\  \phantom{\bullet} \\  \phantom{\bullet} \\  \phantom{\bullet} \\
& & \bullet
\end{array}
$$
Where is the orthogonality now?  When you look at, for example, the sine and cosine functions, you are looking at something like this second graph, where the geometric relation of orthogonality is not visible.  It becomes visible only when the shapes of the graphs are not visible: just plot the point $(a,b)$ for $a\cos x+b\sin x$ and $(c,d)$ for $c\cos x+d\sin x$, and see whether the vectors $(a,b)$ and $(c,d)$ are orthogonal to each other.
But next we have the problem of a space of many dimensions, which our ordinary sense don't help us see.  But lots of things about the geometry are the same, and that geometry can be applied to such spaces.

A: Consider a vector space of functions.  To fix our ideas, let's say it's the space of all continuous real-valued functions on domain $-\pi\le x\le\pi$.  We define the "dot product"
$$f\cdot g=\int_{-\pi}^\pi f(x)g(x)\,dx\ .$$
It seems reasonable to call this a "dot product" because it shares the fundamental properties of the usual dot product of vectors in $\Bbb R^n$:

*

*$f\cdot g=g\cdot f$;

*$(f_1+f_2)\cdot g=(f_1\cdot g)+(f_2\cdot g)$;

*$(\lambda f)\cdot g=\lambda(f\cdot g)$;

*$f\cdot f\ge0$;

*if $f\cdot f=0$ then $f=0$: note that "$f=0$" means "$f(x)=0$ for all $x$".

I am sure you can very easily prove the first four of these, the fifth is a little harder.  Since we are treating this definition as being similar to a dot product, it makes sense to define two functions to be orthogonal if the dot product is zero.  For eaxmple,
$$(\cos x)\cdot(\cos2x)=\int_{-\pi}^\pi \cos x\cos2x\,dx=0$$
(exercise: explain why the integral is zero), so $\cos x$ and $\cos2x$ are orthogonal with respect to this dot product.
Comments

*

*In this context, the "dot product" is usually referred to as an inner product and written $\langle f,g\rangle$ instead of $f\cdot g$.

*It is possible to define different inner products for the same space of functions; $\cos x$ and $\cos2x$ might not be orthogonal with respect to a different inner product.

*I doubt that you can visualise orthogonality of functions by means of any simple picture.  However, if you continue to study Fourier series, you will soon see why orthogonality of functions is important.

Hope this helps!!


Q: How to divide one row in various? I have a column data in a postgresql table that receive data like this: |A|C|F|L|T|U|
The others columns are name, date
Example:
NAME    | DATE       | DATA
ALYSSON | 2019-01-01 | |A|B|C|

How to create a select that return:
NAME    | DATE       | DATA
ALYSSON | 2019-01-01 | A
ALYSSON | 2019-01-01 | B
ALYSSON | 2019-01-01 | C

A: You can use string_to_array along with unnest to break your data into first an array and then separate rows.
select * FROM (
  select name, date, unnest(string_to_array(data, '|')) as data from stuff
) AS sub
WHERE sub.data != '';

The WHERE clause is required to remove the empty strings at the beginning and end of your data.


Q: Is it possible to define a differentiable manifold structure on a cone? A cone is a topologic manofold but can we define  a differentiable manifold structure on it?

A: The projection $p$ from the cone onto the $x,y$-plane is a homeomorphism. So you can use $p$ to pull back the differential manifold structure on the $x,y$-plane and you get a differential manifold structure on the cone.


Q: Can HTTP-header LAST-UPDATED be trusted? I have been using Rex Swain's HTTP Viewer to verify that none of the texts on a certain webpage has been changed recently.
The response was: "Code last updated 21 January 2012", so as I understand it, I can't really assume that anything was actually changed on that date but is it safe to assume that none of the texts on the webpage has been changed since that date?
I am not an HTTP expert, so please use layman terms where possible, thanks :-)
BR

A: A web server typically uses the corresponding file's last updated attribute as the value for the HTTP Last-Modified header, so in general it can be trusted, but it's always possible that the date is wrong, for whatever reason.
The Last-Modified header is usually used for caches, to populate the If-Modified-Since header in subsequent requests.


Q: Disable Apache logging completely I have an old server running online with over 250 sites on it I am not sure, but maybe too many logfiles in the apachelog are slowing down the server?
Now since I don't need the Apache logs, How do I disable all logging completely?

A: I disabled all vhosts logging with:
find /etc/apache2/sites-enabled/* -exec sed -i 's/#*[Cc]ustom[Ll]og/#CustomLog/g' {} \;
find /etc/apache2/sites-enabled/* -exec sed -i 's/#*[Ee]rror[Ll]og/#ErrorLog/g' {} \;

and commented out in /etc/apache2/apache2.conf
#ErrorLog ${APACHE_LOG_DIR}/error.log

and added
ErrorLog /dev/null

Restart apache gracefully:
apache2ctl graceful

I have a lot of logs in different places so I can watch the result with
 tail -n 1 -f /var/kunden/logs/*log /var/kunden/logs/*log /var/log/apache2/*log

If you want to enable all logging into one file you can edit /etc/apache2/apache2.conf again and add those lines:
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log  "%h %v %l %u %t \"%r\" %>s %b"

and comment out
#ErrorLog /dev/null

A: For all who have the  other_vhosts_access.log file and want to disable it too, comment out the line:
#CustomLog ${APACHE_LOG_DIR}/other_vhosts_access.log vhost_combined

in:
/etc/apache2/conf-available/other-vhosts-access-log.conf

or disable this config file:
sudo a2disconf other-vhosts-access-log


Q: Make a fixed position element appear behind a static position element How can you make an element that has a position: fixed display behind an element with position: static? Changing z-index doesn't seem to matter since they are not absolute.

A: You can use negative z-index on the fixed element.

This is fixed

This is static

#fixed {
    position:fixed;
    z-index:-1;
}

Fiddle Demonstration


Q: TinyMCE editor dislikes being moved around On a page I have, I need to move TinyMCE editors in the DOM tree once in a while. However, for some reason, the editor doesn't like it: it clears itself completely and becomes unusable. As far as I can see, this behavior is consistent between Safari 4 and Firefox 3.6, but not Internet Explorer 7/8. Here's an example.
It truly is annoying to do something that works in Internet Explorer but not with more appreciable browsers. Is there something I missed in the docs about never trying to move an editor in the DOM tree? Is there some kind of workaround?

A: This is a browser bug/issue not a problem with TinyMCE. It's impossible to retain iframe contents in some browsers since once you remove the node from the dom the document/window unloads. I suggest first removing the editor instance then re-adding it instead of moving it in the DOM.

A: Had the same issue and here's how I resolved it...
Create the issue
I use jquery to move the dom element that contains the tinymce editor that causes it to lose all it's contents:
$('.form-group:last').after($('.form-group:first'))

After this point, the editor's iframe contents are removed.
The Solution
var textareaId = 'id_of_textarea';
tinyMCE.get(textareaId).remove();
tinyMCE.execCommand("mceAddEditor", false, textareaId);

There are times when the editor will add the iframe back, but not be visible.  If that's the case, unhide the container:
$textarea = $('#' + textareaId)
$textarea.closest('.mce-tinymce.mce-container').show()

Note, this is using tinymce 4.x.


Q: Why was Frodo able to go to the Blessed Realm? All along, I had the impression that, as reward for resisting the One Ring and contributing towards the journey to its ultimate demise, Bilbo (for finally abandoning it), Frodo (for having done the most to carry the burden for the actual journey) and Sam (for carrying it when Frodo couldn't and successfully resisting temptation to take over as the main bearer) were granted passage to spend the remainder of their mortal days in the Undying Lands, where the Blessed Realm can help heal/protect their souls from the dark taint of the Ring until the end of their days.
I just found Arwen's wiki article, though, and a passage quotes thus:

After marrying Aragorn, she bestowed upon Frodo Baggins a gift: Her place on the ships to Valinor.

This implies that Frodo was originally ineligible for entry into the Undying Lands, until Arwen gave him her ticket.
Is my prior impression wrong? I think it came from many years ago, the one time I read RotK. If I am correct, then why does the quoted passage seem to conflict it? Did I misinterpret it, or is it a movie vs book thing? If I am wrong and the quoted passage is correct, then:

*

*Why can Bilbo and Sam go to the Undying Lands? Whose place on the ships did they take?

*Arwen already gave up her immortality to be with Aragorn. She is known to have told her father Elrond: "There is now no ship that would bear me hence". I don't think the choice of abandoning immortality can be walked back once made, so why did she have a seat to offer to anyone by that point?

*Even if she still held a place on the ships to the West, is it her place to offer it to anyone?


Q: Subsetting a vector base on another vector I have 2 input vectors, iv1 and iv2, as shown below. I would like to separate the elements of the second vector according to elements of the first. It works like this: The values in iv2 between the first 2 values of iv1 are stored in ov1, the values in iv2 between the second and third values of iv1 are stored in ov2, and so on. Note: The values in iv1 and iv2 are already in ascending order. Any thoughts please?
Input:
iv1 <- c(100, 200, 300, 400, 435)
iv2 <- c(60, 120, 140, 160, 180, 230, 250, 255, 265, 270, 295, 340, 355, 401, 422, 424, 430)

Desired output:
ov1 = c(120, 140, 160, 180)
ov2 = c(230, 250, 255, 265, 270, 295)
ov3 = c(340, 355)
ov4 = c(401, 422, 424, 430)

A: As @RonakShah suggested, the most efficient way in this case may be this:
split(iv2, cut(iv2, breaks = iv1,labels = paste0('ov',1:4)))

Output:
$ov1
[1] 120 140 160 180

$ov2
[1] 230 250 255 265 270 295

$ov3
[1] 340 355

$ov4
[1] 401 422 424 430


Q: Jacobi identity and Leibniz rule - the same thing? Is there any formal connection between the Jacobi identity
$$[[a,b],c] = [a,[b,c]] + [b,[c,a]]$$
and the Leibniz rule
$$d(a \cdot b) \cdot c = a \cdot d(b) \cdot c + b \cdot c \cdot d(a) ~\text{?}$$

A: Yes, with $d=\operatorname{ad}(x)(y)$, the adjoint operator in a Lie algebra, defined by $\operatorname{ad}(x)(y)=[x,y]$.
Then the Jacobi identity is equivalent to the statement that the operator $d$ satisfies the Leibniz rule, with $x.y=[x,y]$:
$$
    d([a,b])=[d(a),b]+[a,d(b)]
$$
Applying $\operatorname{ad}(c)$ yields $[d([a,b]),c]=[[d(a),b],c]+[[a,d(b)],c]$.


Q: Unable to invalidate Asp.Net Session during IdP initiated Single LogOut with WSO2 we are implementing a Single Sign On process using WSO2 Identity Server. We have both Microsoft and Java web applications involved and we are facing a problem during the Single LogOut processing with Microsoft based web apps. The issue is related to session invalidation on Identity Provider initiated SLO.
This is the scenario:

*

*WSO2 Identity Server with a single Identity Provider configured

*an Asp.Net MVC application using ComponentSpace SAML2 assembly and Forms authentication marking controllers with the [Authorize] attribute to ensure that users are authenticated to access them.

*the DEMO Java Web application provided by WSO2 to test SSO

The login process works fine. We get a session ID from WSO2 and the user is authenticated landing on WSO2 login form in the first app, and transparently in the sencond one.
In the Asp.Net webapp, when a successfull login occurs, we authenticate the user to access [Authorize] marked controllers calling FormsAuthentication.SetAuthCookie(userName, false); . When the user logout from one of the apps, WSO2 sends a SLO request to other partecipants on a configured URI. When this request is reveived by the Microsoft one, we call the FormsAuthentication.SignOut(); method but the session is not destroyed. If the user refresh the browser page its User.Authenticated property is still True so he can still access [Authorize] marked controllers. This makes sense in my opinion because the caller is WSO2 and not the user browser.
We performed some investigation in the code of the JAR provided by WSO2 for Java applications and it creates a filter on Tomcat implementing a singleton to store WSO2 Session ID relation with Session objects each time a success login operation occurs. When WSO2 request a SLO the filter gets WSO2 Session ID as parameter, accesses the singleton HashTable to retrieve the Session object and calls the Session.Invalidate() method of the session object. If the user refreshes the browser, he gets redirected to login page. We tryied to implement something similar on Asp.Net side but even if we get the Session object on server side and call the Session.Abandon() method nothing happens when the user refresh the browser. He is still marked as authenticated.
I am not very familiar with Cookies and I have the feeling that is something related to them.
Had anyone faced a similar issue?
Any advice or suggestion will be very appreciated.
Thanks

A: Calling FormsAuthentication.SignOut should clear the authentication cookie. I suggest capturing the HTTP flow and confirming whether the authentication cookie has been deleted. The default name for the authentication cookie is .ASPXAUTH. Alternatively it will be the name specified in your web.config's  section. For example, forms name="mycookie" would rename the cookie to mycookie. You shouldn't have to delete the ASP.NET_SessionId session ID cookie.


Q: How to add fail to ant macrodef I created a macro to search for a file in a number of directories. That part is working.
Now I'm trying to add fail to the macro if no file is found but this gives me an error
macrodef doesn't support the nested "fail" element.
Is there a way to achieve this ?
<macrodef name="searchfile">
    <attribute name="file" />
    <attribute name="path" default="${custom.buildconfig},${wst.basedir}" />
    <attribute name="name" />
    <attribute name="verbose" default="false" />
    <sequential>
        <first id="@{name}">
            <multirootfileset basedirs="@{path}" includes="@{file}" erroronmissingdir="false" />
        </first>
        <property name="@{name}" value="${toString:@{name}}" />
        <echo>property @{name} ${@{name}}</echo>
    </sequential>
    <fail message="${file}was not found in ${custom.buildconfig},${wst.basedir}">
        <condition>
            <equals arg1="${@{name}" arg2=""/>
        </condition>
    </fail>
</macrodef>

A: Credits to martin clayton for his comment, moving fail in the sequential fixes the issue.
   <macrodef name="searchfile">
        <attribute name="file" />
        <attribute name="path" default="${custom.buildconfig},${wst.basedir}" />
        <attribute name="name" />
        <attribute name="verbose" default="false" />
        <sequential>
            <first id="@{name}">
                <multirootfileset basedirs="@{path}" includes="@{file}" erroronmissingdir="false" />
            </first>
            <property name="@{name}" value="${toString:@{name}}" />
            <echo>property @{name}=${toString:@{name}}</echo>
            <fail message="@{file} was not found in ${custom.buildconfig},${wst.basedir}, customdir=${customdir}">
                <condition>
                    <equals arg1="${toString:@{name}}" arg2=""/>
                </condition>
            </fail>
        </sequential>
    </macrodef>


Q: POST to https://www.sandbox.paypal.com/cgi-bin/webscr gives 500 error , Classic asp I am working on classic asp to create donation site and payment gateway is paypal.
I have implemented IPN and paypal is sending notification on that notify_url that i pass with form.
Also payment is also working correctly i.e i can get payment history and IPN history in my sandbox paypal account.
Now the problem is in IPN handler file, when i use sandbox.paypal url to post back to paypal, it give 500 error. Same thing is not true for live paypal url.
Below it the code that will explain better.
Test Form
<form action="zPaypalTest.asp" method="POST">
<input name="mc_gross" type="hidden" value="500.00" />
<input name="custom" type="hidden" value="some custom data" />
<input name="address_status" type="hidden" value="confirmed" />
<input name="item_number1" type="hidden" value="6" />
<input name="item_number2" type="hidden" value="4" />
<input name="payer_id" type="hidden" value="FW5W7ZUC3T4KL" />
<input name="tax" type="hidden" value="0.00" />
<input name="address_street" type="hidden" value="1234 Rock Road" />
<input name="payment_date" type="hidden" value="14:55 15 Jan 07 2005 PST" />
<input name="payment_status" type="hidden" value="Completed" />
<input name="address_zip" type="hidden" value="12345" />
<input name="mc_shipping" type="hidden" value="0.00" />
<input name="mc_handling" type="hidden" value="0.00" />
<input name="first_name" type="hidden" value="Jason" />
<input name="last_name" type="hidden" value="Anderson" />
<input name="mc_fee" type="hidden" value="0.02" />
<input name="address_name" type="hidden" value="Jason Anderson" />
<input name="notify_version" type="hidden" value="1.6" />
<input name="payer_status" type="hidden" value="verified" />
<input name="business" type="hidden" value="paypal@emailaddress.com" />
<input name="address_country" type="hidden" value="United States" />
<input name="num_cart_items" type="hidden" value="2" />
<input name="mc_handling1" type="hidden" value="0.00" />
<input name="mc_handling2" type="hidden" value="0.00" />
<input name="address_city" type="hidden" value="Los Angeles" />
<input name="verify_sign" type="hidden" value="AlUbUcinRR5pIo2KwP4xjo9OxxHMAi6.s6AES.4Z6C65yv1Ob2eNqrHm" />
<input name="mc_shipping1" type="hidden" value="0.00" />
<input name="mc_shipping2" type="hidden" value="0.00" />
<input name="tax1" type="hidden" value="0.00" />
<input name="tax2" type="hidden" value="0.00" />
<input name="txn_id" type="hidden" value="TESTER" />
<input name="payment_type" type="hidden" value="instant" />
<input name="last_name=Borduin" type="hidden" />
<input name="payer_email" type="hidden" value="test@domain.com" />
<input name="item_name1" type="hidden" value="Rubber+clog" />
<input name="address_state" type="hidden" value="CA" />
<input name="payment_fee" type="hidden" value="0.02" />
<input name="item_name2" type="hidden" value="Roman sandal" />
<input name="invoice" type="hidden" value="123456" />
<input name="quantity" type="hidden" value="1" />
<input name="quantity1" type="hidden" value="1" />
<input name="receiver_id" type="hidden" value="5HRS8SCK9NSJ2" />
<input name="quantity2" type="hidden" value="1" />
<input name="txn_type" type="hidden" value="web_accept" />
<input name="mc_gross_1" type="hidden" value="0.01" />
<input name="mc_currency" type="hidden" value="USD" />
<input name="mc_gross_2" type="hidden" value="0.01" />
<input name="payment_gross" type="hidden" value="0.02" />
<input name="subscr_id" type="hidden" value="PP-1234" />
<input name="test" type="submit" value="test" />
</form>

MY IPN handler File
zPaypalTest.asp
                <%@  language="VBScript" %>
            <%
            Dim Item_name, Item_number, Payment_status, Payment_amount
            Dim Txn_id, Receiver_email, Payer_email
            Dim objHttp, str
            DIM ApplicationRootPath
            ApplicationRootPath = Request.ServerVariables("APPL_PHYSICAL_PATH")

            ' read post from PayPal system and add 'cmd'
            str = Request.Form& "&cmd=_notify-validate"

            ' post back to PayPal system to validate
            set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
            'Set objHttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
            ' set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP.4.0")
            'set objHttp = Server.CreateObject("Microsoft.XMLHTTP")
            'objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr", false
            objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false
            'objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false
            'Send response message back to paypal'

            'objHttp.open "POST", "https://ipnpb.paypal.com/cgi-bin/webscr", false
            'objHttp.open "POST", "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", false

            Response.write "IPN-Sand"
            Response.write "<br/>"

            objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
            objHttp.Send str

            Response.write objHttp.status

            if (objHttp.status <> 200 ) then
            ' HTTP error handling
            elseif (objHttp.responseText = "VERIFIED") then
            Response.write "VERIFIED"
            elseif (objHttp.responseText = "INVALID") then
            Response.write "INVALID"
            else
            Response.write "ERROR"

            end if
            set objHttp = nothing
            %>

Above is the example file.
Here is the code sample that i used. https://github.com/paypal/ipn-code-samples
I test it on localhost IIS and it work fine there too.
So only problem is when i use ,
objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false

OR
objHttp.open "POST", "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", false

I get 500 server error and this 500 server is only on my server that runs both in http or https, but in localhost IIS it works.
Also
If i change that url to live url
objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr", false

OR
objHttp.open "POST", "https://ipnpb.paypal.com/cgi-bin/webscr", false

It works.
If i just browse that page in my browser in my server i.e https://myserver.com/zPaypalTest.asp, it gives error when using sandbox url only.
I am not able to think what is the error here. Why it gives 500 error.
I will be very thankful if any one could give me any clue what's wrong.


Q: Unary operators, binary expression tree and shunting yard algorithm I am writing the mathematics expression solver which takes infix expression and solves them, both binary expression tree and shunting-yard are doing good for me (I have even solved the problem of handling unary and ternary operators). Encountered an issue with trigonometric functions. When I write 45sin or (45)sin or (44+1)sin, shunting-yard converts it to valid Reverse Polish Notation(RPN) and evaluation is successful. Though the valid infix expression is sin(44+1) or sin45 + 1. Please suggest to solve this pr1oblem.
Here is the java code from class ExpressionEval which converts infix to RPN.
public String infixToPostFix2(String[] expression)
{
    String val = "";

    if (expression == null || expression.length <= 0)
    return "";

    Stack<String> stack = new Stack<String>();
    ArrayList<String> exp = new ArrayList<String>();

    for (String token : expression)
    {
        if (OperatorList.isOperator(token))
        {
            Operator o1 = OperatorList.getOperator(token);
            Operator o2 = null;
            while (!stack.empty() && OperatorList.isOperator(stack.peek()))
            {
                o2 = OperatorList.getOperator(stack.peek());
                if (    (o1.getAssociativity() == Associativity.LEFT && o1.lessThanEqual(o2))
                    || (o1.getAssociativity() == Associativity.RIGHT && o1.lessThan(o2))
                    )
                {
                    exp.add(stack.pop());
                    continue;
                }
                break;
            }
            stack.push(token);
        }
        else if(OperatorList.isLeftParenthesis(token))
        {
            stack.push(token);
        }
        else if (OperatorList.isRightParentheis(token))
        {
            while(!OperatorList.isLeftParenthesis(stack.peek()))
            {
                if (stack.empty())
                {
                    this.error = Error.MISMATCHED_PARANTHESIS;
                    return ""; //Mismatched paranthesis
                }
                exp.add(stack.pop());
            }

            stack.pop();//Pop off the left paranthesis but not move to output
        }
        else //Operands
        {
            exp.add(token);
        }
        }

        while(!stack.empty())
        {
        String s = stack.pop();
        if (OperatorList.isParanthesis(s))
        {
            this.error = Error.MISMATCHED_PARANTHESIS;
            return "";
        }
        exp.add(s);
    }

    postfixExpression = new String[exp.size()];
    int index = 0;
    for (String elem : exp)
    {
    postfixExpression[index++] = elem;
    }

    CalcDebug.printArray(postfixExpression);

    return val;
}

Once we have post-fix expression the evaluation is done in this function of ExpressionEval class
 public double evaluateExpression(String[] postfixExpression) {

    CalcDebug.Debug("evaluateExpression()");

    double val = 0.0;
    if (postfixExpression == null || postfixExpression.length <= 0)
        return val;

    Stack<String> operationStack = new Stack<String>();

    CalcDebug.printArray(postfixExpression);

    for (String elem : postfixExpression) {

        CalcDebug.Debug("elem = " + elem);

        if (!OperatorList.isOperator(elem)) {
            operationStack.push(elem);
        } else {
            double arg0 = 0.0;
            double arg1 = 0.0;
            double arg2 = 0.0;

            OperatorType t = OperatorList.getOperatorType(elem);
            if (t == OperatorType.BINARY) {
                arg1 = Double.parseDouble(operationStack.pop());
                arg0 = Double.parseDouble(operationStack.pop());
                val = CalculatorBrain.performCalculation(elem, arg0, arg1);
            } else if (t == OperatorType.UNARY) {
                arg0 = Double.parseDouble(operationStack.pop());
                val = CalculatorBrain.performCalculation(elem, arg0);
            } else if (t == OperatorType.TERNARY) {
                arg2 = Double.parseDouble(operationStack.pop());
                arg1 = Double.parseDouble(operationStack.pop());
                arg0 = Double.parseDouble(operationStack.pop());
                val = CalculatorBrain.performCalculation(elem, arg0, arg1,
                        arg2);
            }
            operationStack.push(Double.toString(val));
        }

        CalcDebug.printStack(operationStack);
    }

    val = Double.parseDouble(operationStack.pop());

    CalcDebug.Debug("val = " + val);

    return val;
}

Operator class is somewhat similar to this.
package com.studentscalculator;

import com.studentscalculator.OperatorComparator.OPERATOR_PRIORITY;

public class Operator
{

    public enum OperatorType
    {
        UNARY, BINARY, TERNARY
    }

    public enum Associativity
    {
        LEFT, RIGHT
    }

    private String operator;
    public String getOperator(){return operator;}
    public void setOperator(String operator){this.operator = operator;}

    private int order;
    public int getOrder(){return order;}
    public void setOrder(int order){this.order = order;}

    private OperatorType type;
    public OperatorType getType(){ return type; }
    public void setType(OperatorType type){ this.type = type; }

    private Associativity associativity;
    public Associativity getAssociativity(){ return associativity;}
    public void setAssociativity(Associativity associativity){ this.associativity = associativity; }

    //Constructors
    public Operator(String operator)
    {
        this.setOperator(operator);
        this.setOrder(OperatorList.getOperatorOrder(operator));
        this.setType(OperatorList.getOperatorType(operator));
        this.setAssociativity(OperatorList.getOperatorAssociativity(operator));
    }

    public Operator(String operator, int order)
    {
        this.setOperator(operator);
        this.setOrder(order);
        this.setType(OperatorList.getOperatorType(operator));
    }

    public Operator(String operator, int order, OperatorType t)
    {
       init(operator, order, t, Associativity.LEFT);
    }

    public Operator(String operator, int order, OperatorType t, Associativity a)
    {
       init(operator, order, t, a);
    }

    void init(String operator, int order, OperatorType t, Associativity a)
    {
        this.setOperator(operator);
        this.setOrder(order);
        this.setType(t);
        this.setAssociativity(a);
    }

    public boolean lessThanEqual(Operator arg0)
    {
        int val = -(this.order - arg0.order);
        if (val <= 0)
            return true;
        else
            return false;
    }

    public boolean lessThan(Operator arg0)
    {
        int val = -(this.order - arg0.order);
        if (val < 0)
            return true;
        else
            return false;
    }

    @Override
    public String toString()
    {
        String val = String.format("Operator = %s : Order %s", getOperator(), getOrder());
        return val;
    }

}


Q: AnimationDrawable Thread skipping frames I am in an Activity which must play an AnimationDrawable (a 'loading' animation) while the rest of the content loads.
I started the animation in another thread since animations tend to give a lot of work to the main thread, however the animation can't be displayed correctly, and the Logcat shows several times to have skipped 40 frames or so.
I'll post the code tomorrow, sorry for the delay.
Meanwhile what can be causing this? all the thread has inside is the start method for the animation drawable.

A: You should not run animation off of the UI thread ("main" thread) - you should load your content in another thread by using a Loader (or something similar) and play the animation on the UI thread. That's what it's for.
Here are official thread guidelines:

Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread

More here


Q: Has the generic version of HttpResponseMessage been removed from the ASP.NET WebApi? I just finished installing VS 2012 RC and have started working with the ASP.NET Web API. I am basing my work on some tutorials from PluralSight which I've been using as reference.
In every tutorial and article which I've used, I notice that they are using a generic version of HttpResponseMessage in the return type of Action, but to my surprise this object was not available to me while coding. I thought perhaps the issue was just an incorrect namespace reference, but that does not seem to be the case.
Can anyone point me toward some source code or reference material on how to utilize the generic HttpResponseMessage object that PluralSight uses in their videos?

A: yes i was also looking through the same thing.. the generic version of the HttpResponseMessage was remove recently.. because it was not type safe

A: Searching for the answer i found this article
and it states that the generic version has been removed
so now just mention the return type to be of type HttpresponseMessage and when actually returning the response use Request.CreateResponse<T>(params);


Q: Inconsistent ParseExeption with Data Format in Java I wrote a simple Util method to convert a String in Java to util.Date. What I am not able to figure out is why the method works for the first input, and fails for the second one, given that the inputs are identical:
Code:
package util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate {

    public Date getDateFromString(String strDate, String dateFormat) {

        DateFormat df = new SimpleDateFormat(dateFormat);
        Date date = null;

        try {

            date = df.parse(strDate);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println(date);

        return date;
    }

    public static void main(String[] args)  {

        StringToDate s2d = new StringToDate();

        s2d.getDateFromString("12-18-11, 10:36 AM","MM-dd-yy, hh:mm a");
        s2d.getDateFromString("02-04-12, 01:17 PM","MM-dd-yy, hh:mm a");
    }
}

Output:
Sun Dec 18 10:36:00 CET 2011
null
java.text.ParseException: Unparseable date: "02-04-12, 01:17 PM"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at util.StringToDate.getDateFromString(StringToDate.java:17)
    at util.StringToDate.main(StringToDate.java:33)

Logically, the output should've been Sat Feb 04 13:17:00 CET 2012 going by the first output. Why is the ParseException being thrown?
EDIT: The following two lines work correctly:
s2d.getDateFromString("02-04-12", "MM-dd-yy");
s2d.getDateFromString("01:17 PM", "hh:mm a");

Output:
Sat Feb 04 00:00:00 CET 2012
Thu Jan 01 13:17:00 CET 1970

But the exception happens when I try to parse both date and time together.

A: Do you have a non-breaking space, or some other Unicode space character, somewhere in either your date string or format mask?
I was able to reproduce your error if I replaced one of the spaces in the second of your date strings with a non-breaking space, such as Unicode character 160.


Q: How to import moment.js angular2 I'm trying to import moment.js into my angular2 application.
First of all I have followed this guide, and I've found this answer but even if I've tried to follow the proposed solutions I'm still unable to import moment.js.
The package is present, and in fact my IDE (visual studio) is able to find the moment.d.ts file without any problem, but when I run my application with npm start, I get this two errors in the console:

"NetworkError: 404 Not Found - http://localhost:3000/node_modules/moment/"
  /node_m...moment/
  Error: patchProperty/desc.set/wrapFn@http://localhost:3000/node_modules/zone.js/dist/zone.js:769:27
      Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:356:24
      Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:256:29
      ZoneTask/this.invoke@http://localhost:3000/node_modules/zone.js/dist/zone.js:423:29
Error loading http://localhost:3000/node_modules/moment as "moment" from 'my file'

I've tried to import moment in this way
import * as moment from 'moment'

and in this way to
import * as moment from 'moment/moment.d'

but nothing, I'm still get the error. My SystemJs'map property is this one
 var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'services':                   'app/service',
    'moment':                     'node_modules/moment',//moment.js
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
 };

If I try to install with typings i get this error:

Typings for "moment" already exist in "node_modules/moment/moment.d.ts". You should let TypeScript resolve the packaged typings and uninstall the copy installed by Typings

so I had uninstalled it, and retype the commands, well I get this error

typings ERR! message Unable to find "moment" ("npm") in the registry.

so is ther a way to get out from this dilemma?

A: Firstly, install the moment package via npm:
npm install moment --save

Secondly change your systemjs config (2 lines):
(function (global) {
  // map tells the System loader where to look for things
  var map = {
    'app': 'app', // 'dist',
    '@angular': 'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs': 'node_modules/rxjs',
    'moment': 'node_modules/moment', <== add this line
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app': { main: 'main.js', defaultExtension: 'js' },
    'rxjs': { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    'moment': { main: 'moment.js', defaultExtension: 'js' } <== add this line
  };

Then you can use it:
import * as moment from 'moment';

Typings will be available from node_modules/moment/moment.d.ts


Q: Get dictionary values as List I know this is asked earlier, but I tried but could not help.
I have below dictionary, want to convert to List, What is the best way to convert to List
dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}

dList = list(dct.values())

Result:
[['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']]

I need splitted List:
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']

Later, I want to compare list of items in "dList" with another List.

A: If you know that the list is the value associated to the 'result' key, simply call dct['result'].
>>> dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct
{'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct['result']
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']

Converting the values to a list is unneeded, inefficient and might return the wrong value if your dict has more than 1 (key, value) pair.

A: Your dictionary have only one value and that itself is a list of elements. So just call the result key and you will get the list value.
If you want the list from your code add the index [0] like,
dList = list(dct.values())[0]
Hope this helps! Cheers!


Q: How to loop between two dates I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and ending with the selected end date, obviously including all of the dates inbetween, regardless of how many days are inbetween the selected start and end dates.
Below I have the beginning of the method which takes the date strings and converts them into DateTime variables so that I can make use of the DateTime calculation functions. However, I cannot seem to work out how to calculate all of the dates inbetween the start and end date?
Obviously the first stage is to subtract the start date from the end date, but I cannot calculate the rest of the steps.
Help appreciated greatly,
kind regards.
public void DTCalculations()
{
List<string> calculatedDates = new List<string>();
string startDate = "2009-07-27";
string endDate = "2009-07-29";

//Convert to DateTime variables
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);

//Calculate difference between start and end date.
TimeSpan difference =  end.Subtract(start);

//Generate list of dates beginning at start date and ending at end date.
//ToDo:
}

A: static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end)
{
    for(var day = start.Date; day <= end; day = day.AddDays(1))
        yield return day;
}

Edit: Added code to solve your particular example and to demonstrate usage:
var calculatedDates =
    new List<string>
    (
        AllDatesBetween
        (
            DateTime.Parse("2009-07-27"),
            DateTime.Parse("2009-07-29")
        ).Select(d => d.ToString("yyyy-MM-dd"))
    );

A: The easiest thing to do would be take the start date, and add 1 day to it (using AddDays) until you reach the end date. Something like this:
DateTime calcDate = start.Date;
while (calcDate <= end)
{
    calcDate = calcDate.AddDays(1);
    calculatedDates.Add(calcDate.ToString());
}

Obviously, you would adjust the while conditional and the position of the AddDays call depending on if you wanted to include the start and end dates in the collection or not.
[Edit: By the way, you should consider using TryParse() instead of Parse() in case the passed in strings don't convert to dates nicely]

A: for( DateTime i = start; i <= end; i = i.AddDays( 1 ) )
{
    Console.WriteLine(i.ToShortDateString());
}

A: You just need to iterate from start to end, you can do this in a for loop
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);

for(DateTime counter = start; counter <= end; counter = counter.AddDays(1))
{
    calculatedDates.Add(counter);
}

A: An alternative method
public static class MyExtensions
{
    public static IEnumerable EachDay(this DateTime start, DateTime end)
    {
        // Remove time info from start date (we only care about day).
        DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
        while (currentDay <= end)
        {
            yield return currentDay;
            currentDay = currentDay.AddDays(1);
        }
    }
}

Now in the calling code you can do the following:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
    ...
}

Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.


Q: Jest encountered an unexpected token when working with React TypeScript I am building a reusable react component without using react-app and I am very new to Jest. I keep on getting this message. I have tried several post solutions on Stackoverflow but I am stuck at the moment:
● Test suite failed to run
Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

C:\Users\User\Documents\accessible-date-picker\src\__tests__\DatePicker.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { DatePicker } from '../containers/DatePicker';
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)

I have the following configuration but I cannot figure out why I cannot resolve the problem:
//jest.config.js
module.exports = {
  roots: ["<rootDir>/src"],
  testMatch: [
    "**/__tests__/**/*.+(ts|tsx|js)",
    "**/?(*.)+(spec|test).+(ts|tsx|js)",
  ],
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  coveragePathIgnorePatterns: [
    "/node_modules/"
  ],
  moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy",
  }
};

Here is my tsconfigurations:
{
    "compilerOptions": {
        "lib": [
            "dom",
            "dom.iterable",
            "esnext"
        ],
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react"
    },
    "include": [
        "src"
    ]
}

Here are my dev dependencies:
 "devDependencies": {
    "@babel/core": "^7.12.7",
    "@babel/plugin-transform-runtime": "^7.12.1",
    "@babel/preset-env": "^7.12.7",
    "@babel/preset-react": "^7.12.7",
    "@babel/preset-typescript": "^7.12.7",
    "@babel/runtime": "^7.12.5",
    "@teamsupercell/typings-for-css-modules-loader": "^2.4.0",
    "@types/fork-ts-checker-webpack-plugin": "^0.4.5",
    "@types/jest": "^26.0.15",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/webpack": "^4.41.25",
    "@types/webpack-dev-server": "^3.11.1",
    "@typescript-eslint/eslint-plugin": "^4.8.1",
    "@typescript-eslint/parser": "^4.8.1",
    "babel-loader": "^8.2.1",
    "css-loader": "^5.0.1",
    "eslint": "^7.14.0",
    "eslint-plugin-react": "^7.21.5",
    "eslint-plugin-react-hooks": "^4.2.0",
    "fork-ts-checker-webpack-plugin": "^6.0.3",
    "jest": "^26.6.3",
    "style-loader": "^2.0.0",
    "ts-jest": "^26.4.4",
    "ts-node": "^9.0.0",
    "typescript": "^4.1.2",
    "webpack": "^5.6.0",
    "webpack-cli": "^4.2.0",
    "webpack-dev-server": "^3.11.0"
  }
}

Any help will be much appreaciated!

A: Looks like your test file is a js file (src\__tests__\DatePicker.spec.js) instead of ts?x file which means this pattern will never meet "^.+\\.(ts|tsx)$": "ts-jest".
However, you might know tsc can also have capability to transpile your js code as well as long as you set allowJs: true as you already did. So I think your problem would be fixed as you refine your pattern to to transform above including jsx file:
{
  transform: {
    "^.+\\.(t|j)sx?$": "ts-jest",
  }
}


Q: How to reload a entire component with angular when route changes? I want to reload or rerender a sidebar component when route change i have the following code:
  constructor(
    private auth: AuthService,
    private router: Router,
    private changeDetector: ChangeDetectorRef
  ) {
    this.auth.currentUser.subscribe(x => this.userData = x);
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
        this.changeDetector.detectChanges();
        console.log('enter');
      }
    });
  }

This enter to show the log 'enter' but not reload the component. Anybody can help with an example?

A: Usually component routing doesn't reload because angular works as SPA(single page application) - but you can make your components to load in order to reduce the browser size if that is the only case
Use href and your path name insted of routerLink on your sidebar anchor link - this will make your component to reload everytime when you click - everytime it will load all your js from server - if you are using lazy load this process is not the right way - this will only helps you to reduce the browser RAM usage on every click and doesn't maintain any previous data but routing will work as the same
So href will be the word for your question - but make sure that you really want to load your components
Hope it helps - Happy Coding:)

A: If you want to reload the entire page, just use
window.location.reload();


Q: adding items to deep List of KeyValuePairs I wrote a deep list:
public static List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>> ListBoxes = new List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>>();

Anybody has an idea how to add to this list any items?
For example:
("A",LIST("B",LIST("C",true)))

A: Easy:
ListBoxes.Add(
    new KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>("A",
        new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>
        {
            new KeyValuePair<string,List<KeyValuePair<string,bool>>>("B",
                new List<KeyValuePair<string,bool>>() {
                    new KeyValuePair<string,bool>("C", true)
                }
            )
        }
    )
);

It looks like you could use some helper methods or something.
Edit
If you create a simple extension method, then the task becomes maybe a bit more readable.
public static List<KeyValuePair<TKey, TValue>> AddKVP<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> self, TKey key, TValue value)
{
    self.Add(
        new KeyValuePair<TKey, TValue>(key, value)
    );

    // return self for "fluent" like syntax
    return self;
}

var c = new List<KeyValuePair<string, bool>>().AddKVP("c", true);
var b = new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>().AddKVP("b", c);
var a = new List<KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>>().AddKVP("a", b);

Edit #2
If you define a simple type, then it helps a bit more:
public class KVPList<T> : List<KeyValuePair<string, T>> { }

public static KVPList<TValue> AddKVP<TValue>(this KVPList<TValue> self, string key, TValue value)
{
    self.Add(new KeyValuePair<string, TValue>(key, value));
    return self;
}

var ListBoxes = new KVPList<KVPList<KVPList<bool>>>()
   .AddKVP("A", new KVPList<KVPList<bool>>()
       .AddKVP("B", new KVPList<bool>()
           .AddKVP("C", true)));

Edit #3
One more and I promise I'll stop.  If you define "Add" on the type, then you can use implicit initialization:
public class KVPList<T> : List<KeyValuePair<string, T>>
{
    public void Add(string key, T value)
    {
        base.Add(new KeyValuePair<string,T>(key, value));
    }
}

var abc = new KVPList<KVPList<KVPList<bool>>> {
    { "A", new KVPList<KVPList<bool>> {
        { "B", new KVPList<bool> {
            { "C", true }}
        }}
    }};


Q: Python - How to get all possible combinations from nested list I have a nested list like this :
values = [['DNO', 0.2], ['Equinor', 0.4], ['Petoro', 0.2], ['Total', 0.2]]

How to get all possible combinations of elements that will have a sum(2nd element of each sub list) greater than 0.5?
This is what I am using :
def getCombinations(values, min_len):
    combo = "\n"
    numbers = []
    doc = {}
    for val in values:
        doc[val[0]] = val[1]
        numbers.append(val[1])

    result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) >= 0.5]
    temp = doc.copy()

    for r in result:
        doc = temp.copy()
        if len(r) >= min_len:
            for rr in r:
                combo = combo + get_key(doc, rr) + " "

                doc.pop(get_key(doc, rr))
            combo = combo + "\n"
    return combo

My algorithm have some problem when there are multiple values like 0.2 in above list.
Currently it is returning this with min_length=3:
Total Equinor Petoro DNO
Total Equinor Petoro
Total Equinor Petoro
Total Petoro DNO
Equinor Total Petoro

A: The following should work:
import itertools
result=[]
for k in range(2,len(values)+1):
    temp=[tuple(x[0] for x in i) for i in list(itertools.combinations(values,k))if sum([p[1] for p in i]) >0.5]
    result.append(temp)
result=sum(result, [])
print(result)

Output:
[('DNO', 'Equinor'), ('Equinor', 'Petoro'), ('Equinor', 'Total'), ('DNO', 'Equinor', 'Petoro'), ('DNO', 'Equinor', 'Total'), ('DNO', 'Petoro', 'Total'), ('Equinor', 'Petoro', 'Total'), ('DNO', 'Equinor', 'Petoro', 'Total')]

A: You can use a list comprehension like this:
Explanation:

*

*The first for defines the length of the combinations. Every length from 2 to the length of values is used.

*The second for creates the actual combinations

*The if uses a generator method to sum the numbers of the items

from itertools import combinations

combis = [
    item
    for length in range(2, len(values)+1)
    for item in combinations(values, length)
    if sum(i[1] for i in item) >= 0.5
]


Q: Does extraction workers in google bigquery save the data into Columnar Storage follows a FIFO pattern? As I understand from bigquery streaming insert lifecycle  also shown in the image below. The data goes through streaming buffer before it is available in the Columnar Storage. The work of processing the data is done by the Extraction Workers.
However, in the documentation, it is not mentioned how the extraction workers process the data. Do they follow a random order for processing or it is FIFO processing?

A: The streaming buffer is a queue, and the extraction worker processes rows in order. The extraction workers take from the queue either when it reaches a certain volume of data or when a certain amount of time has elapsed in order to write sufficiently large chunks of data to managed storage. The underlying storage format in BigQuery is Capacitor, which reorders rows as it is persisting them to disk and performs a variety of other optimizations as well.


Q: Use case for Lock.tryLock() At API docs of Lockinterface for method tryLock(), this code sample is pasted,

A typical usage idiom for this method would be:
  Lock lock = ...;
  if (lock.tryLock()) {
      try {
          // manipulate protected state
      } finally {
          lock.unlock();
      }
  } else {
      // perform alternative actions
  }

My question is , does this use case not existed before Java 5 or folks used to implement it via some other techniques?
I am not able to comprehend the need to execute perform alternative actions based on lock availability.
Can somebody please explain real use cases for this?
I am sure this technique is not a straight forward replacement of synchronizedto write deadlock free code.

A: One straight-forward use case is a thread processing a batch of elements, occasionally trying to commit the elements that have been processed. If acquiring the lock fails, the elements will be committed in the next successful attempt or at the final, mandatory commit.
Another example can be found within the JRE itself, ForkJoinTask.helpExpungeStaleExceptions() is a method for performing a task that can be done by an arbitrary thread, but only one at a time, so only the one thread successfully acquiring the lock will perform it, all others will return, as the unavailability of the lock implies that there is already a thread performing the task.

It is possible to implement a similar feature before Java 5, if you separate the intrinsic locking feature, which doesn’t support being optional, from the locking logic, that can be represented as an ordinary object state. This answer provides an example.

A:
My question is, does this use case not existed before Java 5 or folks used to implement it via some other techniques?

The Lock interface was added in Java 5, is that what you mean?  Not sure what was there before.

I am not able to comprehend the need to execute perform alternative actions based on lock availability.  Can somebody please explain real use cases for this?

Sure.  Just wrote one of these today actually.  My specific Lock implementation is a distributed lock that is shared among a cluster of servers using the Jgroups protocol stack.  The lock.tryLock(...) method makes RPC calls to the cluster and waits for responses.  It is very possible that multiple nodes maybe trying to lock and their actions might clash causing delays and certainly one lock to fail.  This either could return false or timeout in which case my code just waits and tries again.  My code is literally:
if (!clusterLock.tryLock(TRY_LOCK_TIME_MILLIS, TimeUnit.MILLISECONDS)) {
    logger.warn("Could not lock cluster lock {}", beanName);
    return;
}

Another use case might be a situation where one part of the code holds a lock for a large amount of time and other parts of the code might not want to wait that long and instead want to get other work done.
Here's another place in my code where I'm using tryLock(...)
// need to wait for the lock but log
boolean locked = false;
for (int i = 0; i < TRY_LOCK_MAX_TIMES; i++) {
    if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) {
        logger.debug("Lock worked");
        locked = true;
        break;
    } else {
        logger.debug("Lock didn't work");
    }
}

A: The reason for writing code like that example is if you have a thread that is doing more than one job.
Imagine you put it in a loop:
while (true) {
    if (taskA_needsAttention() && taskA_lock.tryLock()) {
        try {
            ...do some work on task A...
        } finally {
            taskA_lock.unlock();
        }
    } else if (taskB_needsAttention() && taskB_lock.tryLock()) {
        try {
            ...do some work on task B...
        } finally {
            taskB_lock.unlock();
        }
    } else ...
}

Personally, I would prefer not to write code like that.  I would prefer to have different threads responsible for task A and task B or better still, to use objects submitted to a thread pool.

A: Use case 1
One use case would be to completely avoid running the thread. Like in the example below, for example a very strict internet hotspot where you can only access one webpage at once, and other requests are cancelled.
With synchronized you cannot cancel it, since it waits until it can obtain the lock. So tryLock just gives you flexibility to cancel something or to run other behavior instead.
package Concurrency;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LimitedHotspotDemo
{
    private static Lock webAccessLock = new ReentrantLock();

    private static class AccessUrl implements Runnable
    {
        private String url;

        public AccessUrl(String url)
        {
            this.url = url;
        }

        @Override
        public void run()
        {
            if(webAccessLock.tryLock()) {
                System.out.println("Begin request for url " + url);
                try {
                    Thread.sleep(1500);
                    System.out.println("Request completed for " + url);
                } catch (InterruptedException e) {
                    webAccessLock.unlock();
                    return;
                } finally {
                    webAccessLock.unlock();
                }
            } else {
                System.out.println("Cancelled request " + url + "; already one request running");
            }
        }
    }

    public static void main(String[] args)
    {
        for(String url : Arrays.asList(
            "https://www.google.com/",
            "https://www.microsoft.com/",
            "https://www.apple.com/"
        )) {
            new Thread(new AccessUrl(url)).start();
        }
    }
}

Output:
Begin request for url https://www.microsoft.com/
Cancelled request https://www.google.com/; already one request running
Cancelled request https://www.apple.com/; already one request running
Request completed for https://www.microsoft.com/

Use case 2
Another use case would be a light sensor which keeps the light on when there is movement in the room (with Sensor thread). There is another thread (TurnOffLights) running to switch the light off when there is no more movement in the room for a few seconds.
The TurnOffLights thread uses tryLock to obtain a lock. If no lock can be obtained, the process is delayed for 500ms. The last Sensor thread is blocking the lock for 5 seconds, after which the TurnOffLights thread can obtain the lock and turn off the lights.
So in this case the TurnOffLights thread is only allowed to turn off the lights when there are no more signals to the Sensor for 5 seconds. The TurnOffLights thread is using tryLock to obtain the lock.
package Concurrency;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LightSensorDemo
{
    private static volatile Lock lock = new ReentrantLock();
    private static volatile Thread lastSignal = null;
    private static Sensor sensor = new Sensor();

    private static class Sensor implements Runnable
    {
        private static Boolean preparing = false;
        public static Boolean isPreparing()
        {
            return preparing;
        }

        @Override
        public void run()
        {
            System.out.println("Signal send " + Thread.currentThread().getName());
            try {
                invalidatePreviousSignalsAndSetUpCurrent();
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                //System.out.println("Signal interrupted " + Thread.currentThread().getName());
                return;
            } finally {
                lock.unlock();
            }
        }

        private static synchronized void invalidatePreviousSignalsAndSetUpCurrent() throws InterruptedException
        {
            preparing = true;
            if(lastSignal != null) {
                lastSignal.interrupt();
            }
            lastSignal = Thread.currentThread();
            lock.lockInterruptibly();
            preparing = false;
        }
    }

    private static class TurnOffLights implements Runnable
    {
        @Override
        public void run()
        {
            while(true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    System.out.println("Interrupted" + this.getClass().getName());
                    return;
                }
                if (!Sensor.isPreparing()) {
                    if(lock.tryLock()) {
                        try {
                            System.out.println("Turn off lights");
                            break;
                        } finally {
                            lock.unlock();
                        }
                    }  else {
                        System.out.println("Cannot turn off lights yet");
                    }
                } else {
                    System.out.println("Cannot turn off lights yet");
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Thread turnOffLights = new Thread(new TurnOffLights());
        turnOffLights.start();

        //Send 40 signals to the light sensor to keep the light on
        for(int x = 0; x < 10; x++) {
            new Thread(sensor).start(); //some active movements
            new Thread(sensor).start(); //some active movements
            new Thread(sensor).start(); //some active movements
            new Thread(sensor).start(); //some active movements
            Thread.sleep(250);
        }

        turnOffLights.join();
    }
}

Notice also that I use lock.lockInterruptibly(); to interrupt previous signals. So the 5 second countdown always starts from the last signal.
Output is something like:
...
Cannot turn off lights yet
Cannot turn off lights yet
Signal send Thread-19
Signal send Thread-20
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Turn off lights

Process finished with exit code 0


Q: Javascript giving me Uncaught ReferenceError: require is not defined error I have a file structure that looks like this:

My index.js has this code
const THREE = require("three")

var scene = new THREE.scene();
console.log(scene)

My index.html
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

What the hell

I did not use the tag { type : "modules } in my package.json. However, I am still getting the Uncaught ReferenceError: require is not defined error. May I know what is the reason? Thanks!
Error in my live server looks like this

This is my package.json if you are interested
{
  "name": "threejs-playground",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "three": "^0.133.1"
  }
}


Q: problem in making records of a file by perl I'm trying putting a file into records with number starting from record 0 to n and saving it into an output file. my file is starting from AA to // and there are several AA's and //  so I'm putting record number for each AA to // as there are 2000 to 3000 AA's so I want to put them in records with number. Could someone please help me.
//
AA  r00001
FA  tea
OS  fskjkterjykjlt
//
AA  T00002
FA  ACE2
OS  coffee
SQ  MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY
//
AA  T00003
FA  Diet coke
OS  ewtji34ut893u569
SQ  MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV
//
AA  T00004
FA  coke
OS  jgerjgkhjetkh
SQ  MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ
SQ  RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA
//
#!/usr/bin/env perl
use strict;
use warnings;

my $ifh;

my $ofh;

my $line;
my $recnum = 0;
my $ifn  = "factor data 1.txt";
my $ofn  = "try.txt";
open ($ifh, "<$ifn") || die "can't open $ifn";
open ($ofh, ">$ofn") or die "can't open $ofn";
my $a = "\/\/ ";

while ($line = <$ifh>)
{
chomp $line ;

    if ($line =~ m/$a\$/)
        {

         print "$ofh $line\n";

         $recnum++;
  }
         else
 {
        print "$ofh $recnum $line\n";
  }
 }
       close ($ifh);
       close ($ofh);

A: These types of record I/O problems are simplified if you use the Perl idiom of changing the record separator.  Now each record becomes a line and lines are easy to count.
NOTE: I also removed the last // so we don't count the empty record.
Ok... I'm guessing that you may want something like this
#! /usr/bin/env perl

 use strict;
 use warnings;

 my $cntr = 0;

 print "Starting\n";

 # change record seperator
 $/ = '//';

 while ((<DATA>))
 {
   print"============== Record number $cntr ======================\n";
   print "$_\n";
   print "========================================================\n";

   $cntr++;
 }

 exit 0;

 __DATA__

 /

 AA r00001

 FA tea

 OS fskjkterjykjlt

 //

 AA T00002

 FA ACE2

 OS coffee

 SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY

 //

 AA T00003

 FA Diet coke

 OS ewtji34ut893u569

 SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV

 //

 AA T00004

 FA coke

 OS jgerjgkhjetkh

 SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ

 SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA

 //

With output like this
 Starting
 ============== Record number 0 ======================

 /

 AA r00001

 FA tea

 OS fskjkterjykjlt

 //
 ========================================================
 ============== Record number 1 ======================

 AA T00002

 FA ACE2

 OS coffee

 SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY

 //
 ========================================================
 ============== Record number 2 ======================

 AA T00003

 FA Diet coke

 OS ewtji34ut893u569

 SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV

 //
 ========================================================
 ============== Record number 3 ======================

 AA T00004

 FA coke

 OS jgerjgkhjetkh

 SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ

 SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA


Q: CLLocationManager does not work for non-wireless connection? I have a Mac app and would like to use core location, however, when I am not on wifi but connected using an ethernet cable, core location (CLLocationManager) reports that the operation could not be completed.
The exact error message is
The operation couldn't be completed. (kCLErrorDomain error 0.)

If I am always connected to the same router (ie. either wifi or ethernet cable) why does CLLocationManager only work for wifi and not for the ethernet connection?
Any suggestions would greatly be appreciated.
Thanks.
Edit:
Here is some code.
I define my location manager as an instance variable like so
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDistanceFilter:ICMinimumUpdateDistance];

I then monitor the location manager's delegate method like so,
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

// Filter out points before the last update
NSTimeInterval timeSinceLastUpdate = [newLocation.timestamp timeIntervalSinceDate:dateOfLastUpdate];

if (timeSinceLastUpdate > 0)
{
    //Do stuff
}

}

I also check for errors using the delegate method
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Location Error:%@", [error localizedDescription]);
}

In the code above, the location manager updates with an invalid newLocation (bad time stamp) and then the location manager calls the delegate error method.

A: For lack of a GPS in your laptop, core-location on OSX uses the (skyhook) service, or something similar.
The service maintains a database of WIFI access-points and  their positions (possibly updated by iPhones that do have GPS and wifi enabled) which is queried.
So by feeding a list of access points you can see, and their relative signal strengths the system is able to triangulate roughly where you are.
So you need both wifi enabled, and a working internet link (but internet shouldn't need to be over wifi, you can leave the airport un-associated)

A: I've noticed this too. If you open the Time Zone tab of the Date & Time pane in System Preferences while connected to the internet via ethernet, it says to connect to a wireless network to determine your current location. This leads me to believe that CoreLocation does, in fact, require a wireless connection.


Q: MetaMask RPC error? 'MetaMask - RPC Error: Internal JSON-RPC error.' I'm developing the front-end to an application that I'm trying to test. However, MetaMask keeps giving me this error? I tried changing the gas limit like previously suggested and nothing. Any ideas?
Error:
MetaMask - RPC Error: Internal JSON-RPC error.
code: -32603
data: {code: -32000, message: "gas required exceeds allowance (30000000) or always failing transaction"}
message: "Internal JSON-RPC error."

A: Without seeing the code, it's hard to say for sure but you could try:

*

*Check any code you changed in the front end, specifically in your code you may have something like this:

const contractInstance = new state.web3.eth.Contract(
    MyContract.abi,
    "0x.....",            // contract address
    {
        from: state.accounts[0],
        gasPrice: 1000,
        gas: 100000
    }
);

Make sure the gas prices are similar to those, you may have to adjust for your case.

*Re-compile and redeploy --> for truffle, run truffle develop first, then compile then migrate --reset for local deployment.

*In Metamask, reset your test account. Metamask > Select Account > Settings > Advanced > Reset account. Only do this for testing accounts

A: Previously it used to happen in older versions due to a gas specification issue which was fixed. rpcErrors.internal` expects a string as the first argument, with arbitrary data being the optional second argument. Passing in a non-
string first argument results in the error being shadowed by an error
from eth-json-rpc-errors.
Please check what you are passing to Metamask.

A: In my case, after trying so many options I have restarted Ganache and re-imported new account from Ganache to Metamask.
I connected this new account with localhost application.
This resoles my issue.

A: Before performing any transaction the sending ETH address must be connected to your own site or UI. So it can get the address of sending account and goes towards the further transaction in the metamask.
Make sure Your sending account address must be connected to your UI.


Q: Is it possible for a translucent  to have to affect on the items below it? I have kind of a weird situation, while trying to make a simple chrome plugin. The idea of the plugin is that it constantly overlays a half-transparent image on top of the page you are viewing. To accomplish this, I have the plugin inject JavaScript, which appends an  tag with the following CSS rules:
img.class#id {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%
  width: 100%;
  opacity: 0.5;
  z-index: 9999999;
}

This already works, but it introduces a new problem. Since the z-index of the image is intentionally large, it overrides the left and right click actions of the user, on the elements with a lower z-index. I can't change the z-index to be smaller, since that would defeat the purpose of the plugin, and I can't change the transparency of the other things on the page, since there's too much variability. Is there a way to ensure that the page is still usable, even with the image overlayed on it?

A: set pointer-events: none in css
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

The pointer-events CSS property specifies under what circumstances (if
  any) a particular graphic element can become the target of mouse
  events.

*

*Note that while only mouse events are stated, it is in fact valid for all kinds of pointer events - mouse, touch.

From the possible values:

none The element is never the target of mouse events; however, mouse
  events may target its descendant elements if those descendants have
  pointer-events set to some other value. In these circumstances, mouse
  events will trigger event listeners on this parent element as
  appropriate on their way to/from the descendant during the event
  capture/bubble phases.


Q: Should I be using static or instance methods? I'm really confused with the concept of static vs instance methods. I have created a BMR calculator. I've seperated the GUI from the calculations using different classes.
public class Calculations {

/**
 * If user input is correct, this method will calculate the BMR value of the user given their input and measurement choices.
 *
 * @param userAge, userHeight, userWeight
 * @return BMR Value as a string
 */
public static int calcBMR(int age, String gender, double height, double weight) {

    // This is the body of the calculations - different formulas used depending on gender. Conversions to kg and cm done earlier so no conversions needed here.
    if (gender.equals("M")) { // Uses male bmr formula if genderMale radiobutton is selected
        return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) + 5)); // This is the Miffin St-Jeor formula, calculations done in cm/kg
    } else { // else gender.equals("F") - there are only 2 options for gender, M or F.
        return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) - 161));
    }
}

/**
 * If the user selects the TDEE option, this method will be executed after the calcBMR() method.
 * A value from the calcBMR() method will be passed down to this method, and is multiplied
 * by the activity level parameter passed into this method.
 *
 * @param selectedActivityLevel
 * @return TDEE Value (as a string)
 */
public static int calcTDEE(double activityMultiplier, int bmr) {
    System.out.println(activityMultiplier);
    return (int) Math.round(bmr * activityMultiplier);
}

}
As you can see, the methods are STATIC, however the variables being passed through (to both methods) are instance variables.
I am only calling these methods through the following lines:
            bmrValue = Calculations.calcBMR(userAge, userGender, userHeight, userWeight);
            bmrLabel.setText("
You have a BMR of: " + "" +  bmrValue + "");
            if (tdeeYes.isSelected()) {
                userActivityLevel = activityMap.get(activityLevelBox.getSelectedItem());
                // Looks up selected item from combo box, which is the KEY. Then looks up the value to this key from the map - this value is the TDEE multiplier.
                tdeeLabel.setText("
You have a TDEE of: " + "" + Calculations.calcTDEE(userActivityLevel, bmrValue) + "");
                }

The variables are defined as:
HashMap<String, Double> activityMap;
String[] activityLevels = {"Sedentary", "Lightly Active", "Moderately Active", "Very Active", "Extra Active"};

int userAge;
String userGender;
double userHeight;
double userWeight;
double userActivityLevel;

int bmrValue;

Am I using static/instance variables correctly? Earlier I had all my parameter variables as static, as I know static methods can only access static variables. I didn't know that the parameters could be instance variables until now.
Any guidance would be appreciated.

A: For starters, the difference between static and instance variables is that, only ONE static variable exists for all the instances of the class, whereas an instance variable exists for EVERY instance of the class.
Now, when you are talking about methods, in most cases you need to make a method static when you are trying to call it from another static method (such as main).
In general this practice is wrong for OOP, and chances are you should rethink the way the program is structured.
If you could provide more details about the code you use to call these methods, I would be able to help you with more details on how to fix this.
EDIT:
In light of the new info you provided:
1) I believe that bmrMain,BMRMain and Calculations can all be merged into one class. The constructor of the new class should be adjusted to read input (as well as getters and setters for each variable for added flexibility - optional)
2) Regarding the calculation of the bmr part, there are many ways to tackle this, so I will go ahead and suggest the one that is best in my opinion.
Add a Button with a text "Click to calculate" or something similar, and implement an ActionListener. The action Listener will in turn call (whenever the button is clicked) the method that calculates everything, and finally it will change the text on the JLabel.
sample code for the action Listener:
JButton button = new JButton("Text Button");
button.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    //Call the methods for the calculation
    // bmr and tdee are temporary variables to store the results from the methods
    //handle them properly, or remove them if not needed (I just wrote a sample)
    int bmr = calcBMR(...); //pass the correct variables as arguments here
    int tdee;
    if(userHasPickedTDEE) {  tdee = calcTDEE(...); }  //and here
    label.setText(....);

  }
});

These 2 steps will take care of your "static" problem.
I recommend that you do some research on event-driven programming
And here is some extra and more in-depth reading on Action Listeners
If you need further help, or clarifications let me know :)
EDIT2:
In general, yes it is a good practice to separate classes in order to keep the code manageable. But in this case I think it is a bit superfluous to create a new class just for 2 methods.
Nevertheless if you would like to keep the current structure, the way to fix the "static" is:
1) remove static from the 2 calculation methods.
2)line 332 should be
Calculations c = new Calculations();
bmrValue = c.calcBMR(userAge, userGender, userHeight, userWeight);

FINAL_EDIT:
Well, these questions can easily be transferred to a thread of their own. But here is a useful link from a quick google search I just did, that will help demistify the static keyword:
Static keyword in Java

A: My thumb rule for using static variables goes somewhat like this:

*

*Do not use static

*When it is needed to use static refer to (1)

For most cases, the above thumb rule works. But then, we have standard idioms popularized by JDK, apache-commons libraries. Looking into them you find that:

*

*It is OK to have utility classes that contain all static methods.

*It is OK to create constants using static fields in classes. Though, for this using Enum might be a better choice.

*It is OK to one off utility functions that work on the same class into the class.

As for the restructuring the code goes, you should be looking at who owns the data. In this case, both the methods from Calculations class looks to be using data from the other class. Move the methods into the other class.
The only reason for existence of Calculations class should be that if you are using the methods from multiple other classes which are not related. If they are related, you try to model their relationship and see where these methods go.

A: I use static whenever my class is just used to call those methods (i.e. my main method calls the static methods to set variables in the main class, etc). I believe that is the "utility" class that KDM mentioned. A small example of when I use static or utility classes:
class Utility {
  public static int add(int a, int b) {
    // You would, of course, put something besides simple addition here
    return a + b;
  }
}

class Main {
  public static void main(String[] args) {
    int a = 2, b = 3;
    int sum = Utility.add(a, b);
    System.out.println(sum);
  }
}

On the other hand, if you have a class that is closer to an actual object, with properties of its own, stay away from static. If you use static, then each instance of the class which you want to be separate objects will end up with same values.
Based on the name and functionality of your class, it appears you have a utility class. Static should be fine, but it may not be necessary. Hypothetically, though, if you wanted to use this class with multiple "people" class instances for which to calculate the BMR (where each instance is unique), then I would put calcBMR() in a person class and make it non-static so that each person has their own calcBMR().
Edit: Maybe this will help too:
Instance -> Instantiate: new Calculations().instanceMethod();
Static -> Class itself, the class's "state": Calculations.staticMethod();

A: If you think in terms of, do I want instance methods or static methods, you're going to be lost. Java isn't method-oriented, it's object-oriented. So for your functionality, decide whether you want an object or a pure function (where pure function means no dependencies and no side-effects, it's strictly a function that given this returns that).
It might be good to model this as an object, since you have information describing some aspect of the User and it may make sense to keep it together:
public class User {
    private int age;
    private String gender; // todo: use an Enum
    private double height;
    private double weight;
    private String activityLevel; // todo: use an Enum

    public User(int age, String gender, double height, double weight,
        String activityLevel) {
        this.age = age;
        this.gender = gender;
        this.height = height;
        this.weight = weight;
        this.activityLevel = activityLevel;
    }

    public double calculateBmr() {
        int offset = gender.equals("M") ? 5 : -161;
        return (int) (Math.round((10 * weight)
            + (6.25 * height) - (5 * age) + offset));
    }
}

etc. This way we don't have to preface the variables with "user", they're all placed together in one object. Objects are an organizational scheme for collecting related information, the instance methods are functions that use the object's information.
The alternative route is to create a utility class:
public final class UserCalcUtil {
    private UserCalcUtil() {} // no point instantiating this

    public static int calculateBmr(String gender, double height,
    double weight, int age) {
        int offset = gender.equals("M") ? 5 : -161;
        return (int) (Math.round((10 * weight)
            + (6.25 * height) - (5 * age) + offset));
    }
}

Here you're keeping track of the user data separately, and passing it in to the static method when you want to calculate something. The utility class is a dumping ground for separate static methods (which you can think of as functions).
Whether you want to use objects or utility classes depends on how you want to organize your data and do calculations on it. Packing the data for a User together with the methods that act on that data may be more convenient if you always do the calculations on the individual objects, or moving the calculations into a utility class might make sense if there are multiple unrelated classes that you want to do calculations for. Since Java has more support for object-oriented constructs it often makes sense to take the object approach.
And you can use static methods, but avoid static variables for anything but constants (public static final, with a type that's immutable).


Q: C++ - Qt QObject::connect GET request usage across classes A quick overview of what's happening: I am trying to do a GET request using Qt's QNetworkAccessManager, but the callback function on my QObject::connect(..) function is not being called. My questions is can I call QObject::connect from one object, but connect to a slot of another object (given that I have a pointer to both the object and the slot) - See below for more details.
My ultimate goal is to POST the data (seeing as it's a login function), I had POST Request code that was ultimately suffering from the same issue - callback function not being called. So I would like to be able to do a simple GET request first, once I have that, I think I'll be fine on my own from there.
I currently have a QMainWindow LoginWindow, with a button that calls a slot doLogin() in the LoginWindow class. This all works as you would expect. LoginWindow also has a public slots function called loginResponse(QNetworkReply* response).
//---LoginWindow.h

...

public slots:
    void doLogin();
    void loginResponse(QNetworkReply* response)

...

//---LoginWindow.cpp

LoginWindow::LoginWindow(QWidget *parent) :
    QMainWindow(parent),
ui(new Ui::LoginWindow)
{
    ui->setupUi(this);
    ui->username_le->setFocus();
}

void LoginWindow::doLogin()
{
   MyProduct::Network network(this);
    qDebug() << "Logging in...";

    //Here I call network.login from LoginWindow and pass
    //references to the Slot I want to use and the LoginWindow itself
    network.login(
        ui->username_le->text(), //username
        ui->password_le->text(), //password
        this,                    //reference to this object (LoginWindow*)
        SLOT(loginResponse(QNetworkReply*)) //loginResponse slot
    );
}

void LoginWindow::loginResponse(QNetworkReply* response)
{
    qDebug() << "Log in complete";
}

Next I have another class, under the MyProduct namespace, called Network. As you can see above, Network has a function called login. Here it is:
void MyProduct::Network login(QString username, QString password, QObject *receiver, const char *slot)
{
    QNetworkRequest request(QUrl(API_ROOT + LOGIN_PATH)); //"http://localhost/basic/login.php"
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

    //nam = QNetworkAccessManager* declared in the constructor
    QObject::connect(nam,SIGNAL(finished(QNetworkReply*)), receiver, slot);

    qDebug() << "Posting login data...";
    nam->get(request);
}

The goal here is to create a login function in my Network class that can be used and connected in any number of windows (as users may log in from multiple places). But I'm getting no response - LoginWindow::loginResponse is not run.
I see "Logging in..." and "Posting login data" output in the console, but not "Log in complete".
Can anyone please point me in the right direction or tell me I'm crazy or that this is a bad idea?
Thanks in advance!

A: Note that QNetworkAccessManager operates asynchronously. The get() method does not block while the network operation occurs; it returns immediately. (See the Detailed Description section of the documentation for more info.)
This is pretty typical of Qt's network-related APIs, because you usually don't want your application to freeze while waiting for data to move across a network.
What this means is what your instance, nam, isn't alive long enough for the GET request to actually finish. Your instance of the Product::Network class is deleted immediately after the call to login() because it's allocated on the stack. Although I can't see the code, I'm guessing it cleans up the QNetworkAccessManager as well.
If you extend the lifetime of your network object, you may find that your slot will eventually be invoked.

Also, this is more a matter of preference, but I think it would be cleaner to avoid passing a receiver and a slot to your login() function. I'd recommend declaring your own signals in the Network class as part of its API, and to connect to those in the LoginWindow class.


Q: It's not unusual for Is it possible to say "strange" instead of "unusual"?
It's not unusual for people to want to travel.
or
It's not strange for people to want to travel.

A: Sure, it's possible. There is plenty of overlap between the two words that you can often substitute one for the other.
However, some caveats may apply. For example, consider your two sentences about traveling:

It's not unusual for people to want to travel.
It's not strange for people to want to travel.

How would we talk about those folks who don't like to travel?

It's unusual for people to not want to travel.
It's strange for people to not want to travel.

Both of these sentences would imply that most people enjoy traveling, and want to do so. But the second sentence might cause a homebody to be more offended. It's one thing to say that someone's interests are uncommon (which is what "unusual" might mean), but another to say their preferences are bizarre (which is how "strange" could be interpreted).
In short, I think unusual is a "softer" term, less likely to offend or cause people to bristle. That said, "strange" isn't always insulting, either. Sometimes it's regarded as quaint.

A: I think you can use 'unusual' to mean 'strange' or you can use 'strange' to mean 'unusual'. These two words are almost synonyms. In the case of meaning of 'unusual' is concerned, it is "not usual or expected"
For example:

It is unusual that Tom is riding a bycycle.

In this example, Tom isn't expected to ride a bycycle. May be he always drives a car. So, it's not usual.
But, the word strange is stronger than 'unusual'. For example:

Tom is dancing lonely at home without music. It's his strange behaviour.

Here, [dancing lonely at home without music] is very unusual behaviour.
Tom is showing a strange behaviour. But generally you can interchange them (strange and unusual)
That's why both are correct to use.
It's not unusual for people to want to travel.
or
It's not strange for people to want to travel.

A: "Usual" or "unusual" has to do with expectation of habit or repetition.
"Strange" or "familiar" has to do with more of an absolute level of expectation, experience, or value.

Not so long ago, people usually rode horses to work, which would seem strange today.

"Usual" has more a meaning of "often" but does not usually mean "familiar".

I heard that usually happens, but I've never seen it before.

When events are unexpected, "unusual" and "strange" can often be interchanged.

It was unusual to have rain today.
  It was strange that it rained today.
He has an unusual habit.
  He has a strange habit.

Consider the following pairings

unusually familiar
  strangely familiar
  unusually strange

are idiomatic meaning something is either "familiar" or "strange" but one is not quite sure of the reason, something like deja vu.