How to access a file from resources folder in test in springboot

Question: My file "products.yml" is located in src/test/resources/configs folder. I have defined config import in my application.yml in springboot
spring:
  config:
    import:
      - optional:configtree:src/test/resources/configs/

I am trying to get this "products.yml" filepath using @Value annotation in my configuration class
@Configuration
public class ProductConverterConfiguration {

@Value("${products}")
private String productsYamlFile;

System.out.Println("Got the file as: " + productsYamlFile);
}

Springboot is unable to see that file when I try to run bazel test for that class it fails with null pointer exception.
I tried giving absolute path in the application.yaml and it works.
But I need the relative path since I wont have the same host when I deploy this application. Can someone help me with this?
Comment: Does this answer your question? [Spring boot: How to read resource from classpath in unit test](https://stackoverflow.com/questions/43428305/spring-boot-how-to-read-resource-from-classpath-in-unit-test)
Comment: When you deploy the application, you won't have a `src` folder either. So `src/test/resources/configs` is definitely wrong there.
Comment: Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Answer: Can you try this code ?
application.yml
spring:
  config:
    import:
      - optional:configtree:classpath:configs/

ProductConverterConfiguration class
@Configuration
public class ProductConverterConfiguration {

    @Value("${products}")
    private String productsYamlFile;

    @PostConstruct
    public void init() {
        System.out.println("Got the file as: " + productsYamlFile);
    }
}

(can you chare product.yml if it doesn't work)


require.js is not loading my module

Question: I am using require.js and a library. Unfortunately it looks like when the library is loaded the result comes back as null. Sorry I may be a noob when it comes to using require.js
postmonger.js
    (function(root, factory){
       if(typeof define === 'function' && define.amd) {
        define('postmonger', [], function(){ return factory(root); });
        }else {
            root.Postmonger = factory(root);
        }
    }(this, function(root){
        root = root || window;
var Postmonger;
if (typeof(exports) !== 'undefined') {
        Postmonger = exports;
    } else {
        Postmonger = {};
    }
Postmonger.noConflict = function(){
        root.Postmonger = previous;
        return this;
    }
        console.log(Postmonger);
        return Postmonger;
    }));

Code that loads the postmonger library "customActivity"
define([
    'js/postmonger'
], function(Postmonger){
    'use strict';
   // console.log(postmonger);
    console.log(Postmonger);
});

My runtime script

When I load the page. The first console.log returns an object and the second returns Null. I must be missing something.
Answer: Try using postmonger instead of js/postmonger.
define([
    'postmonger'
], function(Postmonger){
    'use strict';
   // console.log(postmonger);
    console.log(Postmonger);
});

Edit - Why does javscript load but AMD module is null/undefined.
When requires sees path js/postmonger it tries to download the file at js/postmonger.js which it finds and loads successfully. But in this file we have a named module with name postmonger with following code
define('postmonger', [], function(){ return factory(root); });

So module with name js/postmonger is never defined and hence you get undefined. (You should be getting undefined as per my understanding, but you have mentioned it as null)
Comment: but why does my javascript load?
Comment: Updated answer to answer your comment.

require.js is not loading my module


Are there incomparable functions?

Question: Given $\mathbb R^{(0,1)} = \{f:(0,1)\to\ \mathbb R \mid f\text{ is a function}\}$ we define the relation $$f \le g \iff f(x) \le g(x), \forall x \in (0,1).$$
The problem requires to show that this is an order relation, which I did, but then it asks if there are any incomparable elements in $\mathbb (R^{(0,1)},\; \le)$ and also it asks if $\mathbb (R^{(0,1)},\; \le)$ is a lattice. I don't really know how to approach this part.
I'm new to order theory, but here's what I tried:
I know that two elements are comparable if $x \le y$ or  $y \le x$ which should work here, but then I thought what if some $\lim f(x) = \infty$ for some $x \in (0,1)$, is $f(x)$ still comparable with any function from $\mathbb (R^{(0,1)})?\ (1)$ I can't figure this (1) out.
For the second part where it asks if $\mathbb (R^{(0,1)}, \le)$ is a lattice if the condition from (1) is acomplished then  $\mathbb (R^{(0,1)}, \le)$ is a chain (sequence) then we know that every chain (sequence) is a lattice.
Answer: Well, did you consider something simple like $f(x)=\frac12$ for all $x\in (0,1)$ and $g(x)=x$ for all $x\in(0,1)$?
As for finding meets and joins of elements, did you consider the obvious candidates $x\mapsto\min(f(x),g(x))$ and $x\mapsto\max(f(x),g(x))$?
You were on a reasonable track with "two elements $f$ and $g$ are not comparable if $f\nleq g$ and $g\nleq f$." By definition then, there would have to exist an $x$ such that $f(x)\nleq g(x)$ and also an $x'$ such that $g(x')\nleq f(x')$. In words: both of the functions have to climb over each other at some point. Hence, the simple example above.
Comment: So if I take for example $h(x) \ = \ max(f(x), g(x)) \ or \ h(x)  \ = \ min(f(x), g(x)) $ there will always exist meets and joints so $f \ and \ g$ are comparable?
Comment: @GeoBadita That comment sounds very confused, as if you are twisting two of my answers into one line of though. Slow down a bit. I'm saying that the $f$ and $g$ I gave in the first paragraph demonstrate two incomparable functions.  In the second paragraph, I'm saying that max(f,g) is the join of f and g, and min(f,g) is the meet of f and g.
Comment: Finally I understood I can solve it now, thank you very much, now I realise what I wrote in the last comment!

Are there incomparable functions?


linux install on single boot macbook pro 6,2

Question: novice here: i am trying to reasonable wipe anything remaining of this macbook for a clean linux install again.. while installing python/eclipse things got flaky and froze up and i had to shut down and restart.. downhill from there.. won't shutdown properly. won't boot.. so i'm ready for a new reformat of the drive and new install (i'm all backed up).. with that said. i am on a live usb and mounted the sda2 and ran the command 'efibootmgr' at the terminal.. what i got was:

mint mint # sudo efibootmgr
BootCurrent: 0000
Timeout: 5 seconds
BootOrder: 0000,0080
Boot0000* ubuntu
Boot0080* Mac OS X
Boot0082*
BootFFFF*

not sure what this means other than ubuntu is booting 'first'. i only use the linux os. so do i need/want to have the mac os in this boot process? unless i need the mac os for something i don't know about. just thinking this might be the problem with things getting corrupted on a regular basis. simply just trying to run linux on an old macbook pro. any help/thoughts appreciated. thank you.
update: i am logged in with a live usb and when doing a 'fdisk -l' command i find:

     Device Boot      Start         End      Blocks   Id  System
    /dev/sda1               1        2047        1023+  ee  GPT
    /dev/sda2       609517568   625141759     7812096   82  Linux swap / Solaris
    /dev/sda3   *        2048   609517567   304757760   83  Linux
but when i run gparted: it shows /dev/sda1 as linux-swap and /dev/sda2 as ext4. those are the only 2 partitions.
also on sda2 i get "...attempt to read block from filesystem resulted in short read while trying to open /dev/sda2 Couldn't find valid filesystem superblock.."
Answer: Read the contents from the following link:
https://help.ubuntu.com/community/MactelSupportTeam/AppleIntelInstallation
It contains official installation instructions for Ubuntu on Apple computers. Read carefully and follow the tutorial step by step in the "single boot" section. I hope it helps.
Comment: those 'official' install instructions don't work. but these work perfectly. . http://heeris.id.au/2014/ubuntu-plus-mac-pure-efi-boot/#fixing-efi
Comment: Thank you. I have done this several times. Currently I am booting to a black screen. Nothing else.


Can't scan with Simple Scan

Question: After upgrading to Ubuntu 20.04.1, I tried to scan a document.
The Document Scanner recognizes the existence of the scanner, but issues a caveat (INVALD ARGUEMENT) and terminates.  It will not scan any documents.  Meanwhile, the scanner issues a caveat (SCANNING TO COMPUTER) and has to be "rebooted" to go back to an idle state.
I have never had a problem with Simple Scan on Ubuntu 14.04, 16.04, or 18.04, but now, on 20.04, it refuses to work.  Any advice would be appreciated.  (I have no problem printing.  Scanner is an HP mw180)
Answer: A utility that has been a great success for many users with a modern scanner is sane-airscan. The file you want to install is here.
If it works for you, I would be very interested in the outputs you get for scanimage -L and airscan-discover. It would help other users.
Comment: Gwen Walcott has no need to respond. A more co-operative user has supplied the requested information and confirmed that sane-airscan works with this device.
Answer: I wish I had seen this question and the response sooner.  I had the same problem and reported it here:
Ubuntu 20.04 upgrade HP Envy 5640 scanner stopped working
The problem went away when I upgraded to 20.10 last week, so I don't think I can provide any useful outputs for debugging purposes.  But do say if there is anything I can do which would be helpful here.

Can't scan with Simple Scan


How can I drill a straight hole without a drill press?

Question: I'm making some pull up bars with 1 1/8" diameter holes and have some questions about how I should drill the holes:
Right now I'm planning on using spade bits. A drill press is not practical in this situation, but I could use one if I had to. The poles are 6" x 6" x 10', and a small imperfection will span across 5' to magnify. Any suggestions on some sort of portable drill press I could clamp onto the wood to use?
Is there a better tool for this job? Ideally it should be inexpensive/rentable.
Answer: If you are set on using a hand-drill, there are jigs available that will keep the drill perpendicular to the object being drilled.  Alternatively, holding a level against the drill will help you keep it aligned.
I would suggest using a Forstner bit instead of a spade bit.  Spade bits can jump around a bit, tear out and are not that precise. They are good for rough work, but a Forstner bit will give you a much cleaner cut.
That being said, a drill press is the best tool for this, and they can be purchased relatively inexpensively.  You could also find a  "maker" workshop in your area, or a college with a shop where often you can rent time and use their tools.
Comment: Sounds like a perfectly good excuse to buy a drill press!
Comment: I know a guy who has a huge drill press, so I guess this is the way to go, I'll just have to drill them before I bring them to the work-site.
Comment: Just a note: Any portable "drill press" jig I've ever used, was crap. You may be able to find a good one, but it's likely going to be expensive.
Answer: For your safety, you absolutely must use a drill guide that is firmly clamped to the workpiece. Whether you buy one or make one is up to you. This diameter bit is too large for you to be able to control it by hand (and a spade bit will be worse than forstner in this regard as well). I gave myself a black eye when trying to drill holes this large and the drill got away from me... with that diameter you are generating a whole lot of torque. Any unevenness in your angle will make the bit catch. Hard. My general guideline is anything > 3/4" diameter gets a guide.
Alternatively, you can you a router straight bit with a guide riding on a template... depending on the depth of the hole you need.
Comment: Thanks for the safety advice! I will keep that in mind next time. Unfortunately, I don't think a router will be ideal in this situation.


Select latest message from conversation

Question: I have two tables, conversation_tbl and conversation_reply_tbl
conversation_reply_tbl
-------------------------
|  conversation_reply_id|   //auto increment id
|  reply_message        |   //message text
|  user_id              |   //the user who sent the message
|  datetime_sent        |   //date and time of message sent
|  status               |   //values '0' or '1' (read or not)
|  conversation_id      |   //relation to the conversation
-------------------------

conversation_tbl
-------------------------
|  conversation_id      |    //auto increment id
|  from_user            |    //the user who sent the message
|  to_user              |    //the recipient
|  datetime_created     |    //date of the message created
|  gallery_id           |//the gallery where the message started from
-------------------------

Now I use the conversation_reply_tbl to store all the messages that go on in a conversation and conversation_tbl to store the conversation main data.
Now, I want  to select all conversations that the user is involved in but I want to show the most recent message of every conversation, just like how it's done in famous websites and apps such as 'WhatsApp' or 'Facebook'.
Could this be done in one query or do I have to use a function with PHP?
Answer: Here is how you can get that information with one query:
select     t.*,
           last.*
from       conversation_tbl t
inner join (select   conversation_id, max(conversation_reply_id) conversation_reply_id
            from     conversation_reply_tbl
            group by conversation_id) all_lasts
        on all_lasts.conversation_id = t.conversation_id
inner join conversation_reply_tbl last
        on last.conversation_reply_id = all_lasts.conversation_reply_id
left join  (select   conversation_id
            from     conversation_reply_tbl
            where    user_id = :the_user_id
            group by conversation_id) user_conv
        on user_conv.conversation_id = t.conversation_id
where      (     user_conv.conversation_id is not null
           or    t.to_user = :the_user_id )

Note the left join, as it might be that the targeted user has not yet replied with a message, but was the to_user of the starting message. The where clause makes an or of both situations: if the message thread has a message of the user, or if the user is the target of the initiating message, the query should return that conversation.
Comment: I updated the query: in an additional paragraph I explain the changes.
Comment: Thank you so much once again @trincot, now it works :)!
Comment: Hey there @trincot, I am sorry to bother you, but there is a slight issue with the query that you have given me, when I send a message and a new conversation is started, the message won't be shown on the recipient side because there is no data of him on the `conversation_reply_tbl`
Answer: If I understand what you're trying to do correctly, something like this would provide you with the record if provided the appropriate conversation_id.
Get the conversations which the users is a part of
SELECT conversation_id FROM conversation_tbl WHERE from_user = ?

With that id, get the last message that was sent.
SELECT datetime_sent, reply_message FROM conversation_reply_tbl
WHERE datetime_sent IN (SELECT MAX(datetime_sent)
FROM conversation_reply_tbl WHERE conversation_id = ? )

Comment: Understandable :). It's nice getting multiple solutions, as we never truly know how you'll use it. One of us is bound to get it right! Glad you got what you needed.
Comment: Thank you @KadeM. but I have gone with "trincot's" method above.. It is more efficient and crammed in one query.
Answer: I assume that you save all the conversation messages under reply_message column of conversation_reply_tbl table.
In that case, you can try this
SELECT T2.conversation_id, T2.reply_message
FROM conversation_tbl T1  INNER JOIN  conversation_reply_tbl T2 ON
T1.conversation_id = T2.conversation_id
WHERE (T1.from_user = $userID OR T1.to_user = $userID)
GROUP BY T1.conversation_id
ORDER BY T2.datime_sent DESC;

Select latest message from conversation


Dealing with a strong laning combo early game?

Question: In MOBAs (LoL, HoN, Dota, etc.) occasionally you'll get paired vs. a strong laning combo with heavy harassment potential in a dual lane (such that coming near the creeps to lasthit/fight/counterharass will only get your char's head bit off). In cases where you both can and cannot trust your laning partner (as in, you know he's good vs you know he's not good), what are your options to deal with this?
Comment: What does MOBA stand for?
Comment: This might vary pretty heavily between games too.
Comment: @Anna, Multiplayer Online Battle Arena, apparently. I had to look it up myself ... but then I don't play these. Hopefully someone will add a tag excerpt ...
Answer: If you're against a strong laning combo and you cannot rely on your own laning partner, your best bet is to keep your minions between you and the other champions and to use your front-most tower as a "third man".
If you stand behind your minions and out of range of your opponents, you can take potshots at the enemy champions when they are open, get the killing blow on enemy minions when those potshots are not safe to get, and reap the experience and levels from the minion kills. You can coast through your first several levels this way, gain new abilities, and buy gear to counter the champions you're up against (armor against melee, magic resist vs. mages, etc). Your laning partner will also benefit from this, provided they aren't trying to tank the enemy champions past your minion wall.
Hanging out near your front-most tower will result in minions dying faster (and getting you more experience), opening up more "last hits" (since if a tower hits a minion with full health, it gets knocked down into its "one more hit" range, and makes it that much harder to get harassed or ganked.
This strategy will hold you over until after the initial laning phase, when the enemy team starts coordinating ganks and tower takedowns. At that point, you should be powerful enough to be more viable and will be able to use that advantage coupled with team coordination to push back any encroachment, snag a few kills, and take advantage of their temporarily-reduced champion count to push a tower in a weak lane.
If you can rely on your laning partner but you're still not confident that you have the right composition to go against your competition, the same strategy works as well. In this case, you'd have yourself and your lane partner buy items that can help mitigate the effectiveness of the competition, including defending against their damage type, buffing damage types they are weak against, and making sure your movement speed is faster.
One thing to keep in mind is you should keep checking on the items your competition is purchasing. In many cases, the competition won't be paying attention and will be using general item specs, which means you can more easily counter what they are buying. Monitoring the items the competition is using is important in any game, but is even more important if they start with a composition advantage.
In addition, if you managed to get a competent jungler on your team, exploit the advantage of additional experience, gold, and the ability to put pressure on random lanes to mitigate enemy effectiveness.
Above all else, don't die, and stress to your laning partner that they should do their best to stay back and away from possible gank distance. Deaths mean extra gold and experience for the other team, which will only worsen your situation.


Angular.js, how to pass value from one component to any other

Question: Im begginer with Angular.js, so if I dont explain something enought, I will add it to question, just tell me.
I have: A component.js A template.html B component.js B template.html.
A component.js has $scope.isActive = true, and code changes value as needed. This attribute works in template A template.html.
Problem is, that I want to use same value, for B template.html. I have no idea how to pass it, I have also B component.js working with B template.html, if this matters somehow.
Right now Im trying to use $scope.isActive from A component.js in B template.html, but it does nothing, I guess it comes undefined.
This is how I try to use it in B template.html

Answer: The best solution is to move $scope.isActive to a new 'root' component that contains both 'component A' and 'component B'.
Then you can pass / modify its value using input/output bindings in the 'component A' and 'component B' definitions like:
component A definition:
angular.module('app').component('componentA', {
    templateUrl: 'component-A.html',
    bindings: {
       isActive: "<", // use to bind property as component input
       isActiveChanged: "&" // use to bind a METHOD that changes the property in the root component controller
    }
});

component A template (component-A.html):

component B definition:
angular.module('app').component('componentB', {
    template: 'component-B.html',
    bindings: {
       isActive: "<", // use to bind property as component input
       isActiveChanged: "&" // use to bind a METHOD that changes the property in the root component controller
    }
});

component B template (component-B.html):

root component definition:
angular.module('app').component('root', {
    templateUrl: 'root-component-view.html', ,
    controller: 'RootComponentCtrl'
});

root component controller:
angular.module('app').controller('RootComponentCtrl', ['$scope', function($scope) {
   // INPUT: This property is shared with both 'component A' and 'component B'
   $scope.isActive = true;
   // OUTPUT: This method is shared with both 'component A' and 'component B' and can be called from both in order to change the value of $scope.isActive in the RootComponentCtrl
   $scope.isActiveChanged(isActive) {
      $scope.isActive = isActive;
   };
}]);

root-component-view.html template:

   <component-a
      is-active="isActive"
      is-active-changed="isActiveChanged(isActive)"
   ></component-a>
   <component-b
      is-active="isActive"
      is-active-changed="isActiveChanged(isActive)"
   ></component-b>

Notice that binded properties are accessed in the component view/template using the '$ctrl' object like '$ctrl.isActive' as opposed to simply using 'isActive' which refers to the component's $scope.isActive property in the component controller.
To resume:
The shared property is set in the root component controller using:
$scope.isActive = true;

The shared property can be seen in the root component template using:
...>some html text content plus this is {{isActive}}<...

The shared property is passed to componentA and componentB in the html that defines them in the root component view using:
<component-a
      is-active="isActive"
      is-active-changed="isActiveChanged(isActive)"
   ></component-a>
   <component-b
      is-active="isActive"
      is-active-changed="isActiveChanged(isActive)"
   ></component-b>

The shared property is visible in componentA / componentB templates using:
...>some html text content plus this is {{$ctrl.isActive}}<...

The shared property is visible in componentA / componentB controllers using:
   this.isActive // not $scope.isActive

The shared property can be changed from componentA / componentB controllers by calling the method:
$ctrl.isActiveChanged({data: data})

Which actually will call the method in the root component controller and pass the updated value to the $scope property:
$scope.isActiveChanged(data)


Calculating euclidean distance using PyTorch with no loops (only using vectorization)

Question: I am currently trying to work through the MIT Deep Learning and Computer Vision course (EECS 498-007 / 598-005) Assignment 1 by myself, which seems to have a rough equivalent in Stanford CS 231n.
Problem-formulation:
Create a function, which computes the pairwise euclidean distance inputs: xtrain,xtest. Dimensions: [N,x,x] and [M,x,x] (with x being the same number)
output: distance-matrix of shape [N,M] expressing the distance between each training point and each testing point.
There is given a hint in the assignment:
Try to formulate the Euclidean distance using two broadcast sums     and a matrix multiply.
I am trying to implement this mathematical operation using broadcasting, where the middle term is a simple matrix-multiplication
I am struggling with the tensor-shapes. My implementation so far is as follows:
def euc_no_loop(x,y):
  #hint: two broadcast sums
  xsq = torch.sum(x**2,axis=1)
  print(xsq.shape)
  ysq = torch.sum(y**2,axis=1)
  print(ysq.shape)
  #and one matrix multiply
  mixprod = -2 * x.view(x.shape[0],-1).matmul(y.view(y.shape[0],-1).T)
  print(mixprod.shape)
  euc_dist = torch.sqrt(xsq + mixprod + ysq.unsqueeze(1).T)
  return euc_dist

With inputs being:
x = torch.randn(5,3,3)
y = torch.randn(3,3,3)
shapes become:
xsq: [5,3]
ysq: [3,3]
mixprod: [5,3]
And output dimension becomes [3,5,3].
Many other StackOverflow threads exist, where numpy is used - but the numpy dot-product seems to be more flexible than torch.matmul.
Example on numpy-solution: Compute L2 distance with numpy using matrix multiplication
I simply don't understand where I am going wrong.
Comment: It's a bit unclear what you mean by euclidean distance as Euclidean distance is generally defined between two points in (Euclidean) space, whereas each element of `xtrain` and `xtest` are instead arrays of shape `[x,x]` in your example
Comment: It seems that you have too many dimensions in `xtrain` and `xtest`. And in fact the example in numpy that you linked has only two-dimensional rather than 3-dimensional inputs. Please verify the dimensions of your inputs
Comment: That is a good point.

The point is, that the first dimension is number of images in each set, and thus they need not be same size. The other two dimensions are corresponding pixel values in a matrix-grid. Thus, the pairwise distance is to be calculated between corresponding pixel-values between each, and to be summed giving a total distance between training-image i and test-image j in euc_dist[i,j].
Answer: Input tensors probably should have two dimensions in order to compute pairwise distance. So I assume that those x by x matrices should be summed altogether like (N, x, x) => (N)
def euc_no_loop(x, y):
  # Suppose x has (N, x, x) and Y has (M, x, x) dimensions
  xsq = torch.sum(x**2, dim=(1, 2))  # (N,)
  print(xsq.shape)
  ysq = torch.sum(y**2, dim=(1, 2))  # (M,)
  print(ysq.shape)

  mixprod = -2 * x.view(x.shape[0], -1) @ y.view(y.shape[0], -1).T  # (N, M)
  print(mixprod.shape)

  euc_dist = torch.sqrt(xsq.unsqueeze(1) + mixprod + ysq.unsqueeze(0))  # (N,1)+(N,M)+(1,M) => (N, M)
  return euc_dist

Or just flatten the input tensors
x = x.flatten(start_dim=1)
y = y.flatten(start_dim=1)

Comment: This seems to behave exactly as intended. So much simpler!
Thank you so much


When to max Essence Flux(W) over Mystic Shot(Q) on Ezreal?

Question: Most Ezreal guides I've read recommend maxing Mystic Shot(Q) first but recently I see a lot of progamers and high ELO players max his Essence Flux(W) first after getting the token point in Mystic Shot(Q) and Arcane Shift(E). However, I still see other high end players max Mystic Shot(Q) first, too.
After checking up on the exact values of the skills I see Essence Flux(W) having better scaling base damage at a higher Mana cost as well as having the advantage of the attack speed buff/debuff scaling with level.
His Mystic Shot(Q) gets a shorter cooldown at the cost of higher mana cost with lower damage increase than Essence Flux(W).
Is it always better to max Essence Flux(W) first or does it depend on specific situations in which it is better to max one over the other?
Note: I only mean AD Ezreal, not AP Ezreal and with a build like Boots->Phage->Sheen->Trinity
Comment: I personally see it as a matter of player preference.
Comment: AP Ezreal should ALWAYS build Lichbane over Trinity Force.
Comment: Don't encourage people to go AP Ezreal. It is a troll build and doesn't work anymore (one of the most recent patches should see to that)
Comment: @ccreason, I am unsure which patch you are referring to. I went back several month worth of patches and the only remake they had for Ezreal is lowering the mana cost on his Essence flux and Trueshot barrage. So I'm not sure why you think it "doesn't work anymore." I personally prefer AD Ezreal but I certainly wouldn't consider AP Ezreal a troll build.
Comment: Well, for one thing, AP Ezreal relies on three spells to do his AP burst, one of which is his escape, and the other two having rather large cooldowns that, I admit, can be cooled down faster with his Q; however, that is AD damage, and an AP Ez would rather put points in his W and E than his Q to get more damage out. The AD ratios are better than his AP ratios, and the AP ratios supposedly did/will get a massive nerf soon. If not, I still think that an AD Ez would outclass an AP Ez. however, I believe than an Hybrid build is better than both if allowed to freefarm for eons.
Comment: @ccreason your argument is sound, but I reguarly play AP ezreal with great results. and your blatantly ignoring how much burst he does after lich bane. Frankly, your letting your personal opinions get in the way of your clinical thinking and ragging on someones idea rather than giving the asker or answerer advice. Hit the forums guy, this isn't the place.
Comment: My answer is nearly a year old, a lot has changed in that time. AP Ezreal isn't the ideal build for him, but it still works (just like AP Tristana, AP MF, AP Cait, and so on). For instance, Blue Ezreal is quite possibly one of the strongest AD builds in the game, provided you know how to use it properly. As for AP Ezreal, I generally lose the games I play in when we have an AP Ezreal on our team.
Answer: I generally max my W first for three reasons:
<code>Harass
Buffing teammates
Stacking my passive
</code>
The reason I get it to harass, is because you can shoot your opposing lanemate through his minions, and it makes it slightly harder for him to farm with that debuff.
The buff it provides your teammates when pushing towers down is paltry at best if you max it second. Maxing it first, however, means that it will be Lv 4-5 by the time your towers are going down. Its a very good utility spell for the team!
His W makes stacking his passive extremely easy early game. If your support is doing it right, you can get 2-3 stacks on your passive with just one W! That means you're able to harass or farm at a +30% rate over your opponent BEFORE taking into account the debuff placed on him by said W.
Sure its not nearly as spammable as his Q, but you use less mana when harassing for slightly less damage, but the ability to harass through minions where he thinks he's safe from your wrath. Besides, the buff/debuff (damage too!) scales well with levels, whereas the Q only scales damage (the CDR doesn't scale at all, so why bother maxing it first?) and isn't as useful early game (in my opinion).
Hope that helps!
Comment: The Q's CD does scale with level. It's 6 / 5.5 / 5 / 4.5 / 4.
Comment: I meant the CD it gives for your other abilities! Sorry for the miscommunication! :)
Comment: After the recent (early August) nerf bat taken to Ezreal, I haven't noticed any changes in what I mentioned in my answer regarding his W. I still recommend leveling his W first for harass, but if you've got a killbot lane going on with, say, Ezreona or Ezcrank, then his Q is worth it for the damage buff it received.
Answer: This depends a lot on how you are going to build your Ezreal and who you are laning against.
AP Ezreals will always want to max their W first since that is the skill that is used to nuke harass their enemy.
If you are building AD Ezreal at bottom against another AD, it is smart to alternate between Q and W to balance the benefit of the faster Q and the W's attack speed debuff. This allows advantageous straight up trades with the enemy AD carry.
In the case you are laning against an AP champion with an AD Ezreal then maxing the Q first will result in better trades.
Please note that the one weakness of AP Ezreal and maxing W first is the inability to push very fast. W is a Champion only skill so you can't use to against minions and with less points in Q (higher CD) he can't push as much. In most cases this is perfectly fine early game but in mid game it might become a problem if the enemy keep pushing to your tower and you lose a lot of CS because of it.
Comment: I updated my question with a note that i only mean AD Ezreal. An example of W first is http://www.youtube.com/watch?v=Twdy0pcFAWg&feature=player_embedded#t=1223s
Comment: @Jay I wish to note that I pay an extremely brutal AP ezrael and I max Q first for many reasons. I don't wish to defend my position here, only to say that its viable to do so.


How would you find the values in an array that equal the sum a specified number?

Question: I'm working on creating a basic function that takes in 2 parameters -- array and num.
In the array are a list of numbers and the output could essentially generate 3 results:

0 with no two numbers that equal the sum equal to num.
1 variation of two numbers that is equal to the sum that is num
Multiple variations of 2 numbers that equal the sum that is num

I've been working with filter and reduce but haven't been able to produce the desired output.
Let's say I have a nums array of [3,6,9,18] and have a specified num value of 15.
var findNumSum = function(nums, num) {
function val(a, b) {
    a + b === num;
    var es = [a, b]
    return es;
}

var result1 = nums.filter(val); // [3,6,9,18]
var result2 = nums.reduce(val); // [[6, 9], 18]] -- I've been able to isolate the num values but wasn't the result I was expecting. I'm still pretty fresh at this.

};
Comment: Please, add the code you have developed so far.
Comment: Can you show what you've tried?  What output were you getting?
Comment: You don't need to use `reduce`/`filter` here, you can do this with a simple `for` loop (well, nested `for` loops).
Answer: Let's assume you want to find sums for the number 6. Check the first number of the array, let it be 2. You now want to know if there's a 4 in you array, so you check that. Do this process for all the numbers in the array and remove duplicates.
Maybe this could help ?
Comment: That's a clever solution, probably better than looping and trying to generate all possible sums.  I guess if your `num` was `6`, then you'd loop over each number... if the number is bigger than `6` then you skip it, if it's less than `6` then you subtract and search the array for the difference (there may be multiples)... then just keep looping until you have your combinations of sums.
Comment: Yeah, something like that could be a good solution.
Answer: Here is a little snippets along the lines of the previous suggestions:

const arr=[...Array(25)].map((_,v,)=>v), // create an array with 25 numbers
      findsum=(ar,sum)=>
        ar.reduce((a,c,i)=>
          (c>sum || ar.slice(i+1).forEach(v=>
             c+v-sum || a.push([c,v])),a)
        ,[] );

console.log(findsum(arr,27)) // find all possible pairs that add up to 27

Maybe it is helpful to you?
Only if the first condition c>sum is false the following ar.slice(i+1).forEach(...) will be executed. inside the forEach()-callback function the a.push([c,v]) will only be performed c+v-sum is "falsy" i. e. ==0.


Installing Tangible T4 Editor in VS 2010 RC

Question: I installed the (free) Tangible T4 Editor from the VS Gallery, and shut down/restarted VS. I run on XP under an Administrator account. VS Extension Manager indicates that the editor is installed and enabled.
Here is my problem: When I do Add New Item (as in the video here), I don't see any of the Tangible templates. What have I missed?
(BTW, I looked around some more, found the T4 Toolbox, installed that, and still see no new templates for Tangible or the toolbox).
Thanks!
Comment: Received this response from Tangible rep --

...everything is alright with your install. Indeed some of the guidance is refferíng to the VS2008 Version which comes with more templates and UML Tools.
In VS2010 we only provide the Editor as of now and VS itself comes with a Template Called "Text Template" in the normal add dialog.

We are adding more features to vS2010 version soon to achieve feature parity.

As of now the best thing you can do is to visit olegsych.com and learn from the articles there about T4 and also look at our How Do I Videos.
Answer: T4 Toolbox doesn't support 2010 RC just yet. Stay tuned.
Comment: Awesome news Oleg, thanks! I would upvote you but I don't have enough points yet :(
Answer: T4 Editor for 2010 assumes you use the default template "Text Template" that is installed with VS2010 itself. Another option is to use the T4 Toolbox from Oleg which now supports VS2010 RC. Additional templates will be available in the editors template gallery at RTM of VS2010.
Answer: The tangible T4 Editor is now available for VS2010 RTM
http://visualstudiogallery.msdn.microsoft.com/en-us/60297607-5fd4-4da4-97e1-3715e90c1a23


Adding full page figures in Latex, how?

Question: I have a full-page figure that LaTeX keeps putting at the end because of its size.
I would like it to be integrated on a separate page in the flow of text. How can I do it?
Answer: \begin{figure}[hbtp]

h = here
b = botom
t = top
p = page of floats

Algorithm will try the current position in document first, then bottom, then top and then on a seperate page. If you just specify 'h' you will force placement where the figure command is in the document. The order is encoded by you -- i.e., you could specify ptbh which would force a reverse order of evaluation.
p.s., I would strongly recomend anyone using latex to use lyx. Its just as powerfull as straight latex but its wysiwyg and you can drop to tex anywhere you want.
Comment: ok, I used here, but I changed to "p" and it makes the figure goes to another page, just as I wanted. Thanks!
Answer: If you also want the caption to be rotated, you can also use
\usepackage{rotating}

\begin{sidewaysfigure}

That also eliminates the need for using angle=90 or something like that
Answer: \begin{figure*}[tb]
\centering
 \makebox[\textwidth]{\includegraphics[width=.9\paperwidth]{./fig/fig5.eps}}
\caption{The SAP data model based on an UML class diagram: classes and relationships.}
\label{fig:Fig5}
\end{figure*}

Adding full page figures in Latex, how?


jqGrid doesn't show data

Question: I can't get to load data from a database with jqgrid. I used the demo code on the wiki (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:first_grid) and it works, but when I try to load info from my own database it simply doesn't work.
I used the demo code and changed it according to the table I want to use, to see if I coded something wrong the first time, and it didn't work.
index.html:

dades.php :
<?php
//include the information needed for the connection to MySQL data base server.
// we store here username, database and password

include("dbconfig.php");

// to the url parameter are added 4 parameters as described in colModel
// we should get these parameters to construct the needed query
// Since we specify in the options of the grid that we will use a GET method
// we should use the appropriate command to obtain the parameters.
// In our case this is $_GET. If we specify that we want to use post
// we should use $_POST. Maybe the better way is to use $_REQUEST, which
// contain both the GET and POST variables. For more information refer to php documentation.
// Get the requested page. By default grid sets this to 1.
$page = $_GET['page'];

// get how many rows we want to have into the grid - rowNum parameter in the grid
$limit = $_GET['rows'];

// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $_GET['sidx'];

// sorting order - at first time sortorder
$sord = $_GET['sord'];

// if we not pass at first time index use the first column for the index or what you want
if(!$sidx) $sidx =1;

// connect to the MySQL database server
$db = mysql_connect($dbhost, $dbuser, $dbpassword) or die("Connection Error: " . mysql_error());

// select the database
mysql_select_db($database) or die("Error connecting to db.");

// calculate the number of rows for the query. We need this for paging the result
$result = mysql_query("SELECT COUNT(*) AS count FROM llista");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];

// calculate the total pages for the query
if( $count > 0 && $limit > 0) {
              $total_pages = ceil($count/$limit);
} else {
              $total_pages = 0;
}

// if for some reasons the requested page is greater than the total
// set the requested page to total page
if ($page > $total_pages) $page=$total_pages;

// calculate the starting position of the rows
$start = $limit*$page - $limit;

// if for some reasons start position is negative set it to 0
// typical case is that the user type 0 for the requested page
if($start <0) $start = 0;

// the actual query for the grid data
$SQL = "SELECT id,nom,email,poblacio,naixement,tel FROM llista ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());

// we should set the appropriate header information. Do not forget this.
header("Content-type: text/xml;charset=utf-8");

$s = "<?xml version='1.0' encoding='utf-8'?>";
$s .=  "<rows>";
$s .= "<page>".$page."</page>";
$s .= "<total>".$total_pages."</total>";
$s .= "<records>".$count."</records>";

// be sure to put text data in CDATA
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $s .= "<row id='". $row['id']."'>";
    $s .= "<cell>". $row['id']."</cell>";
    $s .= "<cell>". $row['nom']."</cell>";
    $s .= "<cell>". $row['email']."</cell>";
    $s .= "<cell>". $row['poblacio']."</cell>";
    $s .= "<cell>". $row['naixement']."</cell>";
    $s .= "<cell>". $row['tel']."</cell>";
    $s .= "</row>";
}
$s .= "</rows>";

echo $s;
?>

Anybody here know why it dodn't work?
(EDIT)
For the tests I done, it seems that de problem is in the GET part:
$page = $_GET['page'];

// get how many rows we want to have into the grid - rowNum parameter in the grid
$limit = $_GET['rows'];

// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $_GET['sidx'];

// sorting order - at first time sortorder
$sord = $_GET['sord'];

// if we not pass at first time index use the first column for the index or what you want
if(!$sidx) $sidx =1;

it seems that it doesn't work, but i don't understand why.
(EDIT 2)
It seems that the GET part don't work so I ended up doing without it, and the big problem was in the wrong UTF in the database...so changing the database character set and the GETs it works flawlessly.
Comment: Could you include XML data which produce your server? You can use [Fiddler](http://www.fiddler2.com/fiddler2/) or [Firebug](http://getfirebug.com/) to catch data from the server HTTP response. Additionally it can be important to know the value of "Content-Type" in the HTTP header.
Comment: the header in dades.php is:
header("Content-type: text/xml;charset=utf-8");
Comment: Could you include XML data which produce your server?
Answer: for one thing, you haven't changed the result set count query.
 // calculate the number of rows for the query. We need this for paging the result
    $result = mysql_query("SELECT COUNT(*) AS count FROM invheader");

you still need to update this to
// calculate the number of rows for the query. We need this for paging the result
$result = mysql_query("SELECT COUNT(*) AS count FROM llista");

also, you shouldn't need content in the html table:

Comment: thanks, I edit this (allways stupid mistakes are the worse to spot...) but the problems are still here.

jqGrid doesn't show data


Harpy stalemate

Question: What happens when you have, say 5 village members with no killing or blocking or vote manipulation capabilities and 4 coven members where one is a harpy? Given the coven and village both play optimally, there will never be a winner? By silencing one village member, there will only be 4 valid coven votes and 4 valid village votes, but the number of people means that parity will never be achieved, if the village doesn't mislynch.
Answer: Your title is correct in that this will result in a perpetual stalemate situation and would require manual moderator intervention to come in and end the game.
Although this situation is an incredible edge case, your question had made me think that perhaps I should add a check to the game that if there hasn't been a death in X number of nights, the game ends in a draw.
Answer: I don't know if it is in the game you are speaking about, but while playing the boardgame Werewolves that this seem to be based on, there is usually a captain/mayor that is appointed at the beginning of the game, and that is transfered when the captain/mayor meets with his grim fate. (Usually the last action of a mayor is naming their successor)
That role usually breaks ties, because his vote counts to 1.5 instead of 1.
So if that role is in the game, there is no chance of tie because there is always the mayor to break them.

Harpy stalemate


What should be the partition scheme for Ubuntu 18.04 500 GB HDD (no SSD, no dual boot)?

Question: I have a 500 GB HDD.
When I was using Windows, I gave 150 GB to C drive (just to be on the safe side) and 315 GB to D drive.
I used C drive just for installing software. I stored my personal files and projects/programs I created in C and C++ in D drive.
Now I want to learn java and I'm thinking to use Ubuntu.
If I was using windows, I would install the Java related programs in C drive and will save the projects created in D drive.
How should I partition my HDD in Ubuntu?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/88537/discussion-on-question-by-shreekar-sharma-what-should-be-the-partition-scheme-fo).
Answer: The real answer to your question "What should be the partition scheme for ubuntu 18.04 lts 500gb hdd?" is: how you wish it to be. There is no rules. You should partition according on how you want to organize your data.
By default, the installer will establish one single partition containing system and user data. For a personal computer (not a server), this is the simplest solution. The drawback is that if you do a clean install in the future, then you also will need to place your data back. This is the simplest configuration, and there is nothing wrong with that.
Some people prefer to have a separate home partition. The root partition can then be as small as 15 GB or less. The second partition is then mounted on /home. Thus, all user configuration data and user data will be on the other partition. The convenience here is that your user data can remain in case you do a fresh reinstall in the future.
None of these scenarioś eliminates the need to having good backups of your personal data on removable drives or media.
Comment: Hello I am a developer thus intend to install lot of software in the future. So would 15Gb be sufficient for the root? And what is an ideal scheme, I am also using Windows alongside and have a total disk of 500gb.
Comment: IF you plan to install a lot of software, 20 or even 25 Gb may be safer. The ideal scheme is the scheme that works best for you.


Why I should not return a json list as result in web service?

Question: I did try to return a data list as result in my web application. For example
<code>@expose('json')
def getList():
    return ['apple', 'banana', 'orange']
</code>
But the web framework TurboGears2 stops me and says

01:50:22,687 ERROR [error] You may not expose with json a list return value.  This is because it leaves your application open to CSRF attacks

I don't understand, what's the problem of returning list as result? I can't find any article talking about returning JSON list and CSRF. Why is that?
Answer: Here is an article describing the issue.
http://haacked.com/archive/2009/06/25/json-hijacking.aspx


How do I connect a sub-panel to a generator transfer switch?

Question: Our house currently has a transfer switch to our main panel. Our barn has a subpanel that houses our electric fence and more importantly, well pump. As of right now, the transfer switch does not provide power to the barn. The barn has a two pole breaker in our main.
I attached pictures of our panel labels (rooms are correct but red outlining for generator is not--we had some work done recently and the electrician didn't move some of the transfer switch wires) and the actual wiring. The barn breakers used to be where the current surge protect is located. The previous owner did have it hooked into the transfer switch.
My question, is there a simple solution to hook up the barn to the transfer switch? We don't need or want the oven, dryer, or garage on the generator (currently hooked into the transfer switch). They just won't be needed during our power outages. Moreover, we don't need the heat pump as we will just use the furnace.
Additional info incorrectly posted as an "Answer":

There is a main switch on the bottom not pictured. It is an older panel in an old house. We have a 10 circuit transfer switch. However, we have some of the wiring going to breakers we don't need on the generator.

Ignore the blue and yellow dots in the wiring picture (they were for my reference).
Comment: So you have one of those 8-12 circuit transfer switches And only those circuits are transferred currently? I see quite a few wire nuts and that type of transfer switch makes sense from what I see. Your panel is really full and not having a main breaker you can might be able to add another double pole double  throw to that system , if there is a main at the bottom a mechanical interlock could be added but you would need to convert a 30 /40 to a quad  to free up 2 spaces , then the existing switch would not be needed.  My recommendation a panel upgrade with more spaces a mechanical interlock
Comment: There is a main switch on the bottom not pictured. It is an older panel in an old house. We have a 10 circuit transfer switch. However, we have some of the wiring going to breakers we don't need on the generator.
Comment: While @kdog321/everettk is getting his accounts squared away,  I've included the extra info in the original question as it's more likely to be seen there.
Answer: With the barn being a 100 amp feed your existing system is two undersized to be able to add the barn to your system.
Could it be done? Not by code!
using a mechanical interlock you could feed 240 to the barn but since it s a 100 amp feeder your generator would need to be able to feed that load (by code) if you load shed the barn down to just the pump and fence charger, most mid sized generators could push that with the house circuits but your existing transfer switch is not large enough to transfer a 100 amp load ( even if only 20 amps is needed on the barn circuit.
I would suggest a panel upgrade even if the same ampacity code now allows more breakers and you could add GFCI and arc fault protection IF you wanted (in some states required with a panel change)  so by installing a 40 breaker panel or larger you would have room to install a mechanical interlock, the 100 amp breaker could be turned off as the other large circuits are with a mechanical interlock, then you walk out to the barn, turn everything but the pump and fence charger off , go back to the house and turn the barn breaker on, as long as you don't overload the generator this will work and as a mechanical interlocked system will pass a code inspection, I know because I have wired them up. After the mechanical upgrade you could then sell the 10 circuit transfer switch on line, one customer got more than his interlock kit cost (~75$) .
The advantage to a mechanical interlock is you can change what circuits are energized through out the day/night turn 1 circuit off and another similarly loaded circuit on. you have all the circuits in your main panel to work with, not just the 10 on the separate switch assembly. Your current issue.
Answer: You can do it now, at a compromise.
One of the positions on your transfer switch should be for a 240V circuit. (This will need to be common trip).   That is the circuit you use.
Note that since the wiring in the transfer switch is only good for 20 or 30 amps, and the power to the subpanel goes through that wiring at all times, you must downgrade the 100A breaker to that lower number.  That will limit the power you can use at the barn.
I note that many people who install 100A subpanels just pick the number out of the air, and don't necessarily have load demands which require 100A.
Or, get a generator interlock as Ed Beal advises.
It really is the more versatile way to hook up a generator.  Salesmen do a great disservice when they convince you to add a transfer switch to the job, but it is a $550 sale they get commission on.  It is a perverse incentive.
However, while I am always happy to see people get plenty of panel spaces, the cost of a whole replacement panel isn't always on the table for people.
In that case, it may be worth talking to a competent Square D dealer, and searching the aftermarket, for a "generator interlock" that would fit your panel.  Since you say you have a main breaker off photo, the interlock will only require 2 breaker spaces typically.
You can free those up by consolidating two of your 240V breakers onto a quadplex.  Alternately you could fit a subpanel next to this panel, move two 240V circuits to the subpanel, freeing up the 4 spaces needed for interlock and subpanel feed breaker.
Note that dryer, range and subpanel have neutral, so they need "common trip" breakers.  That means typically they need to be on the inside breaker on a quadplex.


Testing if statements

Question: I've got a few lines uncovered but I can't seem to get coverage. Tried all sorts of testing with no luck.
It's my 3 if statements below.
No idea who to fix this.
<code>const user = getState('user');

if (user) {
    if (user.token) {
        axios.defaults.headers.common.Authorization = `Bearer ${user.token}`;
    }

    if (user.account) {
        axios.defaults.headers.common['X-Account-Id'] = user.account.id;
    }
}
</code>
Comment: by just adding an `account` property to `user`?
Comment: is `getUser` imported as a module?
Answer: So I have managed to resolve the issue after reading this post.
I basically had to add a separate unit test that was true and false for each of my if statements.

Testing if statements


How can I stop the "quick shot" feature in XCOM 2 Tactical Missions?

Question: So I just started playing XCOM 2 recently (I'm still on the Gatecrasher mission, no spoilers please!)  But I've noticed a really annoying "feature" where I click on the "fire" icon and my solider immediately fires on one of the visible enemies - without giving me the chance to select my target, if multiple targets are visible.
So far it hasn't screwed me, as my men have always ended up shooting the target I intended to shoot at anyway, but it scares me to think they might one day shoot the wrong guy.  (I did get screwed by a grenade throw though - my soldier ended up throwing the grenade off into the weeds without giving me a chance to position the blast radius over the enemies I actually wanted to hit.)
I haven't had much luck finding information on this "feature" or how to disable it online, although I did find this Reddit thread, which at least suggests it's a feature rather than a bug.  I gather that there's a keyboard shortcut (by pressing "1" twice) that will do this for the enemy with the best chance of being hit.  But this happens when I click (once) on the fire icon with the mouse (maybe it's registering two clicks really fast, by mistake?)
Does anybody have any information about this "quick shot" feature, or how to stop it from triggering?  I'm okay with solutions that disable the feature entirely as well as those that would stop it from happening on mouse-clicks alone.  I like taking my time to choose who I'll shoot at. =)
For the time being I'm training myself to use the number keys to select actions, as it's easier to ensure only one keypress that way.  This may very well end up being a solution in itself, but I'm accustomed to using the mouse from XCOM: EU/EW, and I'd like to continue doing it that way.
PS: I'm not a "modder" by any means, but I'm comfortable enough with computers and such that I'm also willing to hear ideas that involve editing .ini files and such, if anyone knows a way to accomplish this goal by playing with those settings.  Not my favourite solution, but acceptable for this purpose.
Comment: How old is your mouse? Could it be, that you're involuntary double clicking?
Comment: Not sure I've ever seen this, as it would somewhat remove the tactical elements of the game.  The only time I haven't been presented with a choice of target is when only 1 has been available.   It's worth noting that just because you can see a target, doesn't mean your soldier can see them.
Comment: There is no quick-shot feature.  I'd guess your mouse or keyboard is to blame.  Try switching them out and see if it still happens.
Comment: My mouse isn't brand new, it's true, but it's not known for sticking in other programs either.  I can hear it audibly click when I press the button and I only hear one click.  I'll try different one and see if that helps, though.  The keyboard isn't misbehaving for me, (just as well since it's a laptop) - it's just not my preferred input for this particular task.
Comment: @MattR I'm aware of what you're saying.  My soldiers have definitely had more than one visible target when this happens.  Also, remember the grenade I mentioned - it skipped right over letting me position the blast radius and just threw the grenade off screen as soon as I clicked the "frag grenade" icon!  Grenades always (are supposed to) let you position where you'll throw it, enemies or no enemies.
Comment: @Steve-O that sounds like your mouse may be accidentally double clicking (especially the grenades)
Answer: There is no such "feature".
Clicking the cross-hair icon always has the camera zoom-in close to your character and present you with a list of targets to switch between, along with some details on the odds in question.  Clicking the same cross-hair icon again will confirm and fire, as will clicking the large confirmation button or pressing the enter key.  You are likely accidentally double-clicking, possibly due to a bug that some users claim to have experienced.  There are some Steam discussions on the subject here, although no consensus on the solution has been found.  One individual suggested that this update to drivers specific to Razer mice might be a solution, assuming that only Razer mice exhibit the issue.
Comment: This is likely the truth, although it's annoying.  I don't have trouble with unexpected double-clicks in any other programs on my computer (not even XCOM EU or other Steam games.)  Unfortunately, there doesn't seem to be a way to fine-tune mouse sensitivity for clicks.  Thank you for your time. =)
Comment: @Steve-O Looks like this has happened to other people:  http://steamcommunity.com/app/268500/discussions/0/371918937288086701/
Answer: While I agree with the other answer that this is not game-related, I do want to mention that one of the first parts of a mouse that starts failing is the little plastic "spring" (it's not really a spring) that enables clicking the mouse button.
When that little plastic breaks or changes shape, the mouse can register double click. This has happened to the last 3 mice that I didn't lose or break some other way, and seems like a mouse's "dying of old age".
Is there anything you can do? Well, buying a new mouse is the obvious solution.
However, you could also set up AutoHotKey for this. If the mouse is firing click events twice, these will happen in incredibly quick succession. There is a way to set up AutoHotkey in a way that it will ignore any mouseclick that is preceded by another recent mouseclick (you can configure the time).
But I would suggest confirming whether the mouse is faulty by using it on another computer and seeing if the problem reproduces itself (e.g. click on youtube video. If doubleclick registers, it should maximize the window instead of pause the video).
If it is the mouse, I would suggest simply replacing it instead of clever trying to temporarily work around the issue.


Built-In Shelves/Bookcases - IKEA vs Built

Question: I come from a family that is not shy about woodworking, so I am not scared of building a carcass with dados for shelves, tacking on a face frame, then trimming it out; however, I would love to hear others' views on the advantages and disadvantages of these two popular methods.  Instead of the traditional build I just described, the many homeowners will take a pre-fab bookcase from IKEA ( IKEA Billy ) and trim them out to make them look custom.

Which method is considered more valuable to a home's value?
Which method is stronger?
Which method is easier to finish (paint or stain)?
Etc.

I plan on doing a series of these built-ins as my next DIY project, and the IKEA Billy method intrigues me.  It would so super fast, but I am wary of it.  The adjustable shelving with the pins makes me ponder them, but I am not sure how much they would really be used to adjust the height of the shelves.
Comment: I can't comment specifically on Ikea's shelves, but my experience with several other similarly priced brands is that if you actually use the wider models as bookshelves the sawdustboard shelves will slowly sag.  Despite the name on the box, they don't actually have enough strength to be filled with books although they're presumably fine with lighter knickknacks.
Comment: @DanNeely I have a 30-year-old Ikea bookcase with 900mm shelves that has had twenty volumes of a New Grove Dictionary of Music on its top two shelves for at least 20 years. The rest of the second shelf is taken up by ten volumes of the 1951 edition of Grove in a slipcase, and they've been there for all 30+ years. These are large heavy books. The sag in the middle is less than 1/8": barely visible. And note that Ikea only have narrower bookcases now.
Comment: It's worth noting that it's possible to modify IKEA furniture in certain ways quite easily.  I did so with my Father, when building wardrobes to facilitate non-perpendicular walls.  It means we have some shelves with no door on the end, but it fits the room perfectly, giving an even better finish.
Comment: Once I get the shelves put where I want, I never move them again. That adjustable bit is great for first setup, But you'll likely not be switching things around much. Dadoes are stronger, but also forever, so don't mess up.
Comment: Do I need to select and answer for an open ended discussion like this question?
Answer: I have experience with both.  I'll try to answer your bullets and then some other thoughts.
Which adds more to a home's value?  Well, typically bookcases don't add to the value because some people want them and some don't.  If you wanted to build them in, you're typically going to go custom with that and build it yourself.  The rigid dimensions for a pre-made bookcase will normally not allow it to look truly built in.  Also the particle-board-covered-with-paper finish is not going to look good in the long run and could actually detract from the home value because of the cheapness.
However...  I have used the more modular Bestä system to make a built in TV entertainment area that looked very custom and fit the area well.  The reason this worked better is that the "lower quality" IKEA frames were mostly hidden by doors that have better materials and finishes.  I wouldn't have ever built in a Billy.
Which method is stronger?  This is going to largely come down to your building skills and materials, but custom can be stronger.  However, Billy bookcases when properly assembled will be strong enough for their purpose.  Any weakness will only show when it's time to move the bookcase.  They don't hold up to twisting and racking forces as well because they are not glued and only use a few locking fasteners.  They are great for sitting in the corner and holding things tho!
Which is easier to paint or stain? Custom is going to take the lead here for sure.  IKEA uses a particle board covered with a paper-based finish.  This can't be sanded or easily repaired if scratched, nicked or drilled.  It's designed for you to leave it the color it was made, and they do come in a variety of colors.  I'd worry about adhesion issues and what happens to the paper finish when it gets wet (if using water-based paints) and it can't be stained because it's not wood.  There are a few solid wood items that IKEA makes, so none of this applies to them.  They are just wood and you can do whatever you want.
So, you say specifically you want a built-in project.  Unless this is a very low cost home I wouldn't consider Billy bookcases.  They can't be easily painted and can't be easily repaired (like if a shelf peg breaks out).  They just are not intended to be that type of furniture.
As far as stand-alone shelves go - they are great and I've found that you typically can't build your own for less money.  What you pay for lumber and hardware/fasteners might be a little less expensive, but not by much.  You'll end up with a nicer custom product in the end, but not cheaper.
Comment: "They are not glued" - they are when I make them ;)
Comment: One note: In my experience with it, IKEA's engineered wood furniture is covered with actual wood veneer, not a wood-print paper veneer.  There may be exceptions, but the Billy is not one of them.
Comment: @Baldrickk Indeed. In fact, I've noticed more of these kits coming with some sort of wood glue included for the dowels. Someone noticed a little glue solves a lot of problems...
Comment: @TheoBrinkman My experience is with the white ones.  Interesting that Billy has wood veneer at their low price point.  That would paint much better.
Comment: @Machavity IKEA kits still come without glue - at least my Sister's coffee tables and my new Wardrobes still came without any.  A quick trip to the local DIY store solves a lot of problems :)  I've found that the ones that do come with glue tend to be less well built in general... maybe because the glue helps them get away with it?
Comment: @JPhi1618, fair point, I haven't gone with the black or white versions of any of their Billy shelving, so I hadn't considered the differences there.  But, yes, I was pleasantly surprised to find actual wood veneer, even if the way I found it meant taking one shelf of a recently purchased Billy back to get it replaced because the veneer had cracked and was peeling away from the engineered wood underneath.
Answer: The Ikea Billy adds no value to the home since it's obvious to anyone that it's just Ikea furniture.  Built-in shelves add some value if well-executed.
Which is stronger is entirely up to you.
Ikea is well-engineered particle board and cardboard honeycomb (which is strong), but the backs are simple pressboard and are the weak point of Ikea furniture. The backs are vital to keep the furniture from tramming. Consider replacing the backs with 1/4" or 3/8" plywood and fasten it very securely with screws into pre-drilled holes.
Which is easier to finish? Ikea Billy, as it comes finished.
Billy is 1000 times easier.  Measure, buy, knock together. Any self-respecting woodworker who can follow directions will be able to assemble an Ikea kit while watching TV.  You know perfectly well what it takes to design, build and finish shelving from scratch.
Comment: Both great answers just want to add that Ikea is very underrated the hardware that it comes with is superior to many custom jobs that I've seen. Unfortunately for resale Ikea is perceived as cheap.
Comment: What is tramming? I assume from context it means going out of square, but, the only similar reference I can find on the internet is to tramming a milling machine, which seems to be process of making it square.
Answer: If you want strong bookshelves, you need to consider sagging.
I can highly recommend playing with the sagulator (http://www.woodbin.com/calcs/sagulator/) which helps calculate expected sag.
I have an alcove approximately 90cm wide, and I originally used an 80cm billy bookcase which fitted near perfectly. The shelves sagged, and it looked tired after just a couple of years. However, I liked the adjustable shelf option.
I replaced it using bookcase shelving strips (eg https://www.toolstation.com/bookcase-shelving/p87119) screwed directly to the side and back walls, and solid pine shelves. This wasn't significantly more expensive or time-consuming than the billy bookcase, but looks much better.
The key difference is that I've got supports on both sides (1 each), and supports at the back (2, equally spaced). It's still only 4 points of contact, but by distributing the weight on the shelves across the back I've eliminated any sagging, even though it's loaded with heavy recipe books.
Comment: That calculator is fantastic.


Apache CXF (2.6.1): Client gets "Content is not allowed in prolog"

Question: I'm using Apache CXF (2.6.1) in my java application to consume 3rd party Web Service. But I have a problem with it, in particular if I use JAXB for databinding while stubs generation my client will always send requests with "header" like "--uuid:e47f145b-38f7-4402-8eec-657d71bc8ad4..." (see client request below), i.e. besides XML part there is some special info...
It looks like this special info causes error reply from server "Content is not allowed in prolog" (see server response below), i.e. server is not expecting such body. What is interesting here is that if I generate stubs using XMLBEANS for databinding everything starts to work just fine (and there is no such "special" info in request body, only XML). After some googling I suspect that my client for some reason tries to use MTOM (with JAXB) and I don't know how to turn it off. I've already tried the following to turn MTOM off (with no luck):
((BindingProvider)port).getRequestContext().put("mtom-enabled", Boolean.FALSE);
((BindingProvider)port).getRequestContext().put("write.attachments", Boolean.FALSE);
((BindingProvider)port).setMTOMEnabled(false);

Please help I would really want to move to JAXB since it's much more compact in comparison with XMLBEANS...
Client code:
AdminServiceV2 ws = new AdminServiceV2();
AdminV2 port = ws.getAdminPortV2();

Client client = ClientProxy.getClient(port);
HTTPConduit http = (HTTPConduit) client.getConduit();

AuthorizationPolicy authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setUserName("user1");
authorizationPolicy.setPassword("password1");
authorizationPolicy.setAuthorizationType("Basic");
http.setAuthorization(authorizationPolicy);

try {
    port.getUsersInfo("user1");
} catch (Exception e) {
    e.printStackTrace();
}

Client request:
--uuid:e47f145b-38f7-4402-8eec-657d71bc8ad4
Content-Type: text/xml; charset=UTF-8; type="text/xml";
Content-Transfer-Encoding: binary
Content-ID: <firstname.lastname@example.com>

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getUsersInfo xmlns:ns2="http://service.admin.ws.five9.com/v2/"><userNamePattern>user1</userNamePattern></ns2:getUsersInfo></soap:Body></soap:Envelope>
--uuid:e47f145b-38f7-4402-8eec-657d71bc8ad4--

Server response:
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'><env:Header></env:Header><env:Body><env:Fault xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'><faultcode>env:Client</faultcode><faultstring>org.xml.sax.SAXParseException: Content is not allowed in prolog.</faultstring></env:Fault></env:Body></env:Envelope>

Thanks,
Konstantin
Answer: No CXF request ever starts normally with --uuid. That is part-way through a multi-part HTTP message. With or without MTOM, a normal SOAP message consists of an HTTP header followed by the XML content. If it's MTOM, the HTTP header declared multipart, and then there are multipart separators and sub-headers.
If you are using a custom front-end to ask for 'plain XML' messages without the usual required HTTP headers, then that, combined with MTOM, might have the undesirable effect at hand.
JAXB will generally only enable MTOM if you have @XmlMimeType("application/octet-stream") annotations(s). You should also look at the WSDL/XSD for the service and see if it has xmime annotations in there.
See the CXF MTOM doc for more details.
You haven't specified the CXF version or how you configured your CXF client endpoint. You might get better assistance by sending all that data to the CXF user mailing list.
Comment: Hi, thanks for your fast reply, I've updated post with info you've mentioned (cxf version, client code).
Comment: Are you really sure that this is all the data on the wire, and no headers about the --? Have you turned on CXF logging interceptors on the client side?
Comment: Yes, that's all code I have. I've checked for the annotations in my wsdl - nothing found. Logging interceptors doesn't show much new (I can't understand why it's multipart): Outbound Message
---------------------------
ID: 1
Address: https://api.someserver.com/wsadmin/v2/AdminWebService
Encoding: UTF-8
Content-Type: multipart/related; type="text/xml"; boundary="uuid:c0848dcb-39a2-4d0e-ba71-c28fa123895f"; start=""; start-info="text/xml"
Headers: {Accept=[*/*], Authorization=[Basic a2JhYnVzaGtpbjpyb290MTIz], SOAPAction=[""]}
--------------------------------------
Comment: I guess that's something in wsdl that making it multipart:
Comment: Many thanks for your efforts, sorry I leave this question as answered by Dan Kulp (see below).
Answer: The question was answered on CXF user mailing list by Daniel Kulp, for details see
http://cxf.547215.n5.nabble.com/Apache-CXF-2-6-1-Client-gets-Content-is-not-allowed-in-prolog-td5713009.html#a5713055. In short the problem was with WSDL (it contains swaRefs) that forces CXF to send messages like with attachments. Workaround was also provided...


Redirect users to web address based on database data

Question: I'm using in my add-vehicle.php the following code to redirect my users after submitting a form and it works..(this is not the whole code)
if(isset($_GET['success'])  && empty($_GET['success'])) ....(is true)

header('Location: www.mysite.com/add-vehicle?succses');

But I want to redirect my users to a unique webadres. For example:
www.mysite.com/add-vehicle?succses/car_id=1 and the next one to www.mysite.com/add-vehicle?succses/car_id=2'
so I want to output the data of my Database in my url..
What is the best way to do it?
Comment: Query the database for the information, and append it to the location string.
Comment: fetch the data from the database, bind it to a variable and put it into your url string.
Answer: You can just use your PHP variable to adjust the URL.
header('Location: http://' . $_DBPage);


Would it give me more armor if i would use Lightweight Alloys with Hull Reinforcement Package,

Question: I am currently flying Imperial courier and I am very happy with it. I was checking the outfitting setups on the edshipyard.com and I start to wonder, would it give me the better armor if I buy two hull reinforcment modules, 190 armor each, and use Lightweight Alloys instead of Military Grade Composite?
Currently I am using Military Grade Composite bulkheads with no hull reinforcement modules, and it looks like it gives me 280 armor and it waight 8t. While with Lightweight Alloys I would have 144 base armor (no additional weight), and I could buy two hull reinforcement modules (4t each). This set up would give me 524 armor and it would weigh the same as Military Grade Composite bulkheads.
So my question is, "does it really work this way?" Does the hull reinforcement module give the same armor as bulkheads or is it calculated differently?
Comment: Your question may require a more refined answer, but [this question](http://gaming.stackexchange.com/q/239527/108888) will tell you more about how armor works
Answer:
So my question is, "does it really work this way?"

Yes. The bulkheads raise your ship's hull points by a percentage of its base health, while the hull reinforcement package raises it by a flat absolute value, which in this case is higher for the same mass. The trade-off cost is in the highly limited internal module slots.
Specifically, for Military grade composites, the increase is +250% (though for the free lightweight alloys it is already +80%). The Imperial Courier's base armor health is 80, which is raised to 144 (+80%) by the stock lightweight alloy bulkheads. Upgrading these to military grade composites raises it to 280 (by changing the +80% to +250% instead).
The 3D hull reinforcement (as of this writing) gives +260 health for 4t, while the 2E gives +150 health for 4t. These are the only four-ton packages fittable on the Courier, so in different combinations I'm getting 444, 554 or 664 hull points for your second build (maybe things were rebalanced over the years since you got 524).
Still, though, if you are going to hull-tank you might as well go for both the bulkheads and the reinforcement. The 8t increase has only a small impact on sublight speed and jump range.
Comment: You may want to mention the increases to damage resistances that Hull Reinforcement Packages also provide.
Comment: That's true; I wasn't taking engineering into account. Engineered HRP modules can increase resistance, which makes ALL of the ship's armor (not just the module's own) effectively stronger against specific damage types.
Comment: Even non-engineered HRP modules provide a small amount of damage resistance (0.5-2.5%, depending on class).


do all printers have same dmpaper_A4 value?

Question: I am working on printer set up function.
Microsoft has DeviceCapabilities API, let you retrieve printers setting information.
The function uses dmPaperSize for paper size, DMPAPER_A4 is one of the members in dmPaperSize. A4 paper is defined as DMPAPER_A4 that has value 9 in my printer.  My question is whether DMPAPER_A4 is always 9 for all the printers?
Also for dmDefaultSource, do all the member of dmDefaultSource has same value across every printers (if it can be installed in windows)?
Thanks.
Answer: Yes, DMPAPER_A4 is defined in the Windows SDK header files as 9. That means A4 paper size will be identified with the value 9 on all printers. So if you need to check for that value on a platform where you can't use the Windows header files, you can safely assume 9 is A4 paper size.
Theoretically, Microsoft could change that value because they only guarantee the constant DMPAPER_A4 will represent A4 paper and not that it will always have the value 9. But in practice there's no way Microsoft would ever do that. They would break hundreds of applications with such a move so you should be safe coding the value 9 if you have no way of using the official constant names.
As for dmDefaultSource, all the members of the Win32 printing subsystem that have documented names or values are the same for all printers. A printer that didn't adhere to the Windows standards wouldn't work on Windows.
Comment: @Gábor I understand that. It's basic C++. I kind of figured anyone writing code for the Win32 API most likely understands it.
Comment: I just found my printer HP Officejet Pro 8500 A910 has bin number 15, 259, 258, 257 and bin name are Automatically Select, Printer Auto Select, Tray 1, Tray 2.
Comment: and My pdf995 has bin number 15, 157, names are Automatically Select, onlyone. OnlyOne should be number 1. and 15 should be DMBIN_FORMSOURCE. It seems printers does not conform to ms standard.
Comment: @peter It would be no surprise that a virtual printer like pdf995 doesn't conform, but an HP printer should. I'm not sure what you're saying you think doesn't conform about the HP.
Comment: Thank you for your help. I think the bin name for the bin number 15 should be DMBIN_FORMSOURCE or FORMSOURCE. Automatically Select should be DMBIN_AUTO = 7. I am not sure if I am correct.
Comment: You need to pose a new question. I answered the one you asked as best I can but what you're asking now isn't clear at all.
Comment: "Theoretically, Microsoft could change that value because they only guarantee the constant DMPAPER_A4 will represent A4 paper and not that it will always have the value 9." -- Well, no. There is no constant DMPAPER_A4 in any executable, just the number. The constant is only for the programmer's convenience, nothing beyond that. So they can't change it under any circumstances without risking blowing up everything. Besides, there always is a way to use the constant names, it's just that: `const int DMPAPER_A4 = 9;`
Comment: @Gábor Um, sure they can. Microsoft can change the actual value behind any constant any time they want. Yes, that will break existing programs unless the product owners obtain the new header files and recompile, but they _can_ do it and _have_ done it. I do agree it's very unlikely they would do it, however.
Comment: @Carey Gregory Ok, ok, it wasn't a question of whether they have the power to do. :-) What I meant was that there were no two separate entities, a constant and a value, so that you can change one without affecting the other. There is only one entitiy, the value. The constant doesn't exist in the running program.
Comment: @Gábor, the reason the answer says Microsoft would break hundreds of applications if they changed the value, is because the author of this answer already knew how macros worked.  Not sure what your comment adds to the discussion.
Comment: I really didn't want to drag it out that much. :-) It was meant as a very mild remark on a sentence that isn't really correct: "Theoretically, Microsoft could change that value because they only guarantee the constant DMPAPER_A4 will represent A4 paper and not that it will always have the value 9." There is no distinction between name and value, they are the same for all intents and purposes. They practically guarantee either both or none.

But let's drop it, it's not worth that much. :-)


If $P$ be the orthogonal projection of Hilbert space $X$, then $\langle Px,x \rangle = \|Px\|^2, \forall x \in X $

Question: Let $P$ be the orthonormal projection of a Hilbert space $X$ onto a closed subpace $Y$. Also, assume that $Y$ is the linear span of the orthonormal set $[y_1, \cdots, y_n].$ Then I need to show that $\langle Px,x \rangle = \|Px\|^2, \forall x \in X.$
I began by the very definition: $$Px = \sum_{i=1}^n \langle x,y_i \rangle y_i$$ Thus, $$\langle Px,x \rangle = \Big \langle \sum_{i=1}^n \langle x,y_i \rangle y_i,x \Big \rangle = \sum_{i=1}^n \langle x,y_i \rangle \langle y_i,x \rangle. \quad (I)$$
On the other hand, $$ \|Px\|^2 = \langle Px,Px \rangle = \Big \langle \sum_{i=1}^n \langle x,y_i \rangle y_i , \sum_{j=1}^n \langle x,y_j \rangle y_j  \Big \rangle = \sum_{i=1}^n \sum_{j=1}^n \langle x,y_i \rangle \langle x,y_j \rangle \delta_{ij} = \sum_{i=1}^n \langle x,y_i \rangle \langle x,y_i \rangle. \quad (II) $$
Now, I need to show that (I) and (II) are the same. But are they in general? Knowing that generally, $\langle x,y\rangle = \overline{\langle y,x\rangle}$ and not necessarily $\langle x,y\rangle = {\langle y,x\rangle}.$ Am I right so far? If so, how to continue from this point onward?
Answer: No, they're not the same. You have an error in version II. Since $\langle\cdot,\cdot\rangle$ is conjugate-linear in the second variable, you should have $\overline{\langle x,y_j\rangle}$, and then the two expressions do in fact become equal.
Note that it should have been suspicious that your formula for $\|Px\|^2$ did not necessarily give a real answer.
Comment: I'd really rather write it as $\sum\langle x,y_i\rangle\overline{\langle x,y_i\rangle} = \sum |\langle x,y_i\rangle|^2$.
Comment: Thanks. So it should have been: $\Big \langle \sum_{i=1}^n \langle x,y_i \rangle y_i , \sum_{j=1}^n \langle x,y_j \rangle y_j  \Big \rangle = \sum_{i=1}^n \sum_{j=1}^n \langle x,y_i \rangle \overline{\langle x,y_j} \rangle \delta_{ij} = \sum_{i=1}^n \langle x,y_i \rangle \langle y_i,x \rangle. $
Answer: If $P$ is a projection than $P=P^2$ and if $P$ is an orthogonal projection then $P^*=P$. Hence
$\langle Px , x \rangle = \langle P^2x , x \rangle = \langle P^*Px , x \rangle = \langle Px , Px \rangle $.
Comment: Thanks. I've seen this one. But I wanted to begin with the definition and work it up from there. Have I made a mistake in my reasoning?
Comment: I think Ted has an answer to your question.


OnListItemClick only working once

Question: I am working on a listview that when you click an item, it shows an alertdialog with 2 options, and after they pick an option it takes them back to the listview where they can do it again with another selection. For some reason once I click an item, if I click the positive button (the one with code in it) then try and click on another item the alert dialog doesn't pop up. Does anyone know why this would happen? The code is below:
protected void onListItemClick(ListView l, View v, int position, long id) {
        final int i = position;
        try {
            new AlertDialog.Builder(this)
            .setTitle("Download")
            .setMessage("You have selected the level " + jArray.getJSONObject(i).getString("level_name") + ". Would you like to save it?")
            .setPositiveButton("Save", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        saveLevel(jArray.getJSONObject(i).getString("level_name"),jArray.getJSONObject(i).getInt("id"));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return;
                }
            })
            .setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            })
            .show();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        super.onListItemClick(l, v, position, id);
    }

If you need anything other info let me know! Thanks in advance!
William
Edit
From what I can tell, it is happening in the saveLevel function, I am posting it below
public void saveLevel(String i, int id)
{
    InputStream is = null;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("uid","demo"));
    String result = "";
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("www.example.com/stuff.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
        jArray = new JSONArray(result);
        File exst = Environment.getExternalStorageDirectory();
        String exstPath = exst.getPath();

        File filePath = new File(exstPath+"/Platformer/Downloaded");
        boolean success = filePath.mkdir();
        String path = filePath.getAbsolutePath() + "/" + i + ".xml";
        File newxmlfile = new File(path);
        try
        {
            newxmlfile.createNewFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();

        }
        FileOutputStream fileos = null;
        try
        {
            fileos = new FileOutputStream(newxmlfile);
        }
        catch(FileNotFoundException e)
        {
            Log.e("FileNotFoundException", "can't create FileOutputStream");
            return;
        }
        OutputStreamWriter output = new OutputStreamWriter(fileos);
        output.write(jArray.getJSONObject(0).getString("level_data"));
        output.flush();
        output.close();
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error parsing data "+e.toString());
    }
}

Comment: cloud you check the logcat  to see if it fire any exceptions or not ?
Answer: Your saveLevel() function does a lot of things (network access, file access), that are not suited well for UI thread. You should separate these things into a background thread, preferably using AsyncTask (tutorial).
Most probably your program is still stuck in saveLevel() when you're trying to click another list item. If you want to check if this assumption is really true, just put a return; line in the beginning of saveLevel() and see if your dialog box pops up as intended.
Comment: Thanks, I will try that now, taking out saveLevel let the button pop up again, but I know the function is done because they level shows up in another list, I am working on async though because I feel like that would be better anyways
Comment: It turns out I was actually clearing the JSONArray in the saveLevel function by accident. I am going to try and get it set up with async though, thanks for that!
Comment: You're welcome, and please, don't put any file/network access routines in your UI thread, offload them to `AsyncTask` or `AsyncLoader` (in the newer version of SDK)

OnListItemClick only working once


Java subclass does not recognise its generic superclass

Question: I need help with a problem I have with generics in Java. I'm writing this Computer algebra system, where the user enters a math expression and the system works with it in different ways (expand it, simplify it etc). It worked fine for expressions containing natural numbers, and I wanted to expand it to work with mathematical sets as well. Instead of +, you would have the intersection operator, etc.
At first, I started recording everything for the sets, but then I realized this was probably not good and started using generics.
Instead of having one parse tree like MathExpr and one like SetExpr, I thought I could just have a generic Expression<T> and build a base class Number and a base class Set.
To try to clarify, I want a mathematical expression like (2 * a) + (3 + 2) to be an instance of a class Expression<Number> and a set expression like (A ∪ B) ∩ C to be an instance of Expression<Set>. I can then perform different operations on this, like calculate the depth etc.
The + operation is implemented as one class, the * as one class etc. Both these classes are subclasses of an abstract class called TwoExpr which in turn is a subclass of the abstract class Expr. This is how I have done it now and everything works fine.
When I wanted to change my code I made my Expr class generic. That is Expr<T>. I also changed TwoExpr to TwoExpr<T> and created a base class Number.
The problem is, now I can't seem to instantiate objects of the type Sum<Number>.
I get a "Type mismatch: cannot convert from Sum to Expr<Number>" error. But Sum is a subclass of TwoExpr<Number>, which in turn is a subclass of Expr<Number>. As you may realize, I can't make the class Sum generic and call it Sum<Number>, because all arithmetic operations don't have analogues for sets.
I have always been able to create objects like
Expr zero= new Leaf(0);
Variable a = new Variable("a");
Expr aPlusZero = new Sum(a, zero);

When I changed to generics, the same code looks like this:
Expr<Number> zero= new Leaf<Number>(new Number(0)); //works fine
Variable<Number> a = new Variable<Number>("a");     //works fine
Expr<Number> APlusZero=new Sum(a,zero); //gives a "Type mismatch:
//cannot convert from Sum to Expr<Number>" error

How come it doesn't recognize that Sum(a,zero) is a subclass of Expr<Number>, when it says in the declaration of Sum
public class Sum extends TwoExpr<Number> {

    public Sum(Expr<Number> a, Expr<Number> b) {
        super(a, b);
    }
...
}

and in the declaration of TwoExpr
public abstract class TwoExpr<T> extends Expr<T> {

    protected Expr<T> a;
    protected Expr<T> b;

    public TwoExpr(Expr<T> a, Expr<T> b) {
        this.a=a;
        this.b=b;
    }
    ...
}

I know that Lizkows substitution principle doesn't apply for generic arguments. But Number isn't a subclass of anything (except Object) and don't have any subclasses.
I hope I've been fairly clear about what I'm trying to do and what problem I have. Does anybody have any idea how to solve it? Please tell me if anything was unclear in the above or if you want more code.
Thanks in advance.
Mattias
Comment: Could it be that the compiler mixes your Number type with `java.lang.Number`?
Comment: Your code given here looks fine, I dare to say that the problem is not in the part you've shown here.
Comment: Agreed, a missing "import ...Number" may be the culprit.
Comment: Well, he's definitely not using java.lang.Number if new Number(0) works. lang.Number is abstract. That wouldn't work with it.
Comment: No, Number is not java.lang.number and Set is not Collections.Set. Those Are both classes I have created. Number is just a wrapper for int and Set is just a wrapper for String.
Answer: I think your problem is in the classes you did not show, I tried the following and it works:
Expr<Number> zero= new Expr<Number>();
Expr<Number> a= new Expr<Number>();
Expr<Number> APlusZero=new Sum(a,zero);

Might it be that Variable is not an Expr?
UPDATE:
I played a little creating Variable and Leaf as I imagine them and it all works:
public class Number {

    public Number(int i){}
}

public class Variable<T> extends Expr<T> {

    public Variable(String s){}
}

public class Leaf<T> extends Expr<T> {

    public Leaf(T t) {
        super();
    }
}

public class Expr<T> {

}

public class TwoExpr<T> extends Expr<T> {

    public TwoExpr(Expr<T> a, Expr<T> b) {
    }
}

public class Sum extends TwoExpr<Number> {

    public Sum(Expr<Number> a, Expr<Number> b) {
        super(a, b);
    }
}

public class AllTogether {

    public static void main(String[] args) {

        Expr<Number> zero= new Leaf<Number>(new Number(0));
        Variable<Number> a = new Variable<Number>("a");
        Expr<Number> APlusZero=new Sum(a,zero);
    }
}

If you take the extends Expr from Variable it does give the error you experience, might it be this the cause?
Comment: the declaration of Variable is public class Variable extends Atomic and the declaration of Atomic is public abstract class Atomic extends Expr so that shouldnt be it, those sort of things worked out perfectly before I added generics so that shouldnt be it
Comment: I wanted to create a similar example to show that there is no error here, but didn't had the time yet - thanks!
Comment: @Mattias, does the example given here compile for you? If not, which compiler are you using? (Maybe we are chasing a compiler bug here.)
Comment: Yes, it did compile. However, there are a couple of differences in your code and mine, for example, Expr and TwoExpr are abstract. When I introduced generics, I also moved the different classes to different packages, could that be it, that it doesn't recognize the classes anymore because they are not in the same package? I use eclipse helios.
Comment: I would advice you to update your question and put all the involved classes (declaration and constructors is enough) so we can try it. Otherwise we are inventing things that actually work but differ from your code
Comment: Yes, I will do that. I didn't want to post all classes because I thought it was confusing but I think youre right. I will post all relevant classes and packages.
Answer: Sum does not import Types.Number. So it's not Expr<Types.Number> but Expr<java.lang.Number>. I would assume this would give a compilation error not only on the assignment but also on the construction of new Sum(vA, zero), but maybe the compiler sees the other error first.
Comment: Well, what do you know... I didn't see that. It should of course be Types.Number. But Variable doesn't import Number either and it works for that one.
Comment: I thought that because Sum was in the package Types.Number.Two it would automatically import all classes in Number, but I have a feeling Im getting packages in java wrong.
Comment: Packages are arranged into trees merely as a convenience. Package "com.example.foo" is not related to "com.example" in any semantic meaningful way.
Answer: Maybe try to debug it:
Object = new Sum(a,zero);
System.out.println(o.getClass().getGenericSuperclass());

Furthermore maybe  is a better solution for your system.
Comment: But I cant even run the program. The Line `Object=new Sum(a,zero);` gives the error message "The constructor Sum(Variable, Expr) is undefined". But the constructor of Sum is `public Sum(Expr a, Expr b) {`
  `super(a, b);`
 `}`
Comment: If Variable extends Expr, shouldnt Variable extend Expr?