How to compute $\int_0^\infty \frac{\cos(ax)}{(1+x^2)\sqrt{x}}dx$.

Question: $$
\mbox{How can I compute}\
\int_{0}^{\infty}\frac{\cos\left(ax\right)}{\left(1 + x^{2}\right)\,\sqrt{\,{x}\,}}\,\mathrm{d}x\ ?.
$$
I saw many questions about computations of that integral without the term $\,\sqrt{\,{x}\,}\,$ and that it can be solved by using various techniques ( contour integral, iterated integral, etc$\ldots$ ). But how can I compute my integral $?$.
Comment: I think this integral can also be computed using complex analysis. Integrate $f(z)=\frac{e^{iaz}}{(1+z^2)\sqrt{z}}$ over a half circle with a small "bump" around $0$. This contour is contained in a domain which has a branch of square root, so $\sqrt{z}$ is well defined there.
Comment: If $a\ge 0$ *Mathematica* says $$\frac{\pi  e^{-a} \left(e^{2 a} \text{erfc}\left(\sqrt{a}\right)+\text{erfi}\left(\sqrt{a}\right)+1\right)}{2 \sqrt{2}}$$
Answer: Let
$$
f(a) = \int_0^{+\infty} \frac{\cos(ax)}{(1+x^2)\sqrt{x}} \, \mathrm{d} x,
$$

First, we note that $f(a)=f(-a)$, hence $f$ is even and we will focus only on $a \ge 0$.
Second,
$$
\begin{split}
\left| f(a) \right| &\le \left|\int_0^{+\infty} \frac{\cos(ax)}{(1+x^2)\sqrt{x}} \, \mathrm{d} x \right|\\
&\le \int_0^{+\infty} \frac{\left|\cos(ax)\right|}{(1+x^2)\sqrt{x}} \, \mathrm{d} x \\
&\le \int_0^{+\infty} \frac{\mathrm{d} x}{(1+x^2)\sqrt{x}}  = f(0)
\end{split}$$
With some math one finds that
$$
f(0) = \int_0^{+\infty} \frac{\mathrm{d} x}{(1+x^2)\sqrt{x}} =2\int_0^{+\infty} \frac{\mathrm dt}{1+t^4} =  \frac{\pi}{\sqrt{2}} \approx 2.22
$$
(see here)

Now, if we differentiate twitce under integral symbol (we can do it because of Leibniz integral rule)
$$
\begin{split}
f''(a) &= -\int_0^{+\infty} \frac{\cos(ax) \cdot x^2}{(1+x^2)\sqrt{x}} \, \mathrm{d} x\\
&= -\int_0^{+\infty} \frac{\cos(ax) \left(x^2+1-1\right)}{(1+x^2)\sqrt{x}} \, \mathrm{d} x\\
&= - \left[\int_0^{+\infty} \frac{\cos(ax)}{\sqrt{x}} \, \mathrm{d} x -\int_0^{+\infty} \frac{\cos(ax) }{(1+x^2)\sqrt{x}} \, \mathrm{d} x \right] \\
&= f(a) - \int_0^{+\infty} \frac{\cos(ax)}{\sqrt{x}} \, \mathrm{d} x
\end{split}$$
Now,
$$
\begin{split}
\int_0^{+\infty} \frac{\cos(ax)}{\sqrt{x}} \, \mathrm{d} x &= \frac{1}{2}\int_\mathbb{R}\frac{\cos(ax)}{\sqrt{|x|}} \, \mathrm{d} x \\
&= \mathcal F \left(\frac{1}{\sqrt{|x|}}\right)(a) \\
&=\frac{1}{2} \sqrt{\frac{2\pi}{|a|}}\\
&= \sqrt{\frac{\pi}{2}}\sqrt{\frac{1}{|a|}}
\end{split}
$$
where we used $ \mathcal F \left(\frac{1}{\sqrt{|x|}}\right)(a) = \frac{1}{2} \sqrt{\frac{2\pi}{|a|}}$ (see Fourier Transform of $\frac{1}{\sqrt{|x|}}$)

So, the problem is now to solve
$$
\begin{cases}
f''(a) -f(a) = -\sqrt{\frac{\pi}{2}}\sqrt{\frac{1}{|a|}}\\
f(0) = \frac{\pi}{\sqrt 2}\\
\end{cases}
$$
From linear differential equations we know that a solution is
$$
f(a) = c_1 \mathrm{e}^a + c_2 \mathrm{e}^{-a} + f_\mathrm p(a)
$$
where $c_1$ and $c_2$ are real numbers and $f_\mathrm p$ is the complementary solution.
Wolfram Alpha helps us to know that
$$
\begin{split}
f(a) &= c_1 \mathrm{e}^a + c_2 \mathrm{e}^{-a} + \sqrt{\frac{\pi}{2}}\int_0^{a} \frac{\mathrm{e}^{-x+a}-\mathrm{e}^{x-a}}{2\sqrt{x}}\, \mathrm d x\\
&= c_1 \mathrm{e}^a + c_2 \mathrm{e}^{-a} + \sqrt{\frac{\pi}{2}}\int_0^{a} \frac{\sinh(a-x)}{\sqrt{x}}\, \mathrm d x
\end{split}
$$
Now, if we add the initial condition, we get
$$
c_1+c_2 = \frac{\pi}{\sqrt 2},
$$
hence, after renaming the constant $c_1 = C$, the solution is
$$
\begin{split}
f(a)&= C \mathrm{e}^a + \left(\frac{\pi}{\sqrt 2} - C\right) \mathrm{e}^{-a} + \sqrt{\frac{\pi}{2}}\int_0^{a} \frac{\sinh(a-x)}{\sqrt{x}}\, \mathrm d x\\
&= 2C \sinh(a) +  \frac{\pi}{\sqrt 2} \mathrm{e}^{-a} + \sqrt{\frac{\pi}{2}}\int_0^{a} \frac{\sinh(a-x)}{\sqrt{x}}\, \mathrm d x
\end{split}
$$
If you find some other initial value (for example $f(1)$), then you can eliminate the constant $C$ too.
Comment: Thank you for the answer. But how do we justify the differentiation? and I calculate your differential equation with mathematica but that answer seems not to be correct.
Comment: Hi @JaeyunYi, I add few more stuffs. Hope this  can help.


How unmanaged C++ implement COM sink

Question: I have a c# COM server defined some delegate for event handling.
This is the sample code from MSDN:
<code>using System;
using System.Runtime.InteropServices;
namespace Test_COMObject
{
public delegate void ClickDelegate(int x, int y);
public delegate void ResizeDelegate();
public delegate void PulseDelegate();

// Step 1: Defines an event sink interface (ButtonEvents) to be
// implemented by the COM sink.
[GuidAttribute("1A585C4D-3371-48dc-AF8A-AFFECC1B0967")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface MyButtonEvents
{
    void Click(int x, int y);
    void Resize();
    void Pulse();
}
// Step 2: Connects the event sink interface to a class
// by passing the namespace and event sink interface
// ("EventSource.ButtonEvents, EventSrc").
[ComSourceInterfaces(typeof(MyButtonEvents))]
public class MyButton
{
    public event ClickDelegate Click;
    public event ResizeDelegate Resize;
    public event PulseDelegate Pulse;

    public MyButton()
    {
    }
    public void CauseClickEvent(int x, int y)
    {
        Click(x, y);
    }
    public void CauseResizeEvent()
    {
        Resize();
    }
    public void CausePulse()
    {
        Pulse();
    }
}
}
</code>
but msdn only provides a VB sample to implement COM client event sink, can anybody give me a sample how unmanaged c++ to do this?
below is the vb sample to implement COM event sink
<code>' COM client (event sink)
' This Visual Basic 6.0 client creates an instance of the Button class and
' implements the event sink interface. The WithEvents directive
' registers the sink interface pointer with the source.
Public WithEvents myButton As Button

Private Sub Class_Initialize()
Dim o As Object
Set o = New Button
Set myButton = o
End Sub
' Events and methods are matched by name and signature.
Private Sub myButton_Click(ByVal x As Long, ByVal y As Long)
MsgBox "Click event"
End Sub

Private Sub myButton_Resize()
MsgBox "Resize event"
End Sub

Private Sub myButton_Pulse()
End Sub
</code>
Answer: Language runtimes often hide the extensive plumbing involved with receiving events from a COM object.  But if you do this in raw C++ then you need to get started by querying the interface pointer for IConnectionPointContainer.  That lets you enumerate all out-going interfaces.  Which then lets you obtain an IConnectionPoint for a particular interface.  You then call its Advise() method to set your sink interface that gets the callbacks.  Which gives you back a cookie, you need to store it.  For later when you want to unsubscribe with the Unadvise call.
It is described fairly well in the MSDN Library, start reading here.
Comment: i have created a c++ class : class CSubButton : public Test_COMObject::MyButtonEvents    but i can't create a instance, compiler tell me that IDispath not implemented.
Comment: it is too complecated for me since i don't have any experience on COM. finally i export a c function and use load library in c# part to cover it as a delegate.

How unmanaged C++ implement COM sink


How does Abathur contribute to team experience?

Question: Abathur is surely an interesting and unique design, but how exactly does he soak xp when he's in a lane?

Do my locusts soak xp when I'm on another lane?
Do I soak 2 lanes worth of xp when minions die to the towers that are just in front of me while I use symbiote on a minion and kill enemy minions on another empty lane?
Comment: I think this and a few other Abathur questions should be merged into one and ideally updated with the latest information.
Answer: Locusts do not grant the AoE experience like heroes do for just being nearby the death of a unit. Instead, locusts gain experience whenever something dies after it has been damaged by the locust within, I believe, the last 5 seconds. Similarly, your mines also grant experience under the same conditions.
Abathur, in theory, can cover all 3 lanes for their experience because of his long-range abilities. 2-3 mines can easily blow up minion waves in one lane, a pack of locusts can be in another, and he can be nearby the third lane or even cloned at this time.
Comment: I know experience is not multiplied by the number of players nearby. What I meant was if everyone is at bot lane, abathur is at mid lane leeching xp from minions dying nearby while he uses symbiote on top lane and kills minions. This means leeching xp from two lanes by himself, thus twice the experience.
Comment: @Varaquilex You are correct with that. He would earn "Nearby Hero" experience from being in mid, and any units in top lane you damaged would give your team experience too. A very aware Abathur can lane dominate and be a huge experience gain because of this.
Comment: I still feel like the full spectrum of mechanisms remains unclear. Can he double dip on xp, gaining xp from his mines, locusts, and proximity? Also, doesn't he spawn the minions in the same lane he's in, so how can the minions leech from a different lane?
Comment: @rbatt As I understand it, Aba has two methods of full XP soak and two methods of semi-soak. He can fully soak by normal proximity himself, but this also works on his symbiote target. So if he symbiotes a minion in a lane empty of heroes, he is effectively there as well. He can additionally gain Xp through mines and locusts as explained above. Mines and locusts do not gain XP for him from proximity, but from damaging/killing minions.
Comment: So for three lanes, he could be in one, be symbioting a minion in a second, and mining a third. About 5/6 as effective as the Vikings being in all three. His advantage is that he can symbiote/clone a hero to participate in a team fight/objective, while still body-soaking a lane. This is something the Vikings cannot do. It also means that the longer the objective is contested, the more XP Aba soaks from the lane.


Do harmful floor tiles count towards the 100% completion of a floor?

Question: Some floors have trap floor tiles that have various effects. Every floor also has a chest that only opens when you have touched every floor tile at least once. Are you required to walk over these traps in order to get 100% completion of a floor or are they exempt?
Answer: Yes they do. I checked by activating the treasure chest for that floor. It highlighted all of the tiles I have not touched, including all of the trap floor tiles.


Windows batch - why is the if not processed?

Question: I made a .bat file that should call Maven task and then copy newly created ear file. I don't know why the file is neither copied, nor the "file doesn't exist" message occurs. If I comment out the "mvn clean install" row, the copying is processed.
cd d:\test\
mvn clean install

if exist d:\test.war (
    echo "copying"
    copy d:\test.war D:\Development\liferay-portal-6.2-ce-ga3\deploy\
) else (
    echo "file doesn't exist"
)

Note: I know this functionality can be done by Maven plugin.
Answer: Probably (sorry, i have no access to a maven install) the mvn command is a batch file (.bat or .cmd extension)
When a batch file directly invokes another one, the execution flow is transfered to the called one and does not return to the caller.
You need to use
call mvn clean install

now, when the called batch file ends, the execution continues in the caller.


Package.appxmanifest Settings for a Apache Cordova Multi-Device Hybrid App

Question: How does one set project specific settings for a hybrid app? I understand that the config.xml file provides some support using both the "preference" and "platform" elements, but there doesn't appear to be a definition as to what the possible values are.
How, for example, would I add wide tile support for a Windows Store output? In a native Windows Store project, I would specify the appropriate "VisualElements" element in the package.appxmanifest file. What are the mappings between package.appxmanifest and config.xml?
Comment: It seems to me that the manifest files are generated automatically when you build the app. Try building then search the project for AppxManifest and you should see the XML file showing up in the bin folder. The only thing is I'm not sure how to change the values of the generated AppxManifest file, because for me it only shows placeholder variables instead of my details (e.g. $username% instead of my username).
Answer: I found this blog entry tonight and tried it and it works. The instructions refer to VS2013. For those trying this in VS2015, I had to create the "cert" folder as mentioned below. Also, these instructions mention a "windows8" folder. In VS2015 the two platform folders for Windows are "windows" and "wp8" (under the other "res" subfolders, anyway). To err on the side of caution, I created those two folders, plus a "windows8" folder. I then created the xml file as specified below, edited it, and copied it to all locations.
When I built, my generated appxmanifest reflected the updated values.
http://sonyarouje.com/tag/cordova/

Create a Package.appxmanifest file under res/cert/windows8. Create a windows8 solution folder if not exist.
Open the project folder and go to bld/windows-AnyCpu/Debug and open AppxManifest.xml in notepad, copy the content and paste it in the above Package.appxmanifest file.
Double click on Package.appxmanifest file then goto Capabilities tab and choose 'Private Networks (Client & Server)'.
Save it and run the app again, this time it worked


Column to check if it has integer value or not using ADF Expression Builder

Question: I have a string column called (Code) which will always have an integer value. I want to check if a Code column got Integer data put the source value, but if Code got string value in it then put 'Invalid' in Code column. Checker column will provide which row is invalid. e.g. If Code column got String value then put the column name otherwise leave it empty.
<code>Code    CodeNewColumn    Checker
7875    7875
9856    9856
6545    6545
565L    Invalid          Code
G787    Invalid          Code
</code>
I am using Derived column in Dataflow, can anyone please help me.
Answer: Create a Derived Column with 2 columns: CodeNewColumn, Checker.
Use these expressions:
CodeNewColumn = iif(isInteger(Code),Code,'Invalid')
Checker = iif(!isInteger(Code),'Code',toString(null()))


Connect separate Heat / AC systems to a Nest E

Question: I have oil/hydro zoned heat, and a separate AC system. I have Honeywell ProSeries thermostats that have some 16 wire connectors (apparently designed to handle a nuclear power plant or something). I recently found an offer through my electric company to purchase Nest thermostats dirt cheap and they are the 'E' model. I decide to buy them to get the remote control/app features, but the Nest E has more limited wiring options compared to it's big brother (Y, G, R, W, C, O/B).
With separate systems I have separate wiring (Rc, G, Y for AC / R, W for Heat). I am quite comfortable with general electrical stuff and after reading several of the questions and answers here, I can understand that there are two separate 24v feeds (R & Rc) and since they are coming from separate transformers they should not be combined. The Nest E model doesn't support my system configuration according to their installation app, but it's just a switch, right? I could probably figure out this puzzle, but I'm looking for some confirmation so I don't fry anything.
I was thinking that perhaps I could wire the thermostat so that the transformer from the heater is driving all of the 24v power and use relays at the AC to complete the AC loops (Y/G) while isolating the two 24v sources. Is that sound thinking? I've heard of using a separate transformer for a 'C' connection (I have none now) but it's unclear to me how 24v at C relates to the R and Rc I have now.
If I just put both 24v (red) wires together in the Nest E (with power off of course) and then at the ac I cut the thermostat lines and run them into two relays; the red wire now has 24v coming from the heater so I run R/Y to one relay and hook the AC R/Y lines to the other side, and the same for the R/G combo. Perhaps there is an alternative related to the C line, but not sure what that would be. Is my thinking sound?
Updating with more details and photos:
I'm getting closer to making the changes based on my interpretation of the answer and diagram from @jwh20. My AC transformer is 40a and my heat is using dual transformers (unmarked) but lists the overall capacity at 80a. I have limited wiring and cross wiring capabilities as the boiler and control board is in the basement and the AC is in the attic, but it does appear that I have one free line in each.
AC Board:

Heater Board:

The heat board appears to wire the thermostat lines backwards (and I'm surprised this works ... seems that the thermostat doesn't care which is hot and which is neutral). I'll swap the wires on the first four zones to ensure consistent polarity since I'll be coupling the systems together.
Here is my plan:

adjust/correct heater thermostat polarity for consistency
use third wire from heat thermostat lines to connect to yellow (common) transformer line
disconnect 24v source (+/-) from AC board
connect 24v+ from heater (red) at thermostat to AC red line (to backfeed 24v power)
connect new common 24v (-) line from heater through extra line in AC thermostat bundle to the 24v (-/C) post on the AC board.

??. Thermostat currently works with no 'C' connection, is there a reason to connect C to the thermostat?
Comment: Is there a reason you want to use the hydronic system transformer to provide R/C instead of the A/C (air handler's) transformer?
Comment: only that the heat uses a pretty hefty dual transformer system which I thought would be more effective.
Comment: Can you post photos of the wiring at both ends please?
Answer: To make this work you need a common 24VAC source for both units.  Chances are that either of your existing transformers will do the job but check the 24VAC requirements for each and make sure the capacity of the transformer you choose is adequate.  If neither is, get a larger one and use it.
You'll also need a C wire which is the "neutral" side of the transformer, wired to your thermostat.  Both units will need to share the C wire so you may need to do some wiring.
I drew the following sketch which I think should work for you using the connections you said were available on your two units.
Comment: Awesome - thanks for the quick response. I'll have to review the available wires and see it there is one free for my common connection.


Grabbing the HTML within a div / class / id from another website

Question: I'm currently creating a website using Wordpress. On one of the pages I want to extract news articles from another website, but I don't want to use iframe (I want to style it with css), nor do I want the entire page, just what's within the text of the article.
I'm pretty new to coding (which is one of the reason why I'm using wordpress), so I'm not sure how to go about it. I've looked around online, but the answers are either different from what I need, or they're far beyond my understanding. If there's some sort of wordpress plugin that does the job for me, that'd be great, but otherwise I'd be grateful to be pointed in the right direction.
Thanks.
Answer: Look for RSS feed, it might contain the content you need and its easier to grab things from RSS than from HTML. Or simply download the page via any programming language into object and find the element with either REGEX or Xpath.
Or use WordPress WebScraper plugin: Here
Comment: The articles themselves don't have an RSS feed (though perplexingly the homepage of the site does).

How would downloading and accessing the HTML file (I assume that's what you meant ) work with Wordpress, and what code would I be using?
Comment: I found a ready to use plugin for you https://wordpress.org/plugins/wp-web-scrapper/
Comment: If it fits your needs, please +1 my answer, I added it there too


What business make profit (with or without upgrades) when I purchase the supplies instead of stealing them?

Question: Let's say that I have all of business that takes supplies purchased:

Which ones make profit when I purchase a full bar of supplies? (GTA$75.000)
What if I have the Equipment, Staff or both upgrade?

Please note that "making profit" means that the total price of the product generated is over the value of the supplies, giving a profit margin.
Comment: In that case, it usually works to go ghost (make sure you are a CEO before starting), or have good friends :D
Comment: As a general note, I prefer to sell in a full lobby - you get an additional 1% for each person in the lobby, which can add up to a substantial amount.
Comment: That is a good bonus, I always sell on lobbies that have at least 16 players. But before selling, I check if there are griefers or KD Farmers to make sure that my product is safe.
Comment: I check for the opposite reason ;) I love a good battle.
Comment: Fighting against other players while moving cargo sounds like a terrible combination. *sees group of Oppressors on the map from the same MC getting near*
Answer: There are two type of basic sales local and remote (+50% cash) I will break it down first amount will be local sale and second will be remote, and there is no difference if you upgrade only staff or equipment so there are 3 different amount of money you get(0 upgrade, 1 upgrade, full upgrade) and security upgrade doesn't make any difference at all.
Bunker

Without upgrade: 100.000$ / 150.000$
With Staff or Equipment upgrade: 120.000$ / 180.000$
Fully upgraded: 140.000$ / 210.000$

On biker businesses when I bought supplies the amount of product I got was different, so it looks like this:
Cocaine

Without upgrade: 60.000 - 90.000$ / 90.000 - 120.000$
With Staff or Equipment upgrade: 72.000 - 96.000$ / 108.000 - 144.000$
Fully upgraded: 84.000 - 112.000$ / 126.000 - 168.000$

Meth Lab

Without upgrade: 51.000 - 68.000$ / 76.500 - 102.000$
With Staff or Equipment upgrade: 61.200 - 81.600$ / 91.800 - 122.400$
Fully upgraded: 71.400 - 95.200$ / 107.100 - 142.800$

Counterfeit Cash

Without upgrade: 42.000 - 56.000$ / 63.000 - 84.000$
With Staff or Equipment upgrade: 50.400 - 67.200$ / 75.600 - 100.800$
Fully upgraded: 58.800 - 78.400$ / 88.200 - 117.600$

Weed farm

Without upgrade: 36.000 - 48.000$ / 54.000 - 72.000$
With Staff or Equipment upgrade: 43.200 - 57.600$ / 64.800 - 86.400$
Fully upgraded: 50.400 - 67.200$ / 75.600 - 100.800$

Document forgery ##

Without upgrade: 18.000 - 24.000$ / 27.000 - 36.000$
With Staff or Equipment upgrade: 21.600 - 28.800$ / 32.400 - 43.200$
Fully upgraded: 25.200 - 33.600$ / 37.800 - 50.400$

So to sum it up Bunker is profitable anytime, cocaine is profitable on remote sales or with upgrades, meth lab only with remote sales and upgrades, counterfeit needs upgrades and remote sale as well, weed farm only fully upgraded and remote sale and lastly document forgery is never going to be profitable with supplies bought.


How do I append a list to an empty numpy array

Question: I have a functionality that for every iteration fetches elements and appends it to a list. At the end of certain number of iterations (say 1 million) I want to append the list to a numpy array, then empty the list and continue the process.
I have declared an empty numpy array as
a= np.array([], dtype="int32")

b =[1,2,3,4] is my list for first 1 million iteration,

b =[5,4,3,2] is the list for second 1 million iteration

how do I keep on appending the list b to the numpy array a after every 1 million iteration.
I need an output as given below
array([[1, 2, 3, 4],
   [5, 4, 3, 2]])

I have tried "concatenate" and "vstack" , but the problem is the dimension for a(when empty) and b doesn't match, so the code gives error.
The list is going to be as big as 1 million, so need an cost effective method to deal with the append. I could also "vstack" elements for each iteration, but that will load the huge list every time I vstack, which would not be cost-efficient. I tried the below code, which is working just fine but I want to avoid the check at every iteration.
if any(a):
    a=np.vstack((a,b))
else:
    a=np.append(a,b, axis=0)

Is there any way I can append a list to a numpy array without performing the check.
Comment: Note that appending to a numpy array is never efficient. Numpy arrays cannot grow dynamically in size, so every concatenation will create a whole new array. If you know the maximum number of iterations you could first initialize the whole matrix and just fill it row by row. A slightly uglier approach would be to store a list of numpy arrays and create the big array in the end.
Comment: You may find this interesting: http://stackoverflow.com/a/5068182/1716866.
Comment: If you want to append to an empty array, you have to specify its dimensions.  For instance, `np.empty((0,4))`.
Answer: I would recommend not appending to the array as that can be very inefficient.  Instead, you could use deque for collecting the lists, and make an array from that only when you need it.  Here is an example:
from collections import deque
import numpy as np

lists = deque()
for i in range(1, 13, 4):
     lists.append(range(i, i + 4))

result = np.array(lists)

Now we have
>>> result
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

deque is a linked list, which means that we don't have to reallocate memory for the whole container once new elements appear.


Does damage from Caltrops with Jagged Spikes stack?

Question: As a Demon Hunter, if you place multiple Caltrops with Jagged Spikes rune on the same spot, does the damage of each one stack? Or does the monster just receive the 45% weapon damage during the trap lifetime?
Comment: I believe the monster receives damage when they trigger the trap, allowing stacking, but I can't be sure.
Answer: I haven't actually tested this specific combination, but it should work the same way as Spike Trap, eg. if you place down 10 Caltrops on the same spot as soon as a monster enters that area then they should get hit by 10x 45% weapon damage, or a bit less than 2 Spike Traps worth of damage. For what it is, it probably isn't an efficient use of your discipline, though it should stack just fine.
Comment: Considering that you can only lay 5 Caltrops, it won't hurt your discipline that much.
Comment: @MBraedley: I wasn't even aware there was a limit on how many you could lay. I usually use the rooting rune, so laying too many isn't really effective.
Comment: I don't think it lists it, but don't seem to be able to lay more than that.
Comment: @Nathew, you can only have 5 untriggered ones. But if you lay down caltrops ontop of already triggered ones they don't despawn. you can get more than 5 on one spot (so you can get that 10 at which point the dmg no longer stacks).
Answer: With the perk passive "perfectionist" you can lay up to 5... but the limiting factor is discipline.
Combined with an ability or passive that assists discipline regeneration the sky is the limit.
Comment: You still can't lay more than 5. After the first 5, they start despawning when you lay more, similar to Spike Trap. I did actually test this.


Is there a way for me to see how much volume an application is outputting?

Question: I'm trying to make a computer application which will look at the volume that Spotify and discord are outputting, and balance it accordingly so that I can hear my friends, but when they're not talking, my music is louder.
This is for a windows 10 computer, I've used pycaw to get the master volume as well as modify the master volume; however, I could not find an option to get the current volume being outputted.
from __future__ import print_function
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume, IAudioEndpointVolume, IAudioEndpointVolumeCallback

def main():
    sessions = AudioUtilities.GetAllSessions()
    for session in sessions:
        volume = session._ctl.QueryInterface(ISimpleAudioVolume)
        if session.Process and session.Process.name() == "Discord.exe":
            print("volume.GetMasterVolume(): %s" % volume.GetMasterVolume())

if __name__ == "__main__":
    main()

By doing this, I can get the maximum volume for discord (for example 1.0). However, I want to get the level of audio discord is currently outputting (for example 0.3). What would I need to replace
volume.GetMasterVolume()

to achieve this? Thanks.
Comment: [EarTrumpet](https://github.com/File-New-Project/EarTrumpet/tree/master/EarTrumpet/DataModel/Audio) has some c# code which is able to get session volume although I don't know how to translate that to python to give proper answer.
Answer: This is not a full answer, but I figured it may help someone on their way.
You should look at the Windows Core Audio API. Part of this API are 'audio sessions' https://learn.microsoft.com/en-us/windows/win32/coreaudio/audio-sessions, which are the audio sessions for the applications as they appear in the Volume Mixer, which I think are the volumes you're referring to.
There's an existing work-in-progress Python library called pyWinCoreAudio, but it appears to be incomplete and doesn't currently cover audio sessions (or in no way that I could fine). However, you can have a look at the open source (GPL) source code and it should be relatively straightforward to add the functionality to query the audio sessions and set their.
For example, with the part that is already working in pyWinCoreAudio, this is how you'd set the volume on an existing device:
import pyWinCoreAudio as wca

wca.AudioDevices[3].render_endpoints[0].volume.channel_levels = (-10, -10)

In this case, AudioDevices[3] happens to be my headset, and setting the volume to (-10, -10) sets it 10dB below max (which would be (0, 0) on both channels.
To list all the audio devices and their outputs on your system, you'd do something like:
import pyWinCoreAudio as wca

for n, d in enumerate(wca.AudioDevices):
    for rep in d.render_endpoints:
        print(f'render endpoint {n}: {rep.name} is a {rep.form_factor}')

But this is in relation to the actual devices, not the applications producing the audio (i.e. the audio sessions), which the library doesn't appear to expose yet.
Answer: I guess what you need is volume.GetMasterVolumeLevel() (source).
from __future__ import print_function
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume, IAudioEndpointVolume, IAudioEndpointVolumeCallback
from ctypes import POINTER, cast
from comtypes import CLSCTX_ALL

def main():
    sessions = AudioUtilities.GetAllSessions()
    devices = AudioUtilities.GetSpeakers()
    interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
    volume = cast(interface, POINTER(IAudioEndpointVolume))
    for session in sessions:
        if session.Process and session.Process.name() == "Discord.exe":
            print("volume.GetMasterVolumeLevel(): %s" % volume.GetMasterVolumeLevel())

if __name__ == "__main__":
    main()

Update:
What this code actually do is getting the current volume level of Windows (instead of the running applications') which I think is relative to what you want to achieve.
When you try this
print("volume.GetVolumeRange(): (%s, %s, %s)" % volume.GetVolumeRange()) # (-74.0, 0.0, 0.03125)

it will return the volume range of Windows (in my case -74.0 to 0.0) from low to high, i.e -74.0 represents the volume level on the computer is 0 while 0.0 represents the volume level on the computer is 100.
If you want to set this value, you can simply do:
volume.SetMasterVolumeLevel(-30.0, None)

Comment: When running this, I always get a negative number between 0 and about -10, regardless of application, or even if there's any audio playing from that application. Any explanation for why this is, or how it works?
Comment: Check some explanation in the update. Hope that helps.


Read file from position (to position)

Question: File-Stream/ifstreamreadbufferandseekfileposition.htm">http://www.java2s.com/Tutorial/Cpp/0240_File-Stream/ifstreamreadbufferandseekfileposition.htm
this page is able to print content of a file twice using
file.seekg(0);

So I assume that seekg(0) puts the "cursor" (in java) to the beginning of the file, and this web site: http://www.cplusplus.com/doc/tutorial/files/ confirms me.
But when I do this to a file that contains (0\n0\n0\n):
while(getline(file,line)) {
    CCLOG(line.c_str());
    CCLOG("%d",(int)file.tellg());
}

file.seekg(0);
CCLOG("%d",(int)file.tellg());

while(getline(file,line)) {
    CCLOG(line.c_str());
}

(I'm doing this in cocos2dx 2.2.2 by the way)
it prints:
0
2
0
4
0
6
-1

I don't know what I'm doing wrong. Please help
Answer: I'm not 100% sure what you're asking here (and what it has to do with Java), but if you're asking why resetting the file cursor to the beginning of the file does not work, then here's my answer:
Make sure you reset the error flags of file before you call seekg. So instead of just
file.seekg(0);

write
file.clear();
file.seekg(0);

That will successfully reset the file cursor to the beginning of the file. The reason for this is, that once you reach the end of the file, the EOF (end-of-file) flag will be set and seekg does not reset it.
Answer: The reason for the behaviour you are seeing is that, once you read to the end of the file, the eof() state flag will be set. Any attempt to read or position the file after that will trigger an error. The error resulting in a return code of ERROR, which is -1.
You can reset the state flags (all of them) using clear(). So the code should read
file.clear();
file.seekg(0);

Read file from position (to position)


.replace backslashes along with chars in a string

Question: I'm stuck on the.replace function.
I have a gallery, previewing thumbnails through this URL standard:
/uploads/admin/mcith/mcith_1157936397041.jpg

I want the URLs to be like this:
/uploads/admin/1157936397041.jpg

removing the mcith/mcith part.
I've done a small .replace script and got pretty close, but got stuck with the slashes and underscores.
Here's what I got:
v = $(this).attr("src").replace(/mcith/g,'');
alert(v);

The alert prints this:
/uploads/admin//_1157936397041.jpg

Any pointers are greatly appreciated! :)
Comment: FYI, `.replace` is a basic JavaScript function, not jQuery.
Answer: You can escape forward slashes by preceding it with a backslash:
v = $(this).attr("src").replace(/uploads\/admin\/mcith\/mcith_/g,'uploads/admin/'); alert(v);

See this example http://jsfiddle.net/AEay2/
Comment: That explains a whole lot for me, thank you very much. but there is also an underscore that needs removal, but only for the image part of the string.
v = $(this).attr("src").replace(/mcith\/mcith/g,'').replace(/_/g, ''); alert(v);

this replaced all the underscores in the url, since the thumbs are generated with the mcith_ prefix, it needs to recognize only this. any ideas? :)
Thanks again.
Comment: please see my answer ... it includes removing the specific underscore
Comment: sure, just added the trailing underscore to the regex pattern. i updated the code in my answer.
Answer: Some characters have a special meaning inside those regular expressions. These characters need to be escaped by preceding them with a backslash
v = $(this).attr("src").replace(/mcith\/mcith_/g,''); alert(v);

Comment: I blinked and it worked! thank you guys for great help and explanations.


Perfect test for uninterrupted redstone signal of a certain length?

Question: Currently I am looking for a (preferably rather compact circuit) that will test whether a certain signal has been on for X amount of seconds.
Just get a Pulse Length Detector, you might say. Only there's a problem with that. When the input signal gets turned off and then back on, the old 'test' will still be successful and a signal will be emitted.
Is it possible to somehow make a 'perfect' test for an uninterrupted redstone signal of X seconds that does not get confused by several shorter pulses?
Comment: Are you allowing command blocks in the solution?  It's still possible without them, just a lot harder.
Comment: No, is meant for vanilla survival. Sorry for not being clear in that regard.
Answer: Use a long clock of the length of time you need, that is disabled when it has no input signal and starts when it gets signal.
To make the clock only tick once: latch its output, invert it, AND it with the target signal, and feed that into the clock's enable line instead of the raw target signal. Finally, attach the inverse of the target signal to the reset line of the latch, else it will be a one-time-only circuit.
Take the output either before or after the latch, depending on whether your desired output is a pulse or a constant signal.
Comment: I think I get the general gist of the logic; I dare say I almost got that far in my head but the details are a problem. What exactly is a 'long clock'? What sort of latch? Is there any chance you could whip up a quick screenshot? The saying regarding images and a thousand words comes to mind. :)


When does Tech 5 become available for the Rebels in Empire at War?

Question: I'm playing through Star Wars: Empire at War as the Rebellion. I'm currently at Tech 4, and about to try the ninth mission Raid Over Corulag, but there is no option to steal up to Tech 5.
When is Tech 5 available? I'd like to build Mon Calamari cruisers soon.
Comment: After the Empire discovers it. IIRC the rebels can only get new tech by stealing it from the empire.
Answer: You have to steal every technology possible per set of available tech for c3p0 and r2d2. Once you've gotten the available tech in that tech level, a new group will appear for you to steal.
Comment: In addition, you don't unlock your final set of Heros (and presumably, tech level 5) until you've got every tech in the final group. Or at least that's the case in Galactic Conquest.
Answer: You need to be stealing tech from the empire consistently. After finishing Han's mission at Corulag, you should be automatically bumped up to tech 5. HTH


My swamp cooler is leaving everything in the house black, why?

Question: It's a brand new swamp cooler. I've called the landlord twice to fix it he said the belt fell off the first time then the second time he said there's nothing is wrong. It's the same problem from before. I noticed it doesn't blow as hard as it did before. It's leaving everything black in the house the walls, stove, counters, and i just saw my white curtain black where the air goes through. I'll upload a picture of that. Any ideas what can be the problem? Nonsmoking household.
Comment: If the pulleys the belt run over are misaligned, the belt could be wearing.
Comment: Is there a filter somewhere?
Comment: @PhilG Should post as an answer...
Comment: could it be mold?
Comment: Thanks ill suggest this when he comes to fix it.
Comment: Makes sense. I have a new belt and for first time in 10 yrs have black dust under vent
Answer: It is my experience that the bolt pattern used to mount the motor in a swamp cooler can easily allow the motor axis to be set not parallel with the axis of the fan shaft. When not aligned parallel the pulley on the motor, even when appearing to be lined up nicely with the fan pulley, can end up rubbing excessively on the sides of the drive belt. This can create excessive amounts of black dust as a belt wears. It is even more interesting that a new belt can be more subject to getting chewed up like this than an older used belt that has developed a glaze on its surface.


Accessing C++ class public member function from private struct data member

Question: This might be a trivial C++ semantics question, I guess, but I'm running into issues on Windows (VS2010) with this. I have a class as follows:
class A {
public:
   some_type some_func();
private:
   struct impl;
   boost::scoped_ptr<impl> p_impl;
}

I'd like to access the function some_func from within a function defined in the struct impl like so:
struct A::impl {
   impl(..) {} //some constructor
   ...
   some_impl_type some_impl_func() {
     some_type x = some_func(); //-Need to access some_func() here like this
   }
};

The VS 2010 contextual menu shows an error so didn't bother building yet:
Error: A non-static member reference must relative to a specific object

I'd be surprised if there was no way to get to the public member function. Any ideas on how to get around this are appreciated. Thanks!
Answer: You need an instance of A. A::impl is a different struct than A, so the implicit this is not the right instance. Pass one in in the constructor:
struct A::impl {
   impl(A& parent) : parent_(parent) {} //some constructor
   ...
   some_impl_type some_impl_func() {
     some_type x = parent_.some_func(); //-Need to access some_func() here like this
   }

   A& parent_;
};

Comment: Thanks, makes sense. I figured the implicit this shouldn't work because it would instead point to impl, but still seems weird I have to do this, given the call comes from an object of A which in turn calls the impl member function.


Will Lego Universe be available for digital distribution?

Question: Will be there some kind of digital distribution for Lego Universe?
Answer: The official support site says:

LEGO Universe will be available both on DVD and for download at LEGOuniverse.com. More specifics about how to get the game will become available closer to the launch date.
Comment: LEGO Universe is not currently available for download at the LEGO site, but is available on Steam for Windows.
Comment: Not true. No digital download there, even if you buy the game online at LEGO website.


How to give a Dynamic url in the redirectTo field?

Question: I want to redirect the previous url when i am entering wrong url (404) !! So i have to give a previous page url in that "RedirectTo" filed
App.module.ts
const appRoutes: Routes = [
{path: 'Sk', canActivate: [AuthGuard], children: [ { path: 'announce',
component: AnnounceComponent },{ path: '**', redirectTo: ?, pathMatch: 'full' }]},{ path: '**',component: AppComponent}];

Comment: I don't think you can, but you could redirect to a component in charge of doing another redirection
Comment: @David  Oh man !!! is there any way to redirect to previous url in app.module.ts
Answer: first import routes to component where you want to change redirectTo.
Then you can access routes in your component and change redirectTo value.
app.routing.ts :
export let routes: Routes = [
    { path: '', redirectTo: 'pages', pathMatch: 'full' },
    { path: 'pages', loadChildren: 'app/pages/pages.module#PagesModule' },
    { path: 'login', loadChildren: 'app/pages/login/login.module#LoginModule' },
    { path: '**', component: ErrorComponent }
];

exampleComponent.ts :
// importing routes
import { routes } from '../app.routing';

// i'm changing it in ngOnInit for example.
ngOnInit() {

 routes[0].redirectTo = 'login';

}

To redirect to previous page if entered url is wrong :

Create a new component, say errorComponent. Whenever url is wrong, we use this component. So in your routes do as follows

    export let routes: Routes = [
       { path: '**', component: ErrorComponent }
    ];

In errorComponent we will write go back to previous page logic.

    import { Location } from '@angular/common';

    ngOnInit() {
      this.location.back();
    }

Comment: how to find & call a previous page url while i am entering wrong url ?
Comment: But i am  facing another one issue that is while i am refreshing the page also in that Error component is  activated.So that location back is triggered
Comment: error component will trigger only if your url path is not in routes.
Comment: Sorry for the inconvenience !! that is my mistake .Once again thank you for your concern.
Comment: it does not take effect , you should update the router config dynamically


Can I use coax outlets for cable modem?

Question: I recently moved into a home where each room has a coaxial wall plate. My ISP provides internet through a cable modem, where unfortunately the cable input is in a non-ideal location. Next to that cable input from my ISP, there is a wall plate where I could connect the coax cable.
If I did that, would I be able to connect my cable modem from another room's wall plate? How could I go about testing the connections?
I unfortunately don't have access to the original owners and can't find out how they did it.
Comment: Did you have a cable service installer as part of starting or moving your service to this location? They usually have the equipment to test installed cable. Assuming there is one cable with branches, you should be able to connect the incoming cable and put the modem at another outlet. Are you mostly interested in TV, internet or both?
Comment: I had to install it myself, no cable installer as this ISP had been used previously. I am only interested in internet, other than this I have no use for the coaxial wall plates.
Comment: why don't you simply run an internet speed test, then move the cable modem and do the speed test again
Answer: Here's the caveat with old coaxial cable. If this is an older house, it might have cable already, but it's probably RG-59. This is from back in the days of analog signals, well before we were sending digital signals down them. If you have a satellite dish, you'll note they need RG-6 or better.
What's the difference? Shielding
Now, it's possible there's no interference on those old lines. In which case, stick your modem on and everything should be fine. Your modem should have a web interface and it should tell you the signal strength the modem is getting. Hook a computer to it and then hook the cable up. If you don't get enough signal, you might need to do some work (or call the cable company and have them do it for you, although they might charge you for that).
If you need more signal, here's some tips

Find the main splitter. It might be in the attic, in the basement (if you have one), or is sometimes outside. All your coax will tie into it. With a multi-port setup they probably have a serial splitter. They should have labels saying things like -3.5dB. Your room might be connected to one that says something like -7dB. Make sure it's on one of the smallest dB loss ports. If not, replace it with either another multi-connector (one that has minimal loss) or just get a double-male and connect them together.
Make a new run with better shielding. You should be able to find RG-6 readily, and probably RG-6 quad shield as well. This would eliminate a lot of signal loss back to the cable connection point. You can buy non-compression ends for this as well, if you don't want to invest in a coax end tool.
Comment: And "burn up" is not necessarily like... set on fire, but a weaker signal triggers excessive signal re-processing that will damage the cable modem much faster than normal.
Comment: Thank you for the answer. Is there a risk if I plug my modem into the RG-59 cabling and the shielding prevents it from working? Is the only risk that it won't work? (don't want to ruin my modem or mess anything else up)
Comment: It won't ruin the modem, you just don't want to plug it in and leave it either. They can burn up over time trying to work with the weaker signal, hence why I say log into the modem's console and check
Comment: @Nelson that's probably the reason I had to replace my cable modem every 24-30 months for quite some time! After a couple of calls to the ISP about very slow performance they replaced the line to the house (squirrels, it seems like the insulation), and the guy ran a single new line to the jack in my office. I haven't had to replace a modem since. #TIL! Thanks!!
Comment: That notion of wearing out faster because the signal is weaker sounds extremely dubious to me.
Comment: @Reid Remember that your cable modem has a transmitter to send data back to the node. If the incoming signal is weak, the transmitter assumes it has to send at a higher power to compensate. That in turn can accelerate [heat death](https://superuser.com/questions/482190/is-it-possible-for-a-router-to-go-bad-with-time), where the component runs hot over an extended period of time.
Comment: That's not how electronics wear. If it's operating within spec, which we can be pretty confident of, it should be able to do so more or less indefinitely. This reeks of urban legend.
Comment: @Reid loss signals = resend.  Resend means using more of the modem to do the same thing.  I don't know why this is hard to believe.  The modem is now sending more packets than necessary, and/or running at a higher power rating than necessary.  For a modem to fail in 3 years is perfectly within specification also.
Comment: It's hard to believe because it's wrong. ;)
Answer: There's probably a gob of cable terminations in your basement or utility room. You'll need to find the two cables that go to the rooms involved (or simply place your modem there). With any luck they're labeled.
Using a pass-through splicer, connect those two. You should now have a continuous route between rooms, and the only question is whether the resistance and noise introduced by the splicer will substantially degrade your signal.
Comment: To add to this -- the easiest way to find out which cable is which (if not labelled) is to short the connector in the room, and then start measuring resistance from center to shell for each cable end in the basement octopus collection.  If you don't have a volt-ohm meter, you can get one for very cheap at any hardware store; many of these come with a "continuity" setting that will beep if there's a connection.
Comment: @opius - that should work. Whatever type of cable you have it has basically two conductors, the center wire and the braided shell(s).connect them at the one end then test for that at the other end. If the shorted wire goes to a splitter before the other end that you want to test, then any cable coming out of the splitter would also be shorted.
Comment: @CarlWitthoft I don't follow - to short the connector I could just use a short wire/paperclip on the wall plate? And then use the volt-ohm meter from all the cables?
Comment: It's worth checking for existing shorts before shorting the cable in the room; if any are already shorted, discount them (e.g. mark with coloured tape) before you start.
Answer: To elaborate further:  You have a couple of options

Plug modem in where it comes into house. (Probably not ideal due to location)
Join outside cable to wall plate, then plug modem in in central utility room.  (Again, might not be in central location.
Plug modem in as in #1.  Many modems have a built-in MOCA adapter (or you can buy one) and connect it to the wall plate.  Join all coax connections in utility room via an N-way splitter, and set up another MOCA adapter and a wifi hub in another room.

FYI, I've done #3 -- works pretty well!

Can I use coax outlets for cable modem?


JsonFormat$Value.hasLenient() Error on Rest Call

Question: I'm building a set of microservices in Spring Boot. I've got one service which interfaces with the database and has a series of RESTful endpoints which other apps can hit. Many of these table entities are complex objects and are served up as a JSON object but some are simple parameters and so are served as strings. When I hit the main DB service endpoints, all data is returned fine without issue.
I have a series of other applications which consume this data in various ways. Because many objects are reused across applications (the DB service response shape, the person entity POJO, etc), I've got a package made with some common classes. Each app imports these common classes and then makes calls to the main DB service via RestTemplate. Because the response is always wrapped in a standard way, I am getting the values by performing an exchange which expects a ParameterizedTypeReference of the response wrapper with the appropriate POJO or Java variable (String, int, etc).
As of 5 months ago, all was good. The app was deployed to a server and is still operating normally. However, I recently went back in to the code in order to make some modifications and now I find that when I run the app locally some of the endpoints fail with the following error:
java.lang.NoSuchMethodError: com.fasterxml.jackson.annotation.JsonFormat$Value.hasLenient()Z

I thought at first that perhaps the two POMs were out of sync and one was pulling a newer version of Jackson but after hard coding the version in the POM to be 100% certain they were the same (version 2.10.1), it still has the same issue. It should also be noted that the method in the error message appears to have been added in version 2.9 and has not been deprecated as of this moment in time. This error only happens when trying to retrieve data from endpoints returning POJOs and not when the data type is a String. It may also be relevant that the call appears to never actually leave the app before throwing an error as the DB service endpoint never gets hit.
Any ideas why I'm getting this error and how I could resolve it?
Response Object:
public class DatabaseServiceResponse<T> {
    @JsonInclude(Include.NON_NULL)
    private List<T> entities;

    @JsonInclude(Include.NON_NULL)
    private String error;

    [getters and setters ommitted]
}

Person Service:
public List<Person> getPeople() {
    List<Person> people = new ArrayList<>();
    HttpHeaders headers = getHeaders();
    HttpEntity<Object> requestEntity = new HttpEntity<>(null, headers);
    ResponseEntity<DatabaseServiceResponse<Person>> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, new ParamaterizedTypeReference<DatabaseServiceResponse<Person>>() {});  // Fails on this line
    if (response.getStatusCode() == HttpStatus.OK) {
        people = response.getBody().getEntities();
    } else {
        throw new ServiceException("Error retrieving people");
    }
    return people;
}

public List<String> getPersonTypes() {
    List<String> personTypes = new ArrayList<>();
    HttpHeaders headers = getHeaders();
    HttpEntity<Object> requestEntity = new HttpEntity<>(null, headers);
    ResponseEntity<DatabaseServiceResponse<String>> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, new ParamaterizedTypeReference<DatabaseServiceResponse<String>>() {});  // Works fine here
    if (response.getStatusCode() == HttpStatus.OK) {
        personTypes = response.getBody().getEntities();
    } else {
        throw new ServiceException("Error retrieving person types");
    }
    return personTypes;
}

Person App POM:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath />
</parent>

Common Elements POM:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.1</version>
    <scope>provided</scope>
</dependency>

UPDATE
I believe the external library and the potentially out-of-sync POM files was a red herring. I have copied all of the relevant classes into the main project to remove the dependency on the external package and I have the same issue. I've also tried completely upgrading all versions to the latest and still no luck. Jackson, for whatever reason, will map JSON to a String or a list of Strings but just will not map my JSON to a POJO.
Comment: The issue may be related to the `provided` scope that means that such dependency should be [provided by JDK or container](https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#dependency-scope), then actual version of the dependency may differ in some environments.  If you use default `compile` scope, this issue should be resolved.
Comment: have you tried building dependency tree to make sure that there are no transitive dependencies pulled? try using `mvn dependency:tree` and look for all lines with `jackson`.
Comment: When building the dependency tree, all show the same `jackson` version: 2.10.1
Comment: In addition to Alexs comment - maybe it's worth checking the classpath when running the app, and check if it may contain some unexpected paths.
Comment: Tried changing the scope to compile but no luck - the issue persists!
Answer: I finally worked out what was wrong here and it feels so absurd that I don't believe anyone would ever have gotten to the right answer without the code in their hands. It was only by pulling all the code back into one place and then seeking to find another means of mapping the object via Jackson (using an ObjectMapper directly as opposed to letting the RestTemplate figure that out) that I stumbled upon the true problem.
There is an audit class which is a property on my Person object which contains the normal, basic properties of created by, created date, modified by, modified date. These dates are LocalDateTime objects in the standard ISO-8601 format. It turns out that Jackson can no longer process the string straight into the LocalDateTime object and needs "help". By adding a setter which takes the date as a string and does a LocalDateTime.parse(date) to set the actual property, I'm now able to successfully hit the endpoints at will.
I still have no clue why the exact error above was thrown, but there you have it. By not specifying a way to help translate from a String to the LocalDateTime object, I received the JsonFormat$Value.hasLenient() error from Jackson.
Answer: I had a similar issue.
In my case @Eyowzitgoin's answer helped me figure out my issue. I had a maven dependency conflict on the jackson annotations.
I was trying to run some tests, and all was fine on the command line but intellij had an issue knowing which version to pick. I had 2.10.3 explicitly declared, but 2.8.5 was being picked up through a transitive dependency.
2.10.3 has a method JsonFormat$Value.hasLenient, but 2.8.5 doesn't.
I was using the JsonFormat annotation on a String variable in a pojo, and intellij was expecting to be able to call the method, but was unable to do so.
In my case I didn't resolve the root of the problem because the variable should have been a LocalDate, so I changed the type and removed the annotation and the issue went away.
I would expect that if I'd left the types as they were and the annotation in place, and instead resolved the dependency issue and made sure that only one of the versions was present/declared the issue would also have been resolved.
Answer: Working on cucumber-report + playwright + java 1.8
These dependencies made my day:
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.10.1</version>
        </dependency>

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Angular doesn't recognize app in IE8

Question: I'm using AngularJS with Asp.NET MVC. I have loaded app.js which includes
var app = angular.module('app', []);

I then call my controller like so
app.controller('OrderController', ['$scope', '$http',... function ($scope, $http...)

I am getting this error
Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Anybody Help?
Comment: Which version of Angular are you using?
Comment: What does your html look like?
Comment: @WilliamLepinski 1.2.25
Comment: @oztune
was:  now because it's  thanks to Srinivas Paila
Answer: Try using data-ng-app instead of ng-app on index.html page, if you are using any  angular version less than < 1.3.0. As angular no more supports IE8 from 1.3.0 version.

Angular doesn't recognize app in IE8


What's the point of the bear coins?

Question: Throughout the game, you can collect bear coins - up to a maximum of 99. Unlink lives, saving the game saves the number of bear coins you have. Once you get to the hidden world, Boomer mentions how he doesn't accept bear coins like the rest of his brothers. However, most of the rest of his brothers don't seem to accept them either.
As far as I know, they're useful at the beginning of the game; you need 55 for the mirror and the shell (one is 50, the other 5), each of which you trade to a bear to get a banana bird. Outside of that, all of the bears trade for prizes, and none of them accept money.
Aside from buying those first two items, is there any use for the bear coins?
Answer: The Bear Coins can be used to purchase special items, like the mirror or shell, as mentioned. They can also be used to purchase advice from the Bazaar as well as compete against Cranky at the Swanky Sideshow tents spread throughout the world.

What's the point of the bear coins?


Submit iOS apps update

Question: I am planning to do an apps update submission.
However, the new apps update need some data patching on server. I am unable to patch the data immediately, because the existing users with old apps will be facing issues with the new data.
Any idea how to resolve this issue?
Comment: fetch data with version checking?
Comment: so do you means i export two different set of data according to version?
Answer: You need to maintain the old data almost indefinitely.
Plenty of users will not update their apps (no matter how much you want them to. ) for a large variety of reasons.
So for this time around you should move the new data to a different location (and reflect that new location in your app.) to ensure that old users maintain a connection to the old data and new users can use new data.
In the future it might be prudent to have your app stop to function when a new dataset and application is published and harass the user to update.
Comment: The unfortunate catch-22 that you have is that you currently have users out there with a app which cannot be 'forced to update'
Comment: i will force user to perform apps update, which means i block them if they do not update the apps. I understand your point, but this is major update, so many data had to be change. I was wondering is there any better way for doing this.
Comment: actually i can. I've apply something like CoC does. repeatedly prompt user for update, and do not allow them to login. Of cause this gonna make me lost some user.

Thank for the feed back. i asking this just to see whether there is better way of doing this.
Comment: @Steven this could only be done if the existing app has some knowledge about this. so CoC asks the server which version 'should' be running, and then harasses the user if they need to update.
Comment: yea. this feature has included in my apps when first launch.  Anyway, thank for the answer. i think i will apply dataset for different apps version.

Submit iOS apps update


Is it possible to add a custom shortcut in Jupyter Notebook?

Question: I would like to add a markdown cell in Jupyter Notebook using a shortcut, since adding a new cell and changing it to Markdown cell takes so much steps and feels painstaking at times.
But it seems that there is no such shortcut; so now I'm searching for a way, if any, to add a custom shortcut in Jupyter Notebook.
Is it possible to define a custom shortcut?
Answer: Jupyter has a way to customize keyboard shortcuts. However, I'm not sure if what you're asking is available. I don't find it that tedious to add a Markdown cell by quickly pressing esc (a or b) m enter in succession, where (a or b) is if you want the cell above or below the current cell.


Apache permissions issue cant upload files

Question: I have recently built my first Debian 6 squeezebox as a LAMP server and all appear to be running fine. It is using the latest Mysql, PHP and Apache.. all installed using the apt-get command.
I have created several domains, and they are all running nicely (CMS systems) with one major exception.
I cannot use the CMS website functions to upload extensions or plugins without changing permissions to 777 first, and then dropping them back to 755 afterwards. Its almost as though the apache service is not running as root, or does not have permissions to the files.. and is more like a public user.
For my personal sites, I suppose this is borderline acceptable, but if I make a CMS for someone else, I cant have them unable to upload their own extensions.
Can anyone advise the best practice (happy to redo everything) for making sure the apache service has the full rights it needs to files and directories so I can leave permissions at 755.. or hell, even 604.
I have created a container in the root called www, and this directory contains a folder in the name of the domain i.e example.com, and in there are folders backup,logs,public.. the website files are in the public directory.
I have configured virtual name servers for all, and of course enabled the site.
Thank you in advance for any assitance
Comment: You never want Apache to run as root.
Comment: Yeah, I get that, careless comment.. but it is not running with any apparent authority at all.
Comment: What do your error logs say when you try to upload?
Comment: No error message, already 100% determined to be a permissions issue with the apache service. If I set permissions to 777 all is ok, anything else like 604 or even 775 leads to 'unable to copy file to this location' etc
Answer: imho you need to create one upload-directory(say) under website public directory and set it's permission to 775..
second thing, the uploaded files might be first going /tmp, so you need to move the uploaded file from there to upload-directory..do ensure that your file is getting successfully uploaded under /tmp first..
Comment: Yes but this is the problem.. I have tried setting to 775 and there is STILL a permissions problem. It is like the apache service is running with the permission 5. I need to make the apache service the owner, or at least in the group.
Comment: the ONLY way I can get the webservice to function properly in terms of being able to add plugins etc using the CMS functions is to set the whole website to 777
Comment: [as posted here](http://stackoverflow.com/questions/5356167/apache-user-does-not-exist) try to check who owns the apache process and also try making nobody as the owner of your *upload-directory*
Answer: For me (on Ubuntu) I had to add umask 002 to /etc/apache2/envvars in order to get Wordpress to upload plugins/images with 775 permissions instead of 755 (i.e. allow anyone besides Apache and root to change the uploaded files)


delete button using destructive style and UIAlertAction

Question: I am new to swift and I am working on a contact app. I would like to be able to delete the contact that I have when a user clicks the delete button but I am having trouble implementing it. At the moment I have a function that lets me see the contact when the user clicks Show Details and also has a cancel button. But for my delete I want to be able to get rid of whatever I contact I click on. I will paste the code down below.
  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedContact = contacts[indexPath.row] as? Contact
        let name = selectedContact!.contactName!
        let actionHandler = { (action:UIAlertAction!) -> Void in
            //            self.performSegue(withIdentifier: "EditContact", sender: tableView.cellForRow(at: indexPath))
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "ContactController")
                as? ContactsViewController
            controller?.currentContact = selectedContact
            self.navigationController?.pushViewController(controller!, animated: true)
        }

        let alertController = UIAlertController(title: "Contact selected",
                                                message: "Selected row: \(indexPath.row) (\(name))",
            preferredStyle: .alert)

        let actionDelete = UIAlertAction(title: "Delete" ,
                                   style: .destructive,
                                   handler:nil)

        let actionCancel = UIAlertAction(title: "Cancel",
                                         style: .cancel,
                                         handler: nil)
        let actionDetails = UIAlertAction(title: "Show Details",
                                          style: .default,
                                          handler: actionHandler)
        alertController.addAction(actionCancel)
        alertController.addAction(actionDetails)
        alertController.addAction(actionDelete)
        present(alertController, animated: true, completion: nil)
    }

Comment: You need to provide a non-nil handler for your alert's delete button. Start with that.
Comment: would i pass the function that will do the deleting in the handler?
Comment: Yes, you already did something very similar with the Show Details handler and passing `actionHandler`
Comment: You can do the same thing you did for the "Show Details" handler. Though there's no need to define a separate variable for the closure.
Answer: You can try this for all with/out action as no need to make a var then add it , you can addAction with it's handler directly
alert.addAction(UIAlertAction(title: "Delete", style:.destructive, handler: { (action) in

      contacts.remove(at:indexPath.row)
      tableView.deleteRows(at:[indexPath],with:.fade)

}))

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedContact = contacts[indexPath.row] as? Contact
    let name = selectedContact!.contactName!
    let alertController = UIAlertController(title: "Contact selected",
                                            message: "Selected row: \(indexPath.row) (\(name))",
        preferredStyle: .alert)

     alertController.addAction(UIAlertAction(title: "Show Details", style:.default, handler: { (action) in

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "ContactController")
            as? ContactsViewController
        controller?.currentContact = selectedContact
        self.navigationController?.pushViewController(controller!, animated: true)

    }))

    alertController.addAction(UIAlertAction(title: "Delete", style:.destructive, handler: { (action) in

        contacts.remove(at:indexPath.row)
        tableView.deleteRows(at:[indexPath],with:.fade)

    }))

    alertController.addAction(UIAlertAction(title: "Cancel", style:.cancel, handler:nil))

    present(alertController, animated: true, completion: nil)
}

Comment: where does this go in the code exactly. I am not sure where to place it.
Comment: @Sh_Khan, what is the different between `.destructive` and `default` style when add the alert action. I try both but seems no different when I delete one item in my collectionView.


Windows form doesn't close after close?

Question: I made a very simple program, but when I close it using the red X at the top right, I can still see it in the Windows Task Manager listed under processes. The program is still running and consuming memory. How can I avoid this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;

namespace PS3Controller
{
public partial class Form1 : Form
{
    GamePadState pad;

    Vector2 centroIzq = new Vector2(138, 132);
    Vector2 centroDer = new Vector2(139, 252);

    float distancia = 20f;

    float ledIzqAngulo = 0;
    float ledDerAngulo = 0;

    float ledIzqVelocidad = 0.0022f;
    float ledDerVelocidad = 0.0022f;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        pad = GamePad.GetState(Microsoft.Xna.Framework.PlayerIndex.One);

        if (pad.Buttons.Y == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledTtriangulo.Visible = true;
        else
            ledTtriangulo.Visible = false;

        if (pad.Buttons.X == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledCuadrado.Visible = true;
        else
            ledCuadrado.Visible = false;

        if (pad.Buttons.A == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledX.Visible = true;
        else
            ledX.Visible = false;

        if (pad.Buttons.B == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledCirculo.Visible = true;
        else
            ledCirculo.Visible = false;

        if (pad.DPad.Left == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledIzq.Visible = true;
        else
            ledIzq.Visible = false;

        if (pad.DPad.Right == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledDer.Visible = true;
        else
            ledDer.Visible = false;

        if (pad.DPad.Up == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledArriba.Visible = true;
        else
            ledArriba.Visible = false;

        if (pad.DPad.Down == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledAbajo.Visible = true;
        else
            ledAbajo.Visible = false;

        if (pad.Buttons.Start == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledStart.Visible = true;
        else
            ledStart.Visible = false;

        if (pad.Buttons.Back == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledSelect.Visible = true;
        else
            ledSelect.Visible = false;

        if (pad.Buttons.LeftShoulder == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledL1.Visible = true;
        else
            ledL1.Visible = false;

        if (pad.Buttons.RightShoulder == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledR1.Visible = true;
        else
            ledR1.Visible = false;

        if (pad.Buttons.BigButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            ledHome.Visible = true;
        else
            ledHome.Visible = false;

        if (pad.Triggers.Left > 0)
            ledL2.Visible = true;
        else
            ledL2.Visible = false;

        if (pad.Triggers.Right > 0)
            ledR2.Visible = true;
        else
            ledR2.Visible = false;

        lblIzqX.Text = pad.ThumbSticks.Left.X.ToString();
        lblIzqY.Text = pad.ThumbSticks.Left.Y.ToString();
        lblDerX.Text = pad.ThumbSticks.Right.X.ToString();
        lblDerY.Text = pad.ThumbSticks.Right.Y.ToString();

        Vector2 ledIzqPos = new Vector2(
            (float)Math.Cos(ledIzqAngulo) * distancia,
            (float)Math.Sin(ledIzqAngulo) * distancia);

        Vector2 ledDerPos = new Vector2(
            (float)Math.Cos(ledDerAngulo) * distancia,
            (float)Math.Sin(ledDerAngulo) * distancia);

        if (pad.ThumbSticks.Right.X == 0 &&
            pad.ThumbSticks.Right.Y == 0)
        {
            ledPadDer.Top = 139;
            ledPadDer.Left = 252;
        }

        if (pad.ThumbSticks.Left.X == 0 &&
            pad.ThumbSticks.Left.Y == 0)
        {
            ledPadIzq.Top = 138;
            ledPadIzq.Left = 132;
        }

    }
}

}
Comment: Could be a number of reasons.  Can you add more details?
Comment: Show us your code, so we can help you. Show us the code where the program close
Comment: which language (okay, i guess c#) where is the code, etc. We can't thought-reading
Comment: We need some code. For example, the Closed or Closing event hander method if these are being handled.
Answer: Be sure to close all the thread of that process...Sometime, the thread keep process to keep executing though the form is closed...You can do this in OnClosing method of windows form......
Comment: I set timer1.Enabled to false in FromClosing.
No problem now.
Answer: Are you sure its your app that is still running or is it YourApp.vshost.exe? The vshost is for Visual Studio and will always run while you have your project open.

Windows form doesn't close after close?


Makefile unable to compile file

Question: Netbeans 7.3
gcc 4.5.3
I've looked at some of the answers to this question but I don't see my specific case.
The makefile generated by Netbeans seems to be correct. The output given in the Netbeans terminal window gives a No rule to make target ReadList.cpp , which seems to be wrong. I can't figure out what's going on.
The output window shows:
"/usr/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make[1]: Entering directory `/c/home/skidmarks/Projects/SLIP/slip'
"/usr/bin/make"  -f nbproject/Makefile-Debug.mk dist/Debug/Cygwin_4.x-Windows/slip.exe
make[2]: Entering directory `/c/home/skidmarks/Projects/SLIP/slip'
make[2]: *** No rule to make target `ReadList.cpp', needed by `build/Debug/Cygwin_4.x-Windows/ReadList.o'.  Stop.
make[2]: Leaving directory `/c/home/skidmarks/Projects/SLIP/slip'
nbproject/Makefile-Debug.mk:94: recipe for target `.build-conf' failed
make[1]: *** [.build-conf] Error 2
make[1]: Leaving directory `/c/home/skidmarks/Projects/SLIP/slip'
nbproject/Makefile-impl.mk:39: recipe for target `.build-impl' failed
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 375ms)

The makefile used shows:
${OBJECTDIR}/SlipReadList.o: SlipReadList.cpp
    ${MKDIR} -p ${OBJECTDIR}
    ${RM} $@.d
    $(COMPILE.cc) -g -w -MMD -MP -MF $@.d -o ${OBJECTDIR}/SlipReadList.o SlipReadList.cpp

The makefile appears correct and works for other files. I have verified that the .cpp and .h files are in the same directory and are in the same directory as other successfully compiled files. Anyone have an idea what's wrong?
Comment: Well the error says that the missing file is ReadList.cpp not SlipReadList.cpp
Comment: Well that helps. I don't have a ReadList.cpp (but I think you have solved my problem), sign and thanks.
Answer: make[2]: *** No rule to make target `ReadList.cpp', needed by `build/Debug/Cygwin

now take a look at your make file:
${OBJECTDIR}/SlipReadList.o: SlipReadList.cpp

you have readlist.cpp initially, but the makefile wants a SlipReadList.cpp. Because of this the compiler has no idea what to do with readlist.cpp. A simple fix would be the change the naming of the file to SlipReadList.cpp

Makefile unable to compile file


How can two default dictionaries of lists be merged into one

Question: the d1 is  defaultdict(<type 'list'>, {'A': [4, 4, 4, 4], 'S': [1]})
the d2 is  defaultdict(<type 'list'>, {'A': [4, 4, 4], 'B': [2], '[]': [4, 4]})

How to merge these two dictionaries into one?
The expected output should be
the d3 is  defaultdict(<type 'list'>, {'A': [4], 'B': [2], 'S':[1] ,'[]': [4]})

In the resultant dictionary the multiple values should be made into one
Comment: @kojiro It was probably downvoted because of 'What have you tried?', but I agree that people should leave a comment.
Comment: I'd imagine the question was downvoted because the OP didn't show any attempt at solving the problem.
Comment: The link between the input and the desired output is completely unclear. What logic governs "merging" `[4, 4, 4, 4]` and `[4, 4, 4]` to get `[4]`? What if I had to merge `[1, 2, 3, 4]` and `[1, 2, 3]`? What about `[1, 2, 3, 4]` and `[5, 6, 7]`?
Comment: @Karl Knechtel: It's not completely unclear, it's possible to make a reason guess and `set` based solutions should be able to deal with cases like those latter two you give just fine even though the OP doesn't have anything similar in their example.
Answer: You should be using a set as the default_factory attribute, as sets don't preserve duplicate elements:
d1 = defaultdict(set)

To convert your existing defaultdicts to use sets, try this:
defaultdict(set, {key: set(value) for key, value in d1.iteritems()})

And for old Python versions:
defaultdict(set, dict((key, set(value)) for key, value in d1.iteritems()))

Comment: In converting the existing dictionary of list into set I am getting an error                                                           d3 = defaultdict(set, {key: set(value) for key, value in d1.iteritems()})
                                             ^
SyntaxError: invalid syntax
Comment: You're probably using a version of Python below 2.7. See my update.
Comment: the d3 is  defaultdict(, {'A': set([4]), 'S':
the d4 is  defaultdict(, {'A': set([4]), 'B': set([2]), '[]': set([4])})
Now How can I get the value of key 'A' in d3 to be just 4 instead of set([4]
Comment: My bad. You have to convert it to a list: `list(d3['A'])[0]`.
Answer: try:
d1.update(d2)
for val in d1.values():
    if len(val) > 1:
        val[:] = [val[0]]

Comment: FYI it doesn't work, and it modifies `d1` instead of producing a separate merged `defaultdict(list)` result in `d3`. The `for` loop does nothing to the values of `d1`.
Comment: @martineau Did you test it, what doesn't work? I don't have python installed on the laptop on which I'm working now (that's why I wrote untested). I know it modifies `d1` but why is this a problem? I supposed that `d1` and `d2` weren't needed anymore. And if I recall correctly, the values of `d1` do get modified, because they are lists (ints or tuples wouldn't have worked).
Comment: This is the final value of `d1: defaultdict(, {'A': [4, 4, 4], 'S': [1], 'B': [2], '[]': [4, 4]})`.
Comment: @martineau Oh, well I guess I have to look into this then, clearly my memory failed me...
Comment: You can try using one of the online Python interpreters, like [this one](http://codepad.org/).
Comment: You need something like `for key,val in d1.iteritems():` and `d1[key] = [val[0]]` in the `for` loop (ignoring the changing of `d1` issue).
Comment: Although you're intuition about the lists being modifiable does seem to make sense, it's not working that way in this case. I'm going to look into the matter further myself when I have a chance.
Comment: If the `val = [val[0]]` is replaced with `val[:] = [val[0]]` in the `for` loop, then `d1` _will_ be modified as you intended -- otherwise a new value is just being assigned to the variable `val` rather than to the list to which it currently refers.
Comment: @martineau thanks for your help and looking further into this! I don't know if you were the one who downvoted my answer (which was fully legit at that time), but if your were, would you consider undoing your vote since it's working know? (btw, it's 'your intuition', not 'you're' :D)
Answer: The following does what you said you want:
from collections import defaultdict

d1 = defaultdict(list, {'A': [4, 4, 4, 4], 'S': [1], 'C': [1, 2, 3, 4]})
print 'the d1 is ', d1
d2 = defaultdict(list, {'A': [4, 4, 4], 'B': [2], '[]': [4, 4], 'C': [1, 2, 3]})
print 'the d2 is ', d2

d3 = defaultdict(list, dict((key, set(value) if len(value) > 1 else value)
                                for key, value in d1.iteritems()))
d3.update((key, list(d3[key].union(set(value)) if key in d3 else value))
                                for key, value in d2.iteritems())
print
print 'the d3 is ', d3

Output:
the d1 is  defaultdict(<type 'list'>, {'A': [4, 4, 4, 4], 'S': [1], 'C': [1, 2, 3, 4]})
the d2 is  defaultdict(<type 'list'>, {'A': [4, 4, 4], 'C': [1, 2, 3], 'B': [2], '[]': [4, 4]})

the d3 is  defaultdict(<type 'list'>, {'A': [4], 'S': [1], 'B': [2], 'C': [1, 2, 3, 4], '[]': [4, 4]})

Note that I added a list keyed with 'C' to both d1 and d2 to show what happens for a possibility not mentioned in your question -- so I don't know if it's what you'd want to happen or not.


If you escape Zarya's ultimate, is it possible to get caught in it again?

Question: There are a few heroes who are able to escape Zarya's Graviton Surge ultimate after being caught in it, including Reinhardt (through Charge) and Reaper (through Wraith Form).
If I escape Zarya's ultimate using one of these characters, is it possible to get caught in the ultimate again if I get too close?
Comment: It *is* a gravitational surge, so it would make sense that if you don't escape it area of effect that it would pull you back in.
Answer: Yes, it is possible. You can easily test this by Blinking just once as Tracer, it won't move you out of the area of effect and you'll quickly be caught again.
Comment: @DanmakuGrazer I don't know what gives you that idea, nor do I feel like debating it. That was a perfectly good use of the word that fits with a common definition. I just want to caution you against randomly criticizing people's word choices without anything to back it up.
Comment: Certain abilities like Winston's leap do not have sufficient momentum to escape in the first place. I also have trouble escaping if I'm near the epicentre as Pharah.
Comment: @DanmakuGrazer Since you enjoy nitpicking, here's the second [definition of epicenter](http://www.thefreedictionary.com/epicenter) from the Free Dictionary: " The focal point of a usually harmful or unpleasant phenomenon or event; the center:". So that's perfect.
Comment: @KizTrap Nitpicking, but epicenter is not the correct word in this context. Just center is fine.
Comment: @DCShannon But that's only used in metaphors, not in actual physical events like a Graviton Surge.
Comment: @DCShannon "Epicenter is properly a geological term identifying the point of the earth's surface directly above the focus of an earthquake. No doubt this is why the Usage Panel approves of **figurative extensions of its use in dangerous, destructive, or negative contexts**." From what you linked. I don't see what's wrong with correcting people when they're wrong, but this is getting way off topic now.


Why is there an extra button showing up at the end of UIActionSheet display?

Question: Any ideas why there is an extra / empty button showing up at the end of the UIActionSheet display?
ALSO - Is there a way to anchor this action sheet at the top of the screen (anchored to the UIToolBar that it launched from)?

Code to generate this:
self.actionButtonActionSheet = [[UIActionSheet alloc] initWithTitle:@"Pick an action"
                                                           delegate:self
                                                  cancelButtonTitle:@"Dismiss"
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:@"Go to Today", @"Share", @"Journal", @"completedStr", nil];
[self.actionButtonActionSheet showFromToolbar:self.actionBar];

(self.actionBar is the one on the top)
I have tried taking this code out and creating a sample project to demonstrate this, but in that project, everything seems fine.
Wondering what am I missing...
Any help / pointers will be greatly appreciated.
Comment: did you try with `yourtabbarcotnro.tabbar.translucent = FALSE;` because in ios7 that by default true.
Answer: Try replacing [self.actionButtonActionSheet showFromToolbar:self.actionBar]; with [actionsheet showFromTabBar:self.view]; to show from top


Biased coin probability

Question: 1) Biased coin flipped twice. There is 6/9 probability that the coin will land heads for at least one of the two flips. What is the smallest number of times that I can flip the coin for at least 99% certainty that it will land heads at least once?
My answer: $n\left(\dfrac{6}{9}\right)^2 = .99 \Rightarrow n = 2.227$
so at least 3 flips
2) Biased coin lands head w/ probability p and start with empty urn. Flip coin n times. each time coin lands head, blue ball into urn. Each time it lands tail, green ball in urn. After finishing flipping the coin, draw k balls from urn one at a time. Replacing each ball you draw before drawing another. If all the k balls you drew are blue, what is the probability that all n balls in the urn are blue?
My answer: I am assuming it is in .99 to 1 range, because since all the balls drawn are blue, it is hard to know the probability for the green ball.
Comment: Do not attempt to deface your own question.  As you can see, it's pointless anyway, because the original content can always be recovered.
Answer: Question 1.  If $X$ is a random variable that counts the number of heads obtained in $n = 2$ coin flips, then we are given $\Pr[X \ge 1] = 2/3$, or equivalently, $\Pr[X = 0] = 1/3 = (1-p)^2$, where $p$ is the individual probability of observing heads for a single coin flip.  Therefore, $p = 1 - 1/\sqrt{3}$.
Next, let $N$ be a random variable that represents the number of coin flips needed to observe the first head; thus $N \sim {\rm Geometric}(p)$, and we need to find the smallest positive integer $k$ such that $\Pr[N \le k] \ge 0.99$.  Since $\Pr[N = k] = p(1-p)^{k-1}$, I leave the remainder of the solution to you as an exercise; suffice it to say, you will definitely need more than 3 coin flips.
Question 2.  Your answer obviously must be a function of $p$, $n$, and $k$.  It is not possible to give a numeric answer.  Clearly, $X \sim {\rm Binomial}(n,p)$ represents the number of blue balls in the urn, and $n-X$ the number of green balls.
Next, let $Y$ be the number of blue balls drawn from the urn out of $k$ trials with replacement.  Then $Y \mid X \sim {\rm Binomial}(k,X/n)$.  You want to determine $$\Pr[X = n \mid Y = k] = \frac{\Pr[Y = k \mid X = n]\Pr[X = n]}{\Pr[Y = k]}.$$  It is trivial to see that $\Pr[Y = k \mid X = n] = 1$, and $\Pr[X = n] = p^n$.  The denominator is the tricky part:  You need to write $$\Pr[Y = k] = \sum_{x=0}^n \Pr[Y = k \mid X = x]\Pr[X = x],$$ by the law of total probability.  Again, I leave the remainder of the solution for you to work out.
Comment: I am getting k to be a less than 3. 2/sqrt(3)*(1-1/sqrt(3))^(k-1)=.99 -> k = 1.178. What am I doing wrong? and thank you so much for your help
Comment: $$\Pr[N \le k] = \sum_{j=1}^k \Pr[N = j] = 1 - (1-p)^k.$$  Now substitute and solve.
Comment: I am sorry, but can you explain Pr[Y=k∣X=n]=1 and the denominator Pr[Y=k] on how you got those
Comment: $X$ counts the number of blue balls in the urn.  $Y$ counts the number of blue balls drawn from the urn in $k$ trials.  So, given that all the balls in the urn are blue, what is the probability that you will always draw a blue ball?
Comment: The probability is 1, since it only blue balls were only drew.

Biased coin probability


WSS implies IID?

Question: If I have two WSS (wide-sense stationary) processes, $x(t)$ and $y(t)$, can I state that they are IID (independent and identically distributed) sequences?
Answer: A strict-sense stationary process, $x(t)$, has its $n$-order statistics preserved throughout the time, where $n \in \mathbb{N}_{++}$. That is, the $n$-order statistics of the random variables $\left\{x(t_1), x(t_2), \cdots, x(t_n)\right\}$ is identical to the set $\left\{x(t_1+\tau), x(t_2+\tau), \cdots, x(t_n+\tau)\right\}$, for any $\tau \in \mathbb{R}$. Therefore,
$$
p_{x(t_1), x(t_2), \cdots, x(t_k)}(x_1, x_2, \cdots, x_k) = p_{x(t_1+\tau), x(t_2+\tau), \cdots, x(t_k+\tau)}(x_1, x_2, \cdots, x_k),
$$
where $p(\cdot)$ is the probability density function (PDF).
However, strict-sense stationary processes are a strong statement, and it is suffice for many applications to guarantee that the first- and second-order statistics are stationary. We refer these type of process as weak-sense stationary process or, for short, WSS process.
For these processes, the mean (its first-order statistic) is simply a constant:
$$
\mu_x(t) = E[x(t)] = \int_{-\infty}^{\infty} x p_{x(t)} (x)\;dx = \mu_x(t+\tau) = \mu_x.
$$
And the autocorrelation (a second-order statistic) only depends on $\tau$, that is
$$
R_x(t, t+\tau) = E[x(t)x(t+\tau)] = \iint_{-\infty}^{\infty} x_1x_2 p_{x(t), x(t+\tau)} (x_1, x_2)\;dx_1\;dx_2 = \phi_x(\tau).
$$
Similarly, if $x(t)$ and $y(t)$ is jointly WSS, then
$$
R_{x,y}(t, t+\tau) = E[x(t)y(t+\tau)] = \iint_{-\infty}^{\infty} x y p_{x(t), y(t+\tau)} (x,y)\;dx\;dy = R_{x,y}(\tau).
$$
You just do not realized before that WSS implies IID because the notation $R_{x,y}(t, t+\tau)$ is commonly simplified to $R_{x,y}(\tau)$. You can change $t$ freely, the PDF $p_{x(t), y(t+\tau)} (x,y)$ will be the same :)

WSS implies IID?


Magento: How to update Category Name via install script

Question: How to update Category Name via install script in Magento?
Answer: <?php
//increase the max execution time
@ini_set('max_execution_time', -1);
//memory_limit
@ini_set('memory_limit', -1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

// Start Despaly All Product Meta Title And Description
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

$categories = Mage::getModel('catalog/category')
                         ->getCollection()
                         // magic is prepared here..
                         ->addAttributeToSelect('*')
                         // then the magic happens here:
                         ->addAttributeToFilter('level', array('eq'=>4))
                         ->load();
    if (count($categories) > 0):

        foreach($categories as $category):

            $catId = $category->getId();
            $category = Mage::getModel('catalog/category')->load($catId);

            if($catId==1465):
                $CategoryName = $category->getName();
                $CategoryNewName = "New Name";

                $category->setName($metaTitle);

                $category->save();

                $check = $category->getName();
                echo "
";
                print_r($check);
                echo "\n";
            endif;

        endforeach;
     else: echo "No Results";
    endif;

?>

Answer: Install scripts are part of the application so can use the same models as normal.
$category = Mage::getModel('catalog/category')->load($categoryId);
// can alternatively use loadByAtrribute('name', $oldName)

$category->setName($newName)
         ->save();

Answer: $installer->run("
    UPDATE catalog_category_entity_varchar SET value = '[value]' WHERE value_id = [value_id]
");

Answer: Magento 2 category Attribute Value Update by Script with level of the category
<?php
    //increase the max execution time
    @ini_set('max_execution_time', -1);
    //memory_limit
    @ini_set('memory_limit', -1);

    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    use \Magento\Framework\App\Bootstrap;

    include('app/bootstrap.php');

    $bootstrap = Bootstrap::create(BP, $_SERVER);

    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();

    $appState = $objectManager->get('\Magento\Framework\App\State');

    $appState->setAreaCode('frontend');

    $categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');

    $categories = $categoryCollection->create();

    $categories->addAttributeToSelect('*');
    $categories->addAttributeToFilter('level', array('eq'=>2));
    $categories->load();

    if (count($categories) > 0):

            foreach($categories as $category):

                $catId = $category->getId();

                $category = $objectManager->create('Magento\Catalog\Model\CategoryFactory')->create()->setStoreId(0)->load($catId);

                $childrenCategories = $category->getChildrenCategories();

                if(!$childrenCategories->count()) continue;

                    $CategoryName = $category->getName();

                    $category->setLandingPage(82);
                    $category->setDisplayMode("PAGE");
                    $category->save();

                    $checkpage = $category->getLandingPage();
                    $checkmode = $category->getDisplayMode();

                    echo "
";
                    print_r($CategoryName);
                    echo "
";
                    print_r($checkpage);
                    echo "
";
                    print_r($checkmode);

            endforeach;
         else: echo "No Results";
        endif;

    ?>


How to define number columns with CHECK constraints in MySQL database

Question:
SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'number,
hofYear number(4) CHECK (hofYear BETWEEN 1901 AND 2155),
hofSeries VAR' at line 22

Code:
CREATE TABLE mospo_HallOfFame(
    hofdriverId number,
    hofYear number(4) CHECK (hofYear BETWEEN 1901 AND 2155),
    hofSeries VARCHAR2(50) NOT NULL CHECK (hofSeries IN ('BritishGT','Formula1','FormulaE','SuperGT')),

Comment: You appear to be trying to use *Oracle* syntax on *MySql*. As you have noticed, that won't work; review the [documentation](https://dev.mysql.com/doc/refman/8.0/en/data-types.html)
Answer: Try:
CREATE TABLE mospo_HallOfFame(
  hofdriverId INTEGER,
  hofYear INTEGER CHECK (hofYear BETWEEN 1901 AND 2155),
  hofSeries VARCHAR(50) NOT NULL CHECK (hofSeries IN ('BritishGT','Formula1','FormulaE','SuperGT')));

This changes the data types to INTEGERs and a VARCHAR.
Comment: MySQL has a `YEAR` datatype.