How can I temporarily attach anti-bird spikes to a window air conditioner?

Question: I'm trying to stick on anti-pigeon spikes on top of my window air conditioner and want a non-permanent solution that I can take off when I put it into storage.
Is there something I can use that's weather-proof but also removable at the end of the season?
Comment: Hook and loop systems (often called by the brand name *Velcro*?
Comment: Yo magnets, yeah!
Comment: superglue super magnets to the bird strips; super easy.
Comment: Silicon Caulk works great
Comment: I'd be a bit concerned about magnets wearing through the paint due to vibration. Maybe use some vinyl sheeting between.
Comment: @isherwood: good point, but sheeting can trap dust and debris over time, turning it to sandpaper. only thing I can think of that won't do that are hotglue or rubber-cement "landing pads", which tend to seal well around the edges.
Comment: hotglue might be a good choice if the outside is not baking in the sun: you can remove it with a hair drier.
Comment: Did you ever get this resolved? If so, please give a check-mark to the answer that helped you the most, or write up your own answer explaining what you did to get it fixed and give yourself a check mark. That will help others with this kind of problem know that this has a resolution and is a good place to look for their answer.
Answer: I think I'd bond the spikes permanently to something heavy as a base, like nylon blocks, using screws or whatever. I'd then apply rubber feet to the blocks and simply set them on the air conditioner.
No need to rely on tenuous adhesive connections and no need to replace the fastener each season.
Answer: If you don't object to a product with an analogue in hook and loop tape, but more durable and substantially stronger, consider to locate 3M Dual Lock tape. It's available in various widths and lengths as well as different adhesive types. The strongest stuff has a gel type of adhesive, not quite foam, but squishy in a fashion.
The pieces are not "gendered" as with hook and loop. The tape has tiny stalks with mushroom heads that engage the other mushroom heads (get your mind out of the 60s here!) to form a very strong bond. The adhesive is weather resistant but I'm not so sure about sun resistance.
You'd attach one piece to the spike and one piece to the cleaned surface of the air conditioner.
The magnet idea is a good one, as you'd need only one magnet if your air conditioner has a steel casing.


Why is the Pokedex glitching

Question: Whenever I want to view a Pokemon within my Pokedex and click on it the Pokedex rotates back to Charmander, which was my starter. Does anyone else have that glitch or knows a solution? Everything else seems to work properly
Update: this is how it looks like when I swipe

Update:
I have a Sony XperiaZ5 compact Android version 6.0.1
I tried restaring the app and the phone multible times. I also reinstalled the app, which also didn't fix the Pokedex.
Comment: Looks familiar. My Pokédex does the same.
Comment: Can you swipe the  screen to change the Pokemon that you're looking at?
Comment: Yes I can but the entrys are not centered and the Pokemon pictures are even more off
Comment: Could you show a picture of this? (Screen shot your device)
Comment: I added it to my question
Comment: What kind of device are you playing on? I've noticed this is a very common issue on android devices whereas it works fine on iOS devices
Comment: Sony XperiaZ5 compact Android version 6.0.1
Answer: I had this issue and it was due to my touchscreen not registering that I had removed my finger.
A restart of the phone resolved the issue.
It might also be worth clearing your cache or re-installing the app. You won't lose anything doing this, because all of your data is stored on your account, not your phone.
Comment: I turn my phone off over night so I already restarted my phone 5 times and it did not fix it. I now cleared my cache which also didn't help. I will try reinstalling the app as soon as I'm at home.
Comment: Didn't have any luck on my Samsung Galaxy S7.
Comment: I reinstalled the app but sadly this did not fix the pokedex glitch
Answer: Niantic released v 0.31.0 for android on 7/30/2016
Beforehand the Pokedex glitched and scrolled, just as your described. After I installed the updated, I was able to load the Pokedex and view the Pokemon with no issues at all.
Comment: The new version fix it for me too.

Why is the Pokedex glitching


How to Build Output JSON Using Jolt Transform in NiFi

Question: I'm facing an issue while trying to construct an output JSON from a joltTransform processor in Apache NiFi. I need to extract values from the idByLine array and match them with values in the orderLine array. Here's a simplified version of my input JSON:
<code>{
  "orderLine": [
    {
      "ID": "1"
    },
    {
      "ID": "2"
    }
  ],
  "idByLine": [
    {
      "idLine": "1",
      "orderId": "AMD123"
    },
    {
      "idLine": "2",
      "orderId": "AMD555"
    }
  ]
}
</code>
My goal is to create the following output object:
<code>[
  {
    "idLine": "AMD123"
  },
  {
    "idLine": "AMD555"
  }
]
</code>
I'm struggling to devise the correct JOLT specification to achieve this. Could someone please assist me in crafting the appropriate JOLT spec for generating the desired output?
Answer: You can try the following spec:
<code>[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "ID": {
            "@": "@(0).&1"
          },
          "idLine": {
            "@(1,orderId)": "@(0).&1"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "ID": {
          "@(1,idLine)": "[].idLine"
        }
      }
    }
  }
]
</code>


Reverse double in c# without using string or array

Question: I know such questions have been asked before, but all of them use strings.
Most common answers to such questions are :

convert to string and take number.Length - 1. However I don't want to use strings.
Divide by 10, but this only works for whole numbers. If I have 1.12 and I divide it by 10 I dont get 2.
Turn the number into array and then reverse it. Which is the same as using a string but more work and its not what I am looking for.

So my question is if I have input like 1.12 I want 21.1 but without using any strings. I want to take the 2 and save it as a number and then take the rest and add the dot.
I want a mathematical solution to the problem.
I will provide you with some test cases so you better understand my problem.
23.45 => 54.32
0.50 => 05.0 => 5
4.3445242 => 2425443.4
232 => 232
123 => 321

And I dont want strings or arrays because when you say "I dont want strings" there is always someone who says " turn the number into array and then reverse it". Nah... I want to use only calculations, if-else and cycles (for,while,do while)
Comment: Start by thinking about this: You do not really show doubles but decimals in your post. Then continue to think about digts!  - Eventually you will  come up with a solution and/or accept that using strings is a vastly superior approach.
Comment: Maybe a math forum would be a better place for this. It's more of a math question than a programming question.
Comment: *"I want a mathematical solution"* then ask your question on [math.stackexchange](https://math.stackexchange.com/).
Comment: May I ask why you don't want to use strings? I don't understand why you have the most common answer but don't want to use it. It's probably a common answer for a reason: It works.
Answer: A relatively ugly way would be essentially promote that double into long and remember the decimal point. Then reverse the long, then divide it by total number of digits minus originl decimal point. Also, if you want to handle negative numbers, you would have to store the sign and Math.Abs the src double you start mucking around with it.
private double Reverse(double src)
{
    double dst = 0;
    int decPoint = 0;

    while (src - (long)src > 0)
    {
        src = src * 10;
        decPoint++;
    }

    int totalDigits = 0;

    while (src > 0)
    {
        int d = (int)src % 10;
        dst = dst * 10 + d;
        src = (long)(src / 10);
        totalDigits++;
    }

    if (decPoint > 0)
    {
        int reversedDecPoint = totalDigits - decPoint;
        for (int i = 0; i < reversedDecPoint; i++) dst = dst / 10;
    }

    return dst;
}

Comment: This suffers from [floating-point accuracy problems](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems). Consider `double d = 1.12 * 10;` where you get `d = 11.200000000000001`.
Comment: and exactly for the reason cited by @AhmedAbdelhameed, OP problem has no solution when dealing with double, since 1.12 is maybe internally stored as something like 1.120000000000001 or 1.19999999999999999
Comment: Of course. Then again, I figured with artificial restrictions a'la no arrays, that thing will only ever need to run past test data anyway :)


$\sum_{n\ge1}n^\alpha r^n<\frac{\Gamma(1+\alpha)}{(1-r)^{1+\alpha}}$

Question: Let $\alpha,r\in(0,1)$. Show that
$$\sum_\limits{n\geq1}n^\alpha r^n<\frac{\Gamma(1+\alpha)}{(1-r)^{1+\alpha}}$$
and that the constant $\Gamma(1+\alpha)$ is best possible.
Edit: Just realized one can just expand the RHS and then it's already solved modulo some info on the generalized binomial coefficients.
Comment: 1. Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.$$$$
2. Please show us your thoughts and attempts to solve this so that we can really help you and not just solve the problem for you.
Comment: What is going on with all the downvotes? I asked this question and soon after (before anyone answered) I edited it and said that I've solved it. Plus Gary answered the question anyways for any future readers. What should the downvotes effect now?
Comment: I don't even know how someone would see this question now? I mean it's answered and has almost no new views. Is it just some guy with multiple accounts?
Comment: @tetra Views grow with time. It seems you have an approach : why not elaborate on it more? The answer to the question isn't part of the context, because it doesn't talk about the origins of the problem. A source for this question should be enough. If you have an approach, perhaps write one line about it in the question, and then add a self-answer (or let me know how it's done and I can add a detailed answer when I have the time).
Comment: @SarveshRavichandranIyer wdym? I already wrote about the approach (which  basically is the solution) and someone already answered. Why is the origin important? 90% of questions don't state the origin.
Comment: @tetra Questions typically don't state the origin : but they may state context in other forms, or (most often) contain detailed enough efforts towards solving the question. Your attempt contains too little information, in my opinion (of course, it is precisely that, which is why you are free to disagree). Context is a requirement for questions on this website. Once again, it takes very little time, and you are free to edit your question. All I'm saying is that the downvotes have to do with this part of your question : even if one person felt it was good enough to answer.
Comment: ok I'm done with this site. makes no sense at all to me
Answer: Assume that $\alpha, r \in (0,1)$. Note that
$$
\frac{{\Gamma (1 + \alpha )}}{{(1 - r)^{\alpha  + 1} }} = \sum\limits_{n = 0}^\infty  {\frac{{\Gamma (n + 1 + \alpha )}}{{\Gamma (n + 1)}}r^n } .
$$
Hence, it is enough to show that
$$
n^\alpha   < \frac{{\Gamma (n + 1 + \alpha )}}{{\Gamma (n + 1)}} \Longleftrightarrow
\frac{{\Gamma (n + 1)}}{{\Gamma (n + 1 + \alpha )}} < \frac{1}{{n^\alpha  }}
$$
for all $n\geq 1$ and $\alpha \in (0,1)$. But \begin{align*}
\frac{{\Gamma (n + 1)}}{{\Gamma (n + 1 + \alpha )}} &= \frac{1}{{\Gamma (\alpha )}}\int_0^1 {t^{\alpha  - 1} (1 - t)^n {\rm d}t}  \le \frac{1}{{\Gamma (\alpha )}}\int_0^1 {t^{\alpha  - 1} {\rm e}^{ - nt} {\rm d}t} \\ & = \frac{1}{{n^\alpha  }}\frac{1}{{\Gamma (\alpha )}}\int_0^n {s^{\alpha  - 1} {\rm e}^{ - s} {\rm d}s}  < \frac{1}{{n^\alpha  }}\frac{1}{{\Gamma (\alpha )}}\int_0^{ + \infty } {s^{\alpha  - 1} {\rm e}^{ - s} {\rm d}s}  = \frac{1}{{n^\alpha  }}.
\end{align*}
By Stirling's formula,
$$
\frac{{\Gamma (n + 1 + \alpha )}}{{\Gamma (n + 1)}} \sim n^\alpha
$$
as $n\to +\infty$, which indicates that the constant $\Gamma(1+\alpha)$ cannot be improved.


What could cause a Trane furnace to not start heating?

Question: I have a newer (2007?) Trane XL90 (model: tdx2b080a9422aa)forced air gas furnace. The problem I am having is the burner and fan will not start. The thermostat is set at 67 degrees and shows it is calling for heat but no heat. Noticed it started coming on and off intermittently over the last few days. I took a multimeter to the ignitor and its not reading ohms. Have not checked the flame sensor yet. Should I? Also the fan is on on the thermostat, however it will not start on the furnace. Is this a startup sequence issue? the fan should start first I believe. Any help would be greatly appreciated.
Comment: Four red flashes. Indicates open temp limit switch.
Comment: What error code are you getting? (blinking lights; what's the pattern and number of the flashes?) There should be a switch for the power; turn it off. If not you may need to cycle the breaker to *actually* reset it. FIRST make note of any error codes.
Comment: Sounds like the plenum overheat sensor.
Comment: Do you live with this person, lol... http://diy.stackexchange.com/questions/51891/split-pack-heating-air-unit
Comment: I could not find any documentation on your equipment. Could you please include the schematic for the furnace, which you should be able to find in the documentation or on the inside of the service panel?
Answer: I have the same issue... I did the filter change, checked all the thermoswitches then it worked for a few hours then no heat LED flashing 4 times. Then I measured the voltage from the 24V transformer and the voltage would vary from 11V to 19V max. Replace transformer and furnace is working perfectly.
Answer: Yours may be different, but generally high temp limit switches look like this:

Order the correct replacement online (if you can figure out the right one to get and have verified it has failed by testing for broken continuity) or take it to your local appliance parts supplier. Bring the model number of your unit with.

"well 4 blinks is an open limit or roll out" -Matthew
What else is on the same wire? (test the other parts of the safety chain)
Roll out switch:

After replacing a faulty ignitor, the elusive culprit for the OP was old batteries in the thermostat.
"I replaced the batteries in the thermostat, even though it wasn't calling for new batteries and now it works".
Comment: @Nick A limit switch is a switch, it's either open or closed. You can test it using the continuity or ohm setting on you multimeter. If the switch is closed, you'll get a reading between the two terminals. If the switch is open, you won't get a reading or you'll measure infinite ohms. The high limit should only be open if the furnace is over heated. If it's open when the furnace is cold, it's bad and needs to be replaced.
Comment: OK back from the local HVAC dealer. Took my ignitor and limit switch. Ignitor was bad and replaced. Limit switch was good. Come back home to put everything back together and its still the sam . No blower fan. And its still flashing 4 red lights. Any ideas? @tester101
Comment: Blower does not come on after thermostat is switched.
Comment: If the blower does not come on when the thermostat is set to the `FAN` (or `ON`) position, there's possibly a problem with the control board. I can't find the schematic for this model online, so I can't confirm this but the blower should turn on despite an open limit. The problem could also be a bad thermostat. Have you tried bypassing the thermostat?
Comment: There should be no ignition sequence for simply turning on the blower in `FAN` mode, it should simply activate the blower relay. If you can't even get that to work, the problem is likely "before" the limits. This would point to the thermostat, control board, power source, or possibly even the blower motor itself.
Comment: Ok guys. Furnace is fixed. As simple as it sounds, I was told to replace the batteries in the thermostat even if it isnt calling for new batteries. Turned on the fan only and then turned heat on and voila! I appreciate all the help!
Comment: Replace that along with the ignitor? Am I able to test resistance on the limit switch?
Comment: Thanks tester101. So would that relate to the fan not starting when the thermostat kicks on?
Comment: Ok I removed the limit switch. got a ohm reading of infinity. Going to replace that as well as the ignitor. Is it common for them to both be bad at the same time? In regards to the blower fan, all breakers are good. Filters were clean however one had gotten dislodged at some point since I replaced them last month and left a decent sized gap. Would this cause these issues?
Comment: @Nick Did you pop the 3 amp fuse on the board (if you were messing with it with the power on it probably tripped).
Comment: @nick cycle the breaker again to reset the lock-out.
Comment: @nick "one of the filters..." do you have 2 filters in parallel (OK) or in series (not OK)?
Comment: If you flip the switch at the thermostat to FAN (or ON not AUTO),  does the blower come on?
Comment: Filters are in a 'v' position
Comment: @nick That's fine, too. Unit status?
Comment: @nick Did you check the roll-out sensors (They should read ~0 ohms), the little fuse, and power cycle the unit?
Comment: Have not tried the roll out switch. At work now will continue in the A.M.
Comment: Agreed, at this point I'd be hot-wiring the blower to test it. A lockout *could* prevent the unit from doing anything.
Answer: My Trane XR90 gas furnace was not producing heat.  The red diagnostic light was blinking 4 times, which means "Open High Temperature Limit Device".
I did some analysis and found that I have two flexible condensate hoses that drain into two 3/4 PVC pipes.  These PVC pipes meet at a Y junction and drain into one PVC pipe that leads to the exterior.  The plumbers clay around one of the flexible hoses was old and crumbling, allowing air to enter. This was creating a backdraft, which prevented condensate from draining and causing a sensor to trip the unit.  As soon as I removed the old, crumbling clay and replaced it with new, pliable clay, the unit starting heating again.  Hope this helps someone.
Answer: It has been my experience that these units are very air filter sensitive, i.e. if dirty or the wrong filter merv rating is used they will go into a limited mode - - - try changing the filter to a Merv 8 and see if it fires up normally .....


Why do people use slime blocks and honey blocks in the same redstone machine?

Question: Some larger flying machines I've seen have alternating rows of honey and slime blocks. Is there some important difference or interaction between the two that would require both types to be used?
Answer: Slime blocks will pull other slime blocks but will not pull honey blocks. Honey blocks will pull other honey blocks but not slime block. This means if you have a design that needs several honey blocks or slime blocks positioned so that they would touch each other without moving each other you will have to alternate between the two.
Comment: I figured this was probably the case.
Comment: I can accept an answer in 6 minutes.


Create contour of given points using MKPolygon in iPhone

Question: I have various number of points each time, and I want to draw contour from them. So I need to draw polygon using only extreme points. Is there any ready to use solution?
EDIT:
Comment: http://stackoverflow.com/questions/17232672/drawing-isotherm-linesor-contour-using-java-given-specific-points if u could find a solution visit this nd help please
Answer: It sounds like you are looking for the convex hull of a set of points.
Implemented using the google maps API v3
Comment: I looks like You are right. But do iOS SDK provide such method?
Comment: Are you using the google maps API v3? If so, it shouldn't depend on anything else.
Comment: Then we need more specific information about your application.  Where to the points come from?  Replace the loop that creates an array of random points with a loop that loads your points (or replace it with the fixed array of points).


Basement subfloor, how exactly should I do it?

Question: I am finishing a basement with my father and want to put in a subfloor. I know if there was ever enough water I would probably have to replace the floor anyways but want to give myself a couple inches more so to protect the expensive electronics I will have down there. There is also a sewer access port and two ground rods that stick ~ 2 inches above the concrete floor.
We were originally planning to lay down pressure treated 2x4's the tall way getting us over the two obstructions and build a plywood floor on top of it. After that we were going to build two small access panels in the floor should we ever need to get to them.
An uncle who is a carpenter stopped by this weekend and said if it was his basement he would not even bother building a subfloor. He said the basement was bone dry and it would be a waste. Even if we did get water it would be trapped in between the 2x4's with no way to get it out. The obstructions are in a corner so we would just box them in somehow going that direction.
This now puts me back to planning. I can't see a disadvantage to building a subfloor other than money and height though the ceiling down there is 8ft so height is not an issue.
What is the best way to build the basement subfloor?
I have seen other methods such as Dri-Core or Delta-FL also suggested. Ideally I would like to create channels so I could somewhat push water out should I ever have an issue. From concrete to carpet please advise me exactly what I need to do in-between.
Answer: I have tried several methods and the best one I have used it foam board on the bottom and 3/4 inch plywood over.  I would never lay down wood on the floor.  Not only will it rot but it will retain moisture.
Comment: Treated wood against concrete, and not constantly submerged isn't going to rot. If you have a stick framed house then you likely have treated wood against your footing.
Comment: Does the foam allow water to travel or is it solid? If I were to use pressure treated sleepers wouldn't this help with rotting?
Comment: Foam board allows water to escape out.  I would only think about solid foam or some sort of rubber (what dri-core uses) for the bottom of a basement subfloor.
Comment: I have seen Dri-Core. Is it just regular old foam board you use on top of the concrete? Nothing else?
Comment: http://www.homedepot.com/p/t/100320356#.UlxEJBDOSZc  - you can glue them down but it is a waste of time because glue will eventually fail.  Float them and tape the seems.  Stagger the seems, then stagger the plywood seems.  You can nail down the plywood but make sure that you use coated nail (tapcons) or something similar.
Comment: @Matthew - but that treated wood will hold a lot of water which could cause mildew/mold issues and the treated wood will eventually warp.  I would never put anything organic on the bottom inch of a basement except for basic wall framing.  All basement that I do either get vinyl/rubber flooring, straight tile on concrete, pad and carpet, or a subfloor with either foam or rubber (dri-core).  I have found the foam board plus plywood install very simple so I have moved to that.
Answer: Putting wood on the concrete in the basement is typically called "sleepers."
You will, without a doubt, be retaining moisture in this layer beneath the finished floor so a proper barrier is paramount. Also, consider that your basement floor is (or should be!) sloped towards the drain so your sleepers will not be flat for your finished floor.
I have a few suggestions if you intend to proceed:
Use 4x4 instead of 2x4 to make fastening easier into the concrete base
Use a "forgiving" finish floor such as carpeting or tile (as you can level with thinset and/or layers of subflooring)
Sleepers should have a clear path for water to run toward the drain. Never create pockets or lay sleepers perpendicular to the flow of water. This may align sleepers in a "star" pattern out from the drain or maybe you should cut channels in the sleepers to permit water to run
Comment: 4x4's are a great idea. What all do I need between them and the concrete?
Comment: I would paint the concrete with a sealant and then I would probably double-layer a vapor barring **above** them, under the plywood.
Comment: Any suggestions for a vapor barrier, links to products?
Comment: @user15608 I have used Tyvek housewrap products but I don't know if they'd be appropriate for this use. Perhaps something like this? http://solutions.3m.com/wps/portal/3M/en_US/Adhesives/Tapes/Promotions/3M-Air-Vapor-Barrier-3015/
Answer: I'm finishing a basement floor that does not have a lot of moisture, but has gotten some water a few times during periods of heavy rain. I'm going to install 1x6 pressure treated decks boards raised off the ground by 3/8" using dense rubber pads. Over the sleepers will be a 6 mil poly vapor barrier and 3/4" Tongue and Groove OSB. I'm going to install a few ventilation vents at the far side of the room from the unfinished furnace room. If we get water I can pull the trim piece under the door to the furnace room and use a fan to blow air under the floor to dry it out. I never want to have to pull out the floor because a little water gets in the basement.
Comment: "I'm going to... I'm going to..."  We like answers that are proven to work, not. This should be a comment. If you've actually done it and it was successful, then it's an answer.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://diy.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://diy.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/151077)
Comment: I'm not sure how this got bumped but I built my basement almost 10 years ago now using the foam & plywood method @DMoore mentioned. It's been fine and water/mold free.
Answer: I suggest some reading at buildingscience.com.  For example, this one might be helpful:  http://www.buildingscience.com/documents/bareports/ba-0309-renovating-your-basment/view?topic=resources/more-topics/homeowner_resources
Comment: -1 Link only answers become useless when the link goes bad and are frequently confused with spam. Be sure to provide context around the link and quote relevant content in case the link goes bad. See [how to answer](http://diy.stackexchange.com/questions/how-to-answer) for more details.


What tool works with this star-shaped screw with a post in the middle?

Question: What tool do I need to unscrew the fasteners shown on the metal lock on this sliding window?
Comment: Kinda looks like the piece used to block a high-rise window from opening fully, to prevent accidental (or purposeful) falls from height. If this is the case and you have kids around, don't remove it and leave it unsupervised. And if the home is a rental, make sure you replace that piece later... and call someone if you're thinking about jumping!
Comment: A Dremel with a metal-cutting blade and a big flat-tip screwdriver.
Answer: Those are tamper proof torx screws.  You will need the appropriate bit.  These are usually sold as kits of security bits.
Comment: Harbor Freight has great sets of security bits!
Comment: @DanMašek I think a source of persisting confusion is that Torx markets (or used to anyway) a system called "Torx Plus" consisting of 5 point tamper proof screws and 6 point normal screws, and no 6 point tamper proof version.
Comment: Thanks. Would something like this from Amazon work? They have other ones with 32 bits but would this 9 piece set likely have a bit to fit the window screws? These are 5 piece sets. Do I need this or a 6 piece set? Thanks https://www.amazon.com/McKay-Multifunction-Security-Tamper-Driver/dp/B01C7R2N9Y/ref=sr_1_3?ie=UTF8&qid=1498773010&sr=8-3&keywords=tamper+proof+torx+screws
Comment: @Help Notice the shape of the screwheads and compare that to the shape of those bits. I don't see how those two could ever fit together. You need the 6-point bits.
Comment: Good to know that. Would this set work? Thanks https://www.amazon.com/McKay-Multifunction-Security-Tamper-Driver/dp/B01C7R2OU2/ref=sr_1_3?ie=UTF8&qid=1498773010&sr=8-3&keywords=tamper%2Bproof%2Btorx%2Bscrews&th=1
Comment: You can often break the pin out of a security torx head by hitting it sideways with a nail set. Then you can you use a normal torx bit.
Comment: I don't want to damage the screw. Let me know if this set on Amazon would work or is there a different set you recommend which has both 5 and 6 point Torx bit. Thanks https://www.amazon.com/McKay-Multifunction-Security-Tamper-Driver/dp/B01C7R2OU2/ref=sr_1_3?ie=UTF8&qid=1498773010&sr=8-3&keywords=tamper%2Bproof%2Btorx%2Bscrews&th=1
Comment: @Help I would think those bits would be OK.  Its hard to tell the size from the pics.


.htaccess rewriting to a different folder where it contains css/js

Question: I have re-written in my .htaccess file in the following way. where I need to direct to games/mybeautifulgame/index.php pages when the user directs to /game?mygame
RewriteEngine On
RewriteRule   [sitename.com]/game?mygame [sitename.com]/games/mybeautifulgame/index.php

However all my bootstrap related CSS, js are inside games/mybeautifullgame folder
example:
games/mybeautifullgame/css/filename.css
games/mybeautifullgame/js/filename.js
Am I doing something wrong?
Answer: You need to use %{QUERY_STRING} to capture the query string data, otherwise ? just means optional for the previous character.
RewriteCond %{QUERY_STRING} ^mygame$
RewriteRule [sitename.com]/game [sitename.com]/games/mybeautifulgame/index.php

Regarding the CSS and js files, you could use absolute paths (just add / at the beginning of the URL).
Comment: I'm typing => https://www.example.com/?game=mygame
Need to show here = > https://www.example.com/games/mybeautifulgame/index.php

RewriteCond %{QUERY_STRING} ^mygame$
RewriteRule https://www.example.com/game https://www.example.com/games/mybeautifulgame/index.php

Have I done anything wrong?
Comment: @coding_lover your original question was /game?mygame but if you want /?game=mygame, use this: RewriteCond %{QUERY_STRING} ^game=mygame$


Are taped drywall corners between rafters likely to crack in cold weather?

Question: I'm remodeling my attic in my bungalow. The way I want to do it is to leave the rafters exposed so I get a rustic loft look. What I did first was put wood strips up between the rafters then installed the flat foam insulation onto the wood strips so there was a expansion gap between the roof and the foam insulation. Then I put up the 3/4 drywall between the rafters.
Now I'm doing the taping on those inside corners of the drywall between the rafters. Because one side of the drywall mud and tape will be on the rafter when we get our extremely cold winter weather even though the attic will be heated can those rafters freeze and cause the corners to crack?
Comment: Gaps aren't left for expansion. They're left for airflow. Also, where does one find 3/4" drywall?
Answer: Since the wood is apt to move a little, I suggest you use "tear away bead", and maybe apply some painter's caulk after a season if you see any gaps. The alternative would be flat taping, but that depends on a pretty close fit between the drywall and the timber.
Comment: Just found something interesting: tear away bead with an integrated gasket, so it'll mate with uneven surfaces and not need caulk. http://www.trim-tex.com/products/drywall-accessories/commercial-beads/tear-away-beads/super-seal-tear-away-l-bead/


Is this a valid function?

Question: What happens to the reference in function parameter, if it gets destroyed when the function returns, then how const int *i is still a valid pointer?
const int* func(const int &x = 5)
{
    return &x;
}

int main()
{
    const int *i = func();
}

Comment: Small thing: I think you meant: `const int *i`, or it won't compile. But otherwise, this is a very interesting question.
Comment: Yes, I meant to write it as `const int *i`.
Answer: §12.2/5:

"A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call."

That means as i is being initialized, it's getting the address of a temporary object that does exist at that point. As soon as i is initialized, however, the temporary object will be destroyed, and i will become just another dangling pointer.
As such, yes, the function is valid -- but with the surrounding code as you've written it, any code you added afterward that attempted to dereference i would give undefined behavior.
Comment: Isn't the "full expression containing the call" here just `func()`, since `const int *i = func()` isn't an expression, it's a definition whose initializer expression is `func()`? ISTR there's some separate text somewhere about the lifetime of temporaries created in initializers.
Comment: @SteveJessop, it's probably still the entire statement up to the ';' since otherwise a `const&` binding to a temporary wouldn't work, which is explicitly allowed in the standard.
Comment: @edA-qamort-ora-y: yes, I'm sure that the lifetime is either the full statement as you say, or perhaps until the initializer has completed (for instance if you do `Foo a = some_temp(), b = some_other_temp();`, then without checking I wouldn't count on the first one living to the semi-colon). It's just a matter of whether someone can be bothered to go diving for the exact text that says so.
Comment: "initializer has completed" - *initialization* has completed, I mean.
Answer: Just because a pointer has a value doesn't mean it's a valid pointer.
In this case it holds an address which used to be that of x, and chances are that address still has the value 5, but it's not valid pointer and you can't count on that value being there.
Answer: int i points to a patch of memory that is unsafe to access, it is not a valid pointer.
Comment: @Steve: that's not guaranteed. Even if it happens to be in the data segment on your implementation, it's still unsafe to access from the POV of the C++ language. For example an implementation *could* copy the value onto the stack (with `5` as an immediate in an asm instruction), leaving `i` pointing to that bit of stack, which could contain anything by the time you come to access it.
Comment: Did you try it?  After the function runs, i points to the number 5...in the Data Segment.
Answer: the variable "i" is still a pointer, but even reading the value it points to will give you undefined behavior.  That's why you should never write a function like func.
Answer: I think that x is created as an un-named temporary on the stack in setting up the call to func(). This temporary will exist until at least the end of the statement in the caller. So the int* i is perfectly valid. It only ceases to be valid at the end of the statement - which means that you cannot use it.
There is something in the standard about un-named temporaries being retained until the last reference to them goes out of scope, but I don't think it covers this explicit and hidden indirection.
[ Happy to have someone tell me otherwise.]
Answer: 5 is program data.  It is in the data segment, not the stack or heap.
So a pointer or reference to it will remain valid for the duration of the program.
Comment: A pointer or reference to it will stop being valid once the function exits. Just because it happens to work on some implementations, doesn't make it any more valid.
Comment: @ MMavipc "It's a pointer to a pointer to 5"  No, the final result is assigned to: const int *i   If you deference *i, you get 5.  It's just a pointer.  And it points to an integer in the Data Segment.
Answer: Default arguments are evaluated every time the function is called, so the call func() is actually func(5) which is binding a temporary to a reference-to-const. The lifetime of that temporary is then extended till the end of the function and the object is destroyed. Any pointer to this object after that is invalid and dereferencing it is undefined behaviour.

Is this a valid function?


display popover on uitextfield

Question: I have created popover using the code below :
UIViewController* popoverContent = [[UIViewController alloc] init]; //ViewController

UIView *popoverView = [[UIView alloc] init];   //view
popoverView.backgroundColor = [UIColor blackColor];

UIDatePicker *datePicker=[[UIDatePicker alloc]init];//Date picker
datePicker.frame=CGRectMake(0,44,320, 216);
datePicker.datePickerMode = UIDatePickerModeDateAndTime;
[datePicker setMinuteInterval:5];
[datePicker setTag:10];
[datePicker addTarget:self action:@selector(Result) forControlEvents:UIControlEventValueChanged];
[popoverView addSubview:datePicker];

popoverContent.view = popoverView;
popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
popoverController.delegate=self;
[popoverContent release];

[popoverController setPopoverContentSize:CGSizeMake(320, 264) animated:NO];
[popoverController presentPopoverFromRect:tempButton.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];//tempButton.frame where you need you can put that frame

The tempbutton is a button created on uitextfied which is hidden (Created to get the frame in tempButton.frame ).
I was wondering if I can use any function in uitextfied which can be used instead of tempbutton.frame like uitextfied.frame or something.
Please let me know I am a noob in ios .
Thanks in Advance.
Answer: You can use:
yourTextField.frame

Just like you would
tempButton.frame

Comment: I Bet that I had tried the same thing the other day but it did not work .Now its working !! WEIRD. I dont know how.Thanks Ryan it helped me a great deal.
Comment: No problem-- an outlet or something may have not been set which is maybe why it was not working when you tried before.
Comment: Quick add-on question: How to add SET DATE and Cancel button on the datepicker ?
Comment: Add a UIToolbar to the top with and create 2 UIBarButtonItems for each Set and Cancel, set them to the toolbar's rightBarButtonItem & leftBarButtonItem. If you need more help I can explain a little more
Comment: In the above example what would the CGRectMake for uitoolbar ? is it CGRectMake(0,44,0,0)  ?
Comment: CGRectMake(0, 0, 320, 44) I believe would work fine. Than add it as a subView to your popoverView
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22424/discussion-between-jacob-wood-and-ryang)

display popover on uitextfield


After resize with GParted there is still no space left

Question: I had very little space on my ubuntu partition, so i decided to give it more space.
I reduced the /dev/sda7 size, and gave 10GB to /dev/sda5 where my ubuntu installation is.
But strangely (or not) the amount of space available it's the same (the amount used went from about 47.77 i think to 57.44) and it still says that there is no space at the root of file system.
Is there an easy way to fix this? I hear this is related to the assembly point / (where my Ubuntu partition is mounted)
I don't have experience dealing with SO partitions, so any help is appreciated. Thanks.
Comment: Whats mounted on the root?
Comment: ubuntu partition is mounted on root
Comment: Try to force fsck on next boot `tune2fs -c 0 /dev/sda5` and reboot. Don't forget afterwards to increase fsck threshold
Comment: Are you housecleaning? https://help.ubuntu.com/community/RecoverLostDiskSpace
Comment: @Krzysztof Księżyk how can i increase the fsck threshold? thanks
Comment: Can anyone help me? I still havent solved this problem
Comment: I gave up on this and uninstalled Ubuntu for now.
Answer: (Ubuntu 18.04.10)
I resized a disk using parted and ran into this because forgot to increase the size of the filesystem. The fix was to use resize2fs.


Does the removal of i386 from the kernel mean Ubuntu is dropping 32 bit support?

Question: I saw recently that the i386 CPU is not going to be supported in the Linux Kernel 3.8
so does that mean that Ubuntu will only be available in the coming years in 64-bit?
Comment: Has to do more with confusing architecture naming.
Comment: For clarification on this subject, see this:  https://askubuntu.com/questions/1029333/will-kubuntu-18-04-lts-be-supported-on-32-bit-machines-for-5-years/1029352#1029352
Answer: No, it means that you won't be able to run Linux on the Intel 80386 chip, the original chip from Intel which supported 32-bit architecture. Those processors had clock speeds of 12-40 Mhz and were superseded by Intel 80486 and then Intel Pentium in early- and mid-1990th.

Other, more modern 32-bit chips (Pentium Pro and above) are still going to be supported. Those processors are characterized as having the i386 architecture but they have some improvements over the original 80386, the use of which allows the removal of some ugly crutches from Linux that are required for 80386 support:

This tree removes ancient-386-CPUs support and thus zaps quite a bit
  of complexity ... which has plagued us with extra work whenever we
  wanted to change SMP primitives, for years.

Anecdote has it that there was some sentimental value in supporting 80386 processor as it was the processor that Linus Torvalds used when he developed the first version of Linux.

[Linux] needs a MMU (sorry everybody), and it specifically needs a
  386/486 MMU (see later). ...  It uses every conceivable feature of the
  386 I could find, as it was also a project to teach me about the
  386.  As already mentioned, it uses a MMU, for both paging (not to disk yet) and segmentation. It's the segmentation that makes it REALLY
  386 dependent (every task has a 64Mb segment for code & data - max 64
  tasks in 4Gb. Anybody who needs more than 64Mb/task - tough cookies).

Also, despite i386 support present in Linux kernel up until version 3.8, in the recent years most Linux distributions were compiled with settings which made them incompatible with 80386 processor anyway. In particular, Ubuntu requires i686 (Pentium Pro) processor or above since Ubuntu 10.10.
Comment: Linus's commit message when he merged the 386 removal patch was "I'm not sentimental.  Good riddance.", so I'm skeptical about the sentimentality claim.  http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commit;h=743aa456c1834f76982af44e8b71d1a0b2a82e21
Comment: x87 is the non-SIMD (mostly MMX/SSE; but AMD did create their own variants for parts of it) floating point extensions to the x86 architecture.  The name comes from the fact that prior to the 486DX all Intel systems needed a separate co-processor chip to do floating point in hardware (the lower cost 486SX which launched after the 486DX was the last x86 chip design Intel sold without an ondie hardware FPU); the chips for it were the 8087, 80287, 80387, and 80487.
Comment: @DanNeely: The commit message from Ingo Molnar, the developer who implemented the change, reads: "Unfortunately there's a nostalgic cost...", so there was a cost at least for Ingo. Of course Linus did not object the change, that would be stupid :) Thanks for the link, btw.
Comment: Don't forget the [x87](http://en.wikipedia.org/wiki/X87) architecture. It's used in some modern Athlon 64s.
Comment: According to the Wikipedia article you link to, the 80386 ran at 12--40 MHz. I distinctly recall having a 386-based system clocked at 16 MHz back when they were still relatively modern.
Answer: Ubuntu hasn't run on proper "i386"'s for a long time, support for the processor was dropped in 10.10.


React router BrowserHistory still asks for hash

Question: I recently started learning react but I ran into an issue:
I am using laravel homestead for my server and on the front-end I am using react. I have to stop displaying the hash sign so in my router I switched from HashRouter to BrowserRouter like so:
import {
    BrowserRouter,
    Switch
} from "react-router-dom";

<BrowserRouter>

                            <Switch>
                                <Route path="/login/:code/:state" component={Login}/>
                                <Route path="/" component={Login}/>
                            </Switch>

                </BrowserRouter>

But when I try to access /login for example the app still asks for that hash: /#/login in order to access the component. Any ideas as to why is this happening? Thank you all for your time!
Comment: have you tried restarting the server and/or clearing the site's cache in your browser?
Comment: @user3229756 I have just done that, sadly with not result
Answer: I have found my issue:
In my web.php routes I was redirecting the user to my welcome.blade only when the '/' route was accessed. All I had to do is change it to redirect it regardless of the route, like so:
How it looked before:
Route::get('/', function () {
    return view('welcome');
});

After the change:
Route::get('{any}', function ($any) {
    return view('welcome');
});

So my issue had nothing to do with react it was regarding the laravel routing.


Conditional move (cmov) in GCC compiler

Question: I saw somewhere that the GCC compiler might prefer sometimes not using conditional mov when converting my code into ASM.
What are the cases where it might choose to do something other than conditional mov?
Comment: I don't know the specifics for GCC. But for general information, see _Replacing conditional jumps with conditional moves_ in Agner Fog's [x86 optimization guide](https://www.agner.org/optimize/optimizing_assembly.pdf).
Answer: Compilers often favour if-conversion to cmov when both sides of the branch are short, especially with a ternary so you always assign a C variable.  e.g. if(x) y=bar; sometimes doesn't optimize to CMOV but y = x ? bar : y; does use CMOV more often.  Especially when y is an array entry that otherwise wouldn't be touched: introducing a non-atomic RMW of it could create a data-race not present in the source.  (Compilers can't invent writes to possibly-shared objects.)
The obvious example of when if-conversion would be legal but obviously not profitable would be when there's a lot of work on both sides of an if/else.  e.g. some multiplies and divides, a whole loop, and/or table lookups.  Even if gcc can prove that it's safe to run both sides and select one result at the end, it would see that doing that much more work isn't worth avoiding a branch.
If-conversion to a data-dependency (branchless cmov) is only even possible in limited circumstances. e.g. Why is gcc allowed to speculatively load from a struct? shows a case where it can/can't be done.  Other cases include doing a memory access that the C abstract machine doesn't, which the compiler can't prove won't fault.  Or a non-inline function call that might have side-effects.
See also these questions about getting gcc to use CMOV.

Getting GCC/Clang to use CMOV
how to force the use of cmov in gcc and VS
Make gcc use conditional moves

See also Disabling predication in gcc/g++ - apparently gcc -fno-if-conversion -fno-if-conversion2 will disable use of cmov.
For a case where cmov hurts performance, see gcc optimization flag -O3 makes code slower than -O2 - GCC -O3 needs profile-guided optimization to get it right and use a branch for an if that turns out to be highly predictable.  GCC -O2 didn't do if-conversion in the first place, even without PGO profiling data.
An example the other way: Is there a good reason why GCC would generate jump to jump just over one cheap instruction?
GCC seemingly misses simple optimization shows a case where a ternary has side-effects in both halves: ternary isn't like CMOV: only one side is even evalutated for side effects.
AVX-512 and Branching shows a Fortran example where GCC needs help from source changes to be able to use branchless SIMD.  (Equivalent of scalar CMOV).  This is a case of not inventing writes: it can't turn a read/branch into read/maybe-modify/write for elements that source wouldn't have written.  If-conversion is usually necessary for auto-vectorization.
Comment: So I think the question is more what the compilers want to support. I guess they would support not inventing writes on an element-by-element basis (i.e., the would support the mprotect scenario). Note that icc _does_ invent writes! I can reliably make it crash by passing a `const char *`-defined string to a method vectorized by icc with invented writes.
Comment: _Compilers can't invent writes to possibly-shared objects_ - doesn't compiler assume that only a write to `std::atomic` variable is a write to a shared variable? A write to a non-atomic variable is data race free only when that variable isn't shared, isn't it?
Comment: @MaximEgorushkin: If this thread never touches `arr[5]` (in the C abstract machine), only `arr[4]` and `arr[6]`, then introducing a non-atomic RMW of `arr[5]` isn't allowed.  Some other thread might be writing it while our loop runs, and we could step on that write.  Inventing writes can create "sharing" (and thus data races) that didn't exist in the source, and thus is disallowed.  (Generally also turning a read into a RMW is disallowed, even though if we're reading then it would already be UB for another thread to be writing.  Without HW data-race detection it might be ok in theory?)
Comment: @PeterCordes - another argument which doesn't involve concurrency is what happens if the memory is mapped read only? Compilers do this in practice (e.g., string constants), and will blow up if you try to write them, even with the same value, so that's an easy way to show this is not allowed without invoking concurrency (which is a more drawn out "proof").
Comment: @BeeOnRope: True, but if the compiler can prove that any part of an array is written, then the whole thing can't be in read-only memory.  Or at least a struct.  Or is it legal (not UB) to `mprotect` part of an array so part of it is `const` but the rest isn't?  Probably with the fairly strict don't-invent-writes behaviour of real compilers like GCC, that's fine.  It's potentially undesirable for real-world compilers to invent writes because it could break COW sharing unnecessarily.
Comment: @PeterCordes - right, but I don't think they use that reasoning. I don't think you'll find answers to stuff like "is it legal (not UB) ... `mprotect`", sine those things are already outside of the standard. So in that sense, the concurrency thing is perhaps a better reason since the motivation lies inside the standard. Things like "read only" are mostly outside (although the standard does accommodate them e.g., by banning modification of const-defined data).

Conditional move (cmov) in GCC compiler


How can I design a registration form with 10 fields for multiple users?

Question: I'm in a situation to design registration form that asks A Dad [a user] to register his "Son or Sons" in a sports activity and pay for this registration.
In order to enable Dads to pay one time even if they have more than one son to register - 2 or 3 sons, for example,- Dad should add all details for every son individual. Usually, this details is about 10 fields, they are all required and there is no way to reduce these fields or details.
How can I ask Dad [a user] to add every son details individual in a simple elegant way that can be applied in web and responsive for mobile user interface (UI), in other words, I'm looking for best practices UI Patterns for inspiration in such a case.
There is no problem if a dad has one son because in this case, he will add the 10 fields details one time.
Comment: Are all of those 10 fields related to the particular kid, or are some of them shared (like, an address or a payment method, for example)? If some of the fields are shared, you can reduce the fields a bit...
Comment: 10 fields sounds a bit much. The fact it is in different fields suggests the system needs specific values to be used later
Answer: As in my mind, you should separate the fields into 2 types:

Fields which is shared between sons
Fields which is related to son

You can get shared information in separated section and put a section in order to let dad to add his sons. By clicking on the "New Son" button, the rest of fields will be appeared.
It is highly recommended to reduce the number of fields or at least group them. If you can not separate fields and all of them is related to sons, you don't need the first form group.
Answer: You'll need to screens. One for listing the number of children of the object (dad) and one for adding new children.
an editable table for listing and then a creation screen for adding new children
the listing must have functions for removing/editing children created in error or for modification
There are patterns for both these views on sites like http://www.mobile-patterns.com/
Answer: Seems to me that the user, in this case, the dad, is paying to register his children for the sports activity. If this is the case, then his goal is to confirm their participation, so why require all the fields to be filled at the checkout moment? Seems it would be easier to have them enter the number of registrations needed, fill the needed info to proceed, pay and then provide further details.
I think it's important to make it clear to the user that they must pay for each son's registration, for that reason I'd present each registration as products that are added to a shopping cart and make the price and item count visible as the user selects the number of registrations needed.


Autocomplettextview filtered by input keys

Question: I use autocompletetextview with SimpleCursorAdapter to get data from sqlite. I'd like to get its drop down list started by the entered key. In my autocompletetextview, the list is not shown or filtered by input text.
eg,
If user enter "an", all text started with "an" will be seen in this list.
In Java
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new);

        txtPNo = (AutoCompleteTextView) findViewById(R.id.txtSTo);

        mDbHelper = new DBAdapter(this);
        mDbHelper.open();

        SimpleCursorAdapter notes = fillToData();
        txtPNo.setAdapter(notes);
}

    private SimpleCursorAdapter fillToData() {
        Cursor c = mDbHelper.getName();
        startManagingCursor(c);
        String[] from = new String[] {DBAdapter.Name,DBAdapter.No1};
        int[] to = new int[] {R.id.txtName,R.id.txtNo1};

        Log.d(TAG, "cursor.getCount()=" + c.getCount());
        SimpleCursorAdapter notes =
            new SimpleCursorAdapter(this, R.layout.autocomplete, c, from,
to);

        return notes;
    }

In new.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#ffffff"
    >
   <AutoCompleteTextView android:id="@+id/txtSTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="#000000"
        android:hint="To"
        android:completionThreshold="1"
        android:selectAllOnFocus="true"
        android:layout_alignParentTop = "true"
        android:layout_alignParentLeft="true"/>
</RelativeLayout>

In autocomplete.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:stretchColumns="0" android:padding="5dp">
    <TableRow android:padding="5dp">
        <LinearLayout android:orientation="vertical">
            <TextView android:id="@+id/txtName"
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:textColor="#000000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView android:id="@+id/txtNo1"
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:textColor="#000000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
    </TableRow>
</TableLayout>

How to implement to get just filtered list?
Answer:     txtPNo = (AutoCompleteTextView) findViewById(R.id.txtSTo);

    mDbHelper = new DBAdapter(this);
    mDbHelper.open();

    SimpleCursorAdapter notes = fillToData();
    txtPhoneNo.setAdapter(notes);

Umm, if you just copy-n-pasted your code...
The issue is the variable name.
txtPNo != txtPhoneNo

AutoCompleteTextView
Comment: sorry. txtPNo.setAdapter(notes);
Comment: okay, i think your problem is that you haven't setup SimpleCursorAdapter Correctly. If you look at http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html it says you need to set a Filter. Also look at: http://developer.android.com/reference/android/widget/CursorAdapter.html#runQueryOnBackgroundThread(java.lang.CharSequence)


Ensure that fields with specific annotations are 'private'

Question: Very common mistake in our code is to write
<code>@Mock Object object;
@InjectMocks Subject subject;
</code>
instead of
<code>@Mock private Object object;
@InjectMocks private Subject subject;
</code>
This prevents PMD/FindBugs/IntelliJ from issuing warning when the field becomes unused and also our code reviews are bloated with "make this field private" comments.
Is there any static-analysis rule in any tool to warn when fields with specific annotations do not have expected visibility?
I found Checkstyle's VisibilityModifier, but it marks all non-private fields, not just the ones with specific annotations.
Comment: Won't post this as a new answer, because I don't have access to it - it's a commercial tool. Fortify seems to support both [structural](https://blog.gdssecurity.com/labs/2013/12/2/building-fortify-custom-rules-for-spring-mvc.html) and [XPath](https://stackoverflow.com/questions/7634663/writing-rules-in-fortify) queries.
Answer: You could use the Structural Search Inspection in IntelliJ IDEA. For example with a pattern like this:
<code>@Mock @Modifier("packageLocal") $FieldType$ $FieldName$ = $Init$;
</code>
FieldType: min: 1, max: 1
FieldName: min: 1, max: 1
Init: min: 0, max: 1
Comment: Thanks - do you think it is possible to automate it on Jenkins and to fail the build with meaningful message if such pattern is matched?
Comment: IntelliJ IDEA has an inspect.sh script it's bin directory, which can be used for something like this. You might also need some kind of plugin for Jenkins. Sorry I can't be more helpful, I have never used Jenkins myself.
Answer: You could use PMD's Rule Designer to create a new XPath rule, which can be embedded into a PMD ruleset xml file. I haven't used PMD with IntelliJ IDEA or Jenkins, but I'm sure the plugins exist.
Here's a rule I've made (not tested outside the Rule Designer):
<code><rule  name="NonPrivateMockAnnotation"
  message="Mock anotation should be private"
  class="net.sourceforge.pmd.lang.rule.XPathRule">
  <description>
  </description>
  <properties>
    <property name="xpath">
    <value>
<![CDATA[
//ClassOrInterfaceBodyDeclaration[
    Annotation/MarkerAnnotation/Name[
        @Image = 'InjectMocks' or
        @Image = 'Mock'
    ] and
    FieldDeclaration/@Private = 'false'
]
]]>
    </value>
    </property>
  </properties>
  <priority>3</priority>
  <example>
<![CDATA[
class Example {
  @Mock Object object;
  @InjectMocks Subject subject;
}
]]>
  </example>
</rule>
</code>
Comment: And here's a tutorial on writing rules: http://techtraits.com/programming/2011/11/05/custom-pmd-rules-using-xpath/
Comment: Above link seems to be gone, adding an archive link: https://web.archive.org/web/20150522015043/http://techtraits.com/programming/2011/11/05/custom-pmd-rules-using-xpath/


How to get an loading gif image when we use infinite scroll in angularjs?

Question: Suppose if the data is more and we keep a infinite scrolling with infinite-scroll-distance=2 ,when ever the data is loading a image of loading gif must be displayed ..Is it possible to do ..Can i have any example for it ?
Comment: https://jsfiddle.net/U7Bz9/3327/ can anyone help me to implement that loading gif in the above fiddle
Comment: you can refer this link http://binarymuse.github.io/ngInfiniteScroll/demo_async.html
Answer: You can use ng-hide directive for this. You need to add loading image which will work as per content load on-top of ng-hide
Angular Code
function Main($scope) {
$scope.items = [];
$scope.showLoader = false;
var counter = 0;
$scope.loadMore = function() {
    for (var i = 0; i < 5; i++) {
        $scope.items.push({id: counter});
        counter += 10;
     }
    $scope.showLoader = true;
  };
    $scope.loadMore();
}

  angular.module('scroll', []).directive('whenScrolled', function() {
    return function(scope, elm, attr) {
      var raw = elm[0];

      elm.bind('scroll', function() {
        if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
            scope.$apply(attr.whenScrolled);
        }
      });
   };
 });

HTML

{{i.id}}

Fiddle: https://jsfiddle.net/anandgh/LedkLocL/
Hope this helps you.


How to group files based on filenames from multiple paths in Java

Question: I would like to group specific files based on their file names from multiple paths.  I have followed this stackoverflow link.  I have not been able to loop through each file after I start streaming the path to find that specific file name.
Here are the paths with files contents:
/var/tmp/data_sample1/data2_first_example.set.csv
/var/tmp/data_sample1/data3_first_example.set.csv
/var/tmp/data_sample1/data1_first_example.set.csv
/var/tmp/data_sample2/data2_second_example.set.csv
/var/tmp/data_sample2/data1_second_example.set.csv
/var/tmp/data_sample2/data3_second_example.set.csv
/tmp/csv_files/data_sample3/data2_third_example.set.csv
/tmp/csv_files/data_sample3/data1_third_example.set.csv
/tmp/csv_files/data_sample3/data3_third_example.set.csv

Enum Class:
enum PersonType {
    A,
    B
}

FileName.java
import java.util.Arrays;
import java.util.List;

public class FileName {
    private final String first = "_first_sample";
    private final String second = "_second_sample";
    private final String third = "_third_sample";

    private final List<String> filenames = Arrays.asList(first, second, third);
    public List<String> getFilenames() {
        return filenames;
    }
}

CSVFiles.java
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

public class CSVFiles {

    private PersonType personType;
    private List<String> fileNames = new ArrayList<>();
    private List<File> firstSample = new ArrayList<>();
    private List<File> secondSample = new ArrayList<>();
    private List<File> thirdSample = new ArrayList<>();

    public CSVFiles(PersonType personType, List<String> paths) {
        if (personType == PersonType.A) {
            this.personType = personType;
            FileName fileName = new FileName();
            this.fileNames = fileName.getFilenames();
            setCSVFiles(paths);
        }
    }

    public List<File> setCSVFiles(List<String> paths) {
        List<Path> collect = paths.stream()
                .flatMap(path -> {
                    try {
                        return Files.find(Paths.get(path), Integer.MAX_VALUE,
                                (p, attrs) -> attrs.isRegularFile()
                                        && p.toString().contains(".set")
                                        && p.toString().endsWith(".csv")
                        );
                    } catch (IOException ex) {
                        throw new UncheckedIOException(ex);
                    }
                }).collect(Collectors.toList());

        return collect.stream()
                .map(Path::toFile)
                .filter(file -> {
                    if (file.getName().contains("_first_sample")) {
                        firstSample.add(file);
                        return true;
                    } else if (file.getName().contains("_second_sample")) {
                        secondSample.add(file);
                        return true;
                    } else if (file.getName().contains("_third_sample")) {
                        thirdSample.add(file);
                        return true;
                    }
                    return false;
                })
                .collect(Collectors.toList());
    }
}

CSVFilesTest.java
import org.junit.Test;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class CSVFilesTest {

    @Test
    public void test() {
        String data_sample1 = "/var/tmp/data_sample1";
        String data_sample2 = "/var/tmp/data_sample2";
        String data_sample3 = "/tmp/csv_files/data_sample3";
        List<String> paths = Arrays.asList(data_sample1, data_sample2, data_sample3);
        System.out.println(paths);

        CSVFiles csvFiles = new CSVFiles(PersonType.A, paths);
    }
}

Desired Output:
firstSample: [data1_first_example.set.csv, data2_first_example.set.csv, data3_first_example.set.csv]
secondSample: [data1_second_example.set.csv, data2_second_example.set.csv, data3_second_example.set.csv]
thirdSample:  [data1_third_example.set.csv, data2_third_example.set.csv, data3_third_example.set.csv]

Any feedback is appreciated!
Comment: In your collect method you are looking for [groupingby](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-) you could remove the data prefix and the extension from the end of the path and use that as the grouping criteria
Comment: If you are grouping by file name only then put all of your file paths in one large list of strings(or a list of paths and then use map to convert them into strings) and you could do something like collect(Collectors.groupingBy(path->path.subString(path.lastIndexOf("/")+1))); .This will return you Map> where the key is the file name(which you extracted in the grouping by clause), and the value is the list of all paths ending with(or having) the file name.
Comment: Thank you @Sync it, will groupingby specify for each file in a specific file list? Maybe some code snip will help.
Comment: Thank you so much @Sync it! That worked better!  I added an update with your solution.  Now I want to close this story as solved....
Comment: Glad I could help but please put your solution as an actual answer(don't edit the question with your solution)and mark it as accepted so not only would it help others having your problem but you would also gain reputation points when people upvote your answer
Comment: Done miss that post answer button, ok it will let me check as answered after 12 hours so will that later. Thank you @Syncit
Answer: Solution thanks to "sync it" comments:
    public Map<String, List<String>> setCSVFiles(List<String> paths) {
        List<Path> collect = paths.stream()
                .flatMap(path -> {
                    try {
                        return Files.find(Paths.get(path), Integer.MAX_VALUE,
                                (p, attrs) -> attrs.isRegularFile()
                                        && p.toString().contains(".set")
                                        && p.toString().endsWith(".csv")
                        );
                    } catch (IOException ex) {
                        throw new UncheckedIOException(ex);
                    }
                }).collect(Collectors.toList());

        return collect.stream()
                .map(Path::toString)
                .collect(Collectors.groupingBy(path ->
                        path.substring(path.lastIndexOf("/")+1)
                        ));
    }


Gulp watch error with gulp-pug

Question: I am trying to set up my gulp to watch for pug changes, but I get the following error, and I have no idea what that can be:
events.js:141
      throw er; // Unhandled 'error' event
      ^
SyntaxError: Unexpected token (19:0)
    at Parser.pp$4.raise (/../node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp.unexpected (/../node_modules/acorn/dist/acorn.js:603:10)
    at Parser.pp$3.parseExprAtom (/../node_modules/acorn/dist/acorn.js:1822:12)
    at Parser.pp$3.parseExprSubscripts (/../node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/../node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/../node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/../node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/../node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$1.parseVar (/../node_modules/acorn/dist/acorn.js:1034:28)
    at Parser.pp$1.parseVarStatement (/../node_modules/acorn/dist/acorn.js:917:10)

My gulpfile.js looks like this:
const gulp = require('gulp');
const pug = require('gulp-pug');

gulp.task('pug', () =>
  gulp.src('pug/*.pug')
    .pipe(pug({ pretty: false }))
    .pipe(gulp.dest('.'))
);

gulp.task('watch', function (){
  gulp.watch('pug/*.pug', ['pug']);
});

Comment: Which is the line 141? Do you have that folder (and at least a pug file)?
Answer: The problem could potentially be .pipe(gulp.dest('.')) you should specify an actual folder name. e.g. .pipe(gulp.dest('folderName'))  /
 .pipe(gulp.dest([__dirname])
Additionally add a return statement to gulp.src('pug/*.pug')
so it looks like
return gulp.src('pug/*.pug') it's avoids errors with the inclusion of a return statement.
Can you edit your question to include your Pug file, please ?

Gulp watch error with gulp-pug


Sum of complex polynomial

Question: I wish to prove that all the roots of polynomials of the form:
$$P(z)=1+2z+3z^2+...+nz^{n-1}$$
are confined within a circle $|z|<1$.
Here is what I did so far:
I multiplied $P(z)$ with $\frac{1-z}{1-z}$, so:
$\frac{1-z}{1-z}P(z)=\frac{1}{1-z}\sum_{k=1}^n (kz^{k-1}-kz^k)=\sum_{k=1}^n k(z^{k-1}-z^k)$
How should I proceed from here?
Comment: Do you mean **the roots** of the polynomial are in the disk $\;|z|<1\;$ ? Is that what "confined" mean here?
Comment: This is a direct consequence of [Gauss-Lucas theorem](https://en.wikipedia.org/wiki/Gauss%E2%80%93Lucas_theorem).
Comment: @DonAntonio I feel so dumb now, I missed that part. thanks.
Comment: Your idea can also be taken to term. Instead of multiplying and dividing by $1-z$, do so but with $(1-z)^2$. The numerator will cancel except for three terms. Then you can apply Rouche's theorem to it.
Answer: Observe that
$$T(z)=z+z^2+z^3+\ldots+z^n=z\left(1+z+\ldots+z^{n-1}\right)=z\frac{z^n-1}{z-1}$$
So all the zeros of $\;T(z)\;$ are within $\;|z|\le1\;$ . Now calculate $\;T'(z)\;$ and apply Gauss-Lucas Theorem...

Sum of complex polynomial


Calculating mean of certain list values in Python

Question: I've been trying to calculate the mean of the third, fourth and fifth values in each row of a .csv file, but my program will only calculate for the first row rather than for each row.
For example, this code:
file=open("file.csv", "r")
data=csv.reader(file)

data=[[row[0],row[1],eval(row[2]),eval(row[3]),eval(row[4])] for row in data]

from statistics import mean

numbers=[row[2],row[3],row[4]]
newdata=[[row[0],row[1],mean(numbers)] for row in data]
sort=sorted(newdata,key=operator.itemgetter(2), reverse=True)

for eachline in sort:
    print(eachline)

file.close()

...reads this file:
Phillip,Turner,1,4,10
Sarah,Connor,4,8,1
Alex,Grice,2,10,3
Cheesy,Wotsit,3,2,6
Chris,Mclaughlin,10,9,8
Alison,Humphries,4,2,6

and produces this:
['Phillip', 'Turner', 4.0]
['Sarah', 'Connor', 4.0]
['Alex', 'Grice', 4.0]
['Cheesy', 'Wotsit', 4.0]
['Chris', 'Mclaughlin', 4.0]
['Alison', 'Humphries', 4.0]

Comment: `newdata=[[row[0],row[1],mean(row[2:])] for row in data]`
Comment: where did you get the idea to use eval? Also is this more gcse exam stuff?
Comment: worked @Jkdc thank you - post it as an answer and I'll best answer it!
Comment: @gulliver you also have to convert each item that you want to find a mean of, to a numerical type (int or float). Check my answer.
Answer: Actually its not the mean of the first line, its the mean from the last. After the first list comprehension, row assumes the value of the last row, and when you use row[2] to create numbers list, you create a static list using the values from the last row.
You can correct that by making mean of the correct numbers:
file=open("file.csv", "r")
data=csv.reader(file)

data=[[row[0],row[1],eval(row[2]),eval(row[3]),eval(row[4])] for row in data]

from statistics import mean

newdata=[[row[0],row[1],mean([row[2],row[3],row[4]])] for row in data]
sort=sorted(newdata,key=operator.itemgetter(2), reverse=True)

for eachline in sort:
    print(eachline)

file.close()

Answer: import csv
averages = []
with open("file.csv", "r") as f:
  reader = csv.reader(f, delimiter=",")
  for row in reader:
    values = map(int, row[2:])
    averages.append(row + [sum(values) / float(len(values))])
for avg in sorted(averages,key=lambda x: x[-1]):
  print avg

prints
['Cheesy', 'Wotsit', '3', '2', '6', 3.6666666666666665]
['Alison', 'Humphries', '4', '2', '6', 4.0]
['Sarah', 'Connor', '4', '8', '1', 4.333333333333333]
['Phillip', 'Turner', '1', '4', '10', 5.0]
['Alex', 'Grice', '2', '10', '3', 5.0]
['Chris', 'Mclaughlin', '10', '9', '8', 9.0]

Answer: You have to do this numbers=[row[2],row[3],row[4]] for each row. Not just once.
You could do:
In [511]: data = csv.reader(open('../a.csv'))

In [512]: x = [[row[0], row[1], np.mean(map(float, row[2:]))] for row in data]

In [513]: x
Out[513]:
[['Phillip', 'Turner', 5.0],
 ['Sarah', 'Connor', 4.333333333333333],
 ['Alex', 'Grice', 5.0],
 ['Cheesy', 'Wotsit', 3.6666666666666665],
 ['Chris', 'Mclaughlin', 9.0],
 ['Alison', 'Humphries', 4.0]]

In [514]: sorted(x, key=lambda v: v[2], reverse=True)
Out[514]:
[['Chris', 'Mclaughlin', 9.0],
 ['Phillip', 'Turner', 5.0],
 ['Alex', 'Grice', 5.0],
 ['Sarah', 'Connor', 4.333333333333333],
 ['Alison', 'Humphries', 4.0],
 ['Cheesy', 'Wotsit', 3.6666666666666665]]

Answer: try like this:
with open('your_file') as f:
    for x in f:
        x = x.strip().split()
        print x + [sum(map(int,x[2:]))/float(len(x[2:]))]

Answer: newdata=[[row[0],row[1],mean(numbers)] for row in data]
Should be
newdata=[[row[0],row[1],mean(row[2:])] for row in data]


At which stage of the pipeline is the projection transform applied?

Question: I've found a site that provides an overview of the OpenGL pipeline:
Rendering pipeline overview
Now in the 3th phase (vertex processing) it says that after the transform feedback, there is the primitive clipping. If I am not mistaken, the primitive clipping must occur after that the vertices are multiplied by the projection matrix, otherwise it's impossible to determine if the primitives are inside or outside the view volume defined with glFrustum().
I know that in a typical GLSL shader you need to apply the modelview matrix to the vertices, so that you obtain a vertex in eye coordinates. So if I am not mistaken, at the end of the vertex shader you don't have vertices defined in clip coordinates yet. But this makes me think: where is the projection matrix applied? it seems like it's missing in this pipeline overview.
Comment: "*otherwise it's impossible to determine if the primitives are inside or outside the view volume defined with glFrustum()*" That page defines the core profile of OpenGL; `glFrustum` *does not exist* in modern OpenGL anymore. Projection is the responsibility of the writer of the shader, not of the rendering pipeline.
Answer:
I know that in a typical GLSL shader you need to apply the modelview matrix to the vertices, so that you obtain a vertex in eye coordinates.

This is not quite correct, you need to apply the modelviewprojection matrix and thus transform your vertices into Clip Space Coordinates.
You can apply the ModelView Matrix in certain instances, e.g. if you want to calculate light in Eye Space. However, the gl_Position will then still not use the ModelView but the ModelViewProjection Matrix and your light/whatever- position will use the ModelView Matrix and be transferred to the fragment shader via the out variables.
For a more detailed discussion, you can look into the comments on this question, I had to be corrected about that myself (since not all literature is clear/correct about Normalized Device Space and Clip Space).


How can I stucture my django code for a webpage with suppose 4 different divisions of data

Question: I am constructing a webpage in django which will parse data and show it all on a single webpage which is divided into 4 sections.
So, I need help in organizing the code so that the backend processing code for different sections can be kept seperate(maybe into seperate methods?), but everything needs to be called and rendered on a single request.
Thanks. :)
Answer: If the code to process date for each section is minimal, just put it all in the class or function for your view. If there is a lot of it, make a function for each section of data processing outside your view class or function, and just call that within your view so that your code stays readable. Regardless of which method you choose, remember to send the resulting data to your template as context, or to wherever you need it if Django is only your backend.
Comment: Yeah, I can do this. So the data that I receive will have to be then combined into a single context in the view function and then sent to a single template?
Comment: What do you mean by single context? Just put it all into a dictionary.

{'data1': data1, 'data2': data2, 'data3': data3, 'data4': data4}

Then, put that dictionary as the context into your render function
Comment: I meant a single 'context' variable.
Understood. Thanks man, You really helped a lot.
Comment: Is your data for each section distinct? Context passed along to the render equation has to be a dictionary. You will then be able to access the values of this dictionary by using the corresponding keys as variables in your template.
Comment: The data is mostly distinct, though it is derived from the same queryset. Hence for that I have supplied that queryset to the init function of the class you mentioned. Then i will use that queryset in the separate functions. Would that be a good architecture?


How to increase the max connections in postgres?

Question: I am using Postgres DB for my product. While doing the batch insert using slick 3, I am getting an error message:

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.

My batch insert operation will be more than thousands of records.
Max connection for my postgres is 100.
How to increase the max connections?
Comment: 1. First check if your middleware is not keeping too many connections open, or is leaking them. 2. (maybe) next use a connection pooler. 3. (almost) never increase the number of allowed connections on this type of problem, in most cases this will make things worse. (except if you are absolutely sure)
Comment: http://stackoverflow.com/questions/9798705/arval-sqlexception-fatal-sorry-too-many-clients-already-in-postgres
Comment: Use a connection pool like pgBouncer or pgPool
Comment: See also https://stackoverflow.com/a/58373811/1609929 for an option using SQL commands instead of configuration.
Comment: @FrankHeikens What is the preferred connection pooler for postgres in windows server?
Answer: Just increasing  max_connections is bad idea. You need to increase shared_buffers and kernel.shmmax as well.

Considerations
max_connections determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.
Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.
Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.
A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.

How to increase max connections
1. Increase max_connection and shared_buffers
in /var/lib/pgsql/{version_number}/data/postgresql.conf
change
max_connections = 100
shared_buffers = 24MB

to
max_connections = 300
shared_buffers = 80MB

The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.

If you have a system with 1GB or more of RAM, a reasonable starting
value for shared_buffers is 1/4 of the memory in your system.
it's unlikely you'll find using more than 40% of RAM to work better
than a smaller amount (like 25%)
Be aware that if your system or PostgreSQL build is 32-bit, it might
not be practical to set shared_buffers above 2 ~ 2.5GB.
Note that on Windows, large values for shared_buffers aren't as
effective, and you may find better results keeping it relatively low
and using the OS cache more instead. On Windows the useful range is
64MB to 512MB.

2. Change kernel.shmmax
You would need to increase kernel max segment size to be slightly larger
than the shared_buffers.
In file /etc/sysctl.conf set the parameter as shown below. It will take effect when postgresql reboots (The following line makes the kernel max to 96Mb)
kernel.shmmax=100663296

References
Postgres Max Connections And Shared Buffers
Tuning Your PostgreSQL Server
Comment: Check your current kernel.shmmax setting (`cat /proc/sys/kernel/shmmax`) prior to changing it. On modern systems it's already set ridiculously high and should not be changed. Mine is set to `18446744073692774399` by default on Ubuntu 18.04.
Comment: You may use [PGTune](https://pgtune.leopard.in.ua/) to help you determine these settings for your system
Comment: 100663296 Bytes = 96 MB (in binary). shmmax is *maximum size of a shared memory segment*. Now because we increased size of shared buffers we need to change shmmax to accomodate the increased memory for caching.
Comment: From the linked article: "Generally, PostgreSQL on good hardware can support a few hundred connections". Your statement "A well-written app typically doesn't need a large number of connections" applys only to low-traffic apps. If each session needs 0.05s on the database you can serve max. 2000 clients per sec. Even pgbouncer (you should definetly use it!) can't get you around this. If you need to serve 5000 clients/sec you will need 250 connections and so on. Otherwise you will see "query_wait_timeout" from pgbouncer. If you have >=16G RAM & enough CPU cores (8+) that is absolutely no problem.
Comment: @Robbo_UK 96 * 1024 * 1024 = 100663296
Comment: great answer.  couple of questions.. how is  100663296 equal to 96MB?   and why do we change shmmax  what does that do?
Comment: I found this online calculator useful for converting units, [for example 96MB to kB](http://unitconverter.io/megabytes/bytes/96)..
Comment: Is it fair to assume that just `pg_bouncer` alone will NOT solve the idle connection problem? (postgres v13)
Comment: I ran `ipcs l` and it says `max total shared memory (kbytes) = 18014398442373116`. Should I worry?
Comment: Is there any rule of thumb regarding how the max_connections and shared_buffers correlate?
Answer: Adding to Winnie's great answer,
If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.
SHOW config_file;

For me changing the max_connections alone made the trick.
EDIT: From @gies0r: In Ubuntu 18.04 it is at
/etc/postgresql/11/main/postgresql.conf

Comment: Thank you. In Ubuntu 18.04 it is ```/etc/postgresql/11/main/postgresql.conf ```
Comment: you can also query `pg_settings`: `SELECT name, setting FROM pg_settings;`
Comment: In Windows it is C:\Program Files\PostgreSQL\12\data\postgresql.conf
Answer: If your postgres instance is hosted by Amazon RDS, Amazon configures the max connections for you based on the amount of memory available.
Their documentation says you get 112 connections per 1 GB of memory (with a limit of 5000 connections no matter how much memory you have), but we found we started getting error messages closer to 80 connections in an instance with only 1 GB of memory. Increasing to 2 GB let us use 110 connections without a problem (and probably more, but that's the most we've tried so far.) We were able to increase the memory of an existing instance from 1 GB to 2 GB in just a few minutes pretty easily.
Here's the link to the relevant Amazon documentation:
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Limits.html#RDS_Limits.MaxConnections
Answer:
Locate postgresql.conf file by below command

locate postgresql.conf

Edit postgresql.conf file by below command

sudo nano /etc/postgresql/14/main/postgresql.conf

Change
max_connections = 100
shared_buffers = 24MB

to
max_connections = 300
shared_buffers = 80MB

Answer: change max_connections  variable
in postgresql.conf file located in
 /var/lib/pgsql/data or /usr/local/pgsql/data/
Comment: Why pg_hba.conf? It doesn't have any parameter about the number of connections, only how to connect. postgresql.conf on the other hand.... But hundreds of connections is a bad idea, don't do it, use a connection pool or suffer from performance issues. PostgreSQL 8.3 is EOL for many years, please use an up to date version.
Answer: For Mac M1 users

/opt/homebrew/var/postgresql@14/postgresql.conf
Answer: for postgres 13 running in docker/kubernetes the path is:
/var/lib/postgresql/data/postgressql.conf
update max_connections = 300 and restart container/pod
Comment: Already answered.


Is there something you need to do to activate the Blacksmith at the beginning of Diablo 3?

Question: My husband can speak to the blacksmith, but he has all his stuff still bundled into duffle bags, and there is no "Craft" option. He's level 9.  I'm also level 9, and I've been able to speak to the blacksmith and use the smithy for some time. My other characters similarly have had no trouble.
Right now, our game is at "The Shattered Crown" quest stage.
Is there someone else he needs to speak with, or some sort of event that must be triggered to have the smith set up shop?
Answer: Once you have unlocked the blacksmith and jeweler on one character you can use them on all your characters at all stages of the game (even before you normally would be able to otherwise).
To unlock the blacksmith you must complete A Shattered Crown (lore and possible spoilers at that link).

 After returning the crown, he confesses he wants his life to have some meaning and your
 character suggests that he craft items for your use.


File downloading in AJAX with download counter

Question: I am creating simple file download counter in AJAX. But in my code, counter is working in PHP codemeans it is increasing its value by one per download but file is not downloading. Below is my code
index.php

    Download

download_counter.php
<?php
       //Code for counter Increment
      //Query to Update database
?>

I don't have any problem with database or download counter in PHP code. I have problem with file downloading. Counter is increasing by one but file is not downloading.
Comment: thakns @mapek...! Its working now
Comment: You have to replace `return false;` with `return true;` in your `click` event handler.
Comment: Great! I've added it as an answer and linked to an useful answer of another question.
Answer: You have to replace return false; with return true; in your onclick event handler so that the default event of your hyperlink will be executed.
Please check this answer for more information about return false; in event handlers:
https://stackoverflow.com/a/11184286/3647441


What is the max amount of achievements I can get by performing any one action?

Question: As most are probably aware, Team Fortress 2 has a ton of achievements, most of which are seemingly unrelated to each other. But I've been curious about this for a long time.
If I was a new player, what is one action I could perform that would net the most amount of achievements instantly?
For example, I came up with that if I was a spy, disguised as a medic, who killed that medic (who was healing me) with a backstab while he had an Ubercharge ready and also got Revenge on him at the same time, I would get the Achievements "Dr. Nooooo", "FYI I am a Spy", "Come in from the Cold", "Identity Theft", and "Insurance Fraud", all at the same time. Is there anything else more advanced than this?
Comment: Cross-reference: This same question [has been discussed](http://www.reddit.com/r/tf2/comments/2j7lbq/the_largest_amount_of_achievements_you_can_get_in/) on Reddit TF2, [more than once](http://www.reddit.com/r/tf2/comments/1r2lgo/experimentmaximum_achievements/).
Answer: The Soldier can put together a pretty good chunk - though as you might expect, it's rather difficult to set up:

Be on a server where Halloween mode is on for any reason.
The map is Dustbowl or Gravel Pit.
Have a crowd of enemies:

A Pyro, who:

Reflected one of your rockets recently, and
has set you on fire

A Demoman,

Wearing a Gibus
and Pyrovision Goggles
whom you're one kill away from dominating

A Sniper

with a Balloonicorn
who's dominating you

A Spy, who:

just stabbed one of your teammates
is disguised as you

A fifth enemy, with 270 health or less.

These enemies are all capping the first point during overtime.
These enemies have all recently damaged the Medic healing you.

Then:

The Medic pops Kritz on you
You fire a crit rocket
The Sniper kills you
Your crocket kills all of your enemies, which wins your team the game.

As a result of this action you claim:

Your 1000th Soldier kill
500th Demoman kill
79th Balloonicorn-owner kill
30th point defense
20th kill while on fire
20th game win
10th top-3 score for MVP
5th revenge kill
1st domination on people wearing:

A Gibus
Pyrovison Goggles

1st time ever completing a full round on either one of Dustbowl/Gravel Pit (having now played full rounds on all of 2Fort, Dustbowl, Granary, Gravel Pit, Hydro, and cp_Well).

By doing this, you get the following achievements:

A Fresh Pair of Eyes
Backdraft Dodger
Costume Contest
Dynasty
Frags of our Fathers
Ghastly Gibus Grab
Hamburger Hill
Impenetrable Defense or Impossible Defense (depends on map)
Medals of Honor
Mutually Assured Destruction
Nemesis
Out, Damned Scot!
Semper Fry
*S*M*A*S*H*
The Great Deflate
Tri-Splatteral Damage
War Crime and Punishment
War Crime Spybunal
World Traveler
One (if not two!) of the Soldier milestone achivements

This gives you a total of 19+2.
Comment: Damn, 21, nice!  That's definitely way more than what I had.
Comment: The concept and bundling is majestic.
Comment: If you've previously killed a few people in the same life, and have never gone more than 4 kills without dying up that point, you could also fit in *Hard to Kill*.
Comment: On reflection, you could also fit in *Riftwalker*, by teleporting to the point, and *Hardcore*, I think, if you only ever played as Soldier, so that your 1000th kill as Solder is your 1000th overall.
Answer: I think I've found another one:
You are a Spy disguised as an enemy Spy backstabbing that same Spy who is

On your friends list
Has his revolver out
Is dominating 3 of your teammates
Is also disguised as a Spy
Is equipping the Balloonicorn and is your 79th Balloonicorn victim

You get Revenge on that Spy and get your 1000th stab on top of a Control Point that just became available because the other spy captured it while being healed by a medic and you being covered in Jarate and after having that enemy spy trigger your Dead Ringer and you exiting a teleporter and having 4 prior spy achievements, and this kill is your 5th kill in a row without dying, gives you:

Come in from the Cold (revenge)
High Value Target (stab someone with 3 dominations)
Spymaster (1000 stabs)
Agent Provacateur (stab 10 friends)
Identity Theft (stab the guy you are disguised as)
A Cut Above (kill a revolver-wielding spy with your knife)
Insurance Fraud (get a backstab while an enemy medic heals you)
Sleeps Agent (kill the guy that triggered your DR within 20 seconds)
On Her Majesty's Secret Surface (start capping a point as soon as it becomes available)
Counter Espionage (backstab a disguised spy)
Wetwork (kill someone while jarated)
Point Breaker
Milestone 1
Milestone 2
Milestone 3
Costume Contest (kill a spy disguised as your current class)
Nemesis (5 revenge kills)
Riftwalker (get a kill shortly after exiting a tele)
Hard to kill (5 kills in a row without dying)
Hardcore (get 1000 total kills)
The great deflate (kill 79 people with balloonicorns)

Total achievements from 1 stab: 21 achievements
Answer: Apparently 25 is possible as Sniper, courtesy of Reddit:
Setup
You must have exactly:

4 Sniper achievements
999 kills (all Sniper)
1 prior Domination
78 Balloonicorn kills
24 parachute headshots
9 Sniper headshots
4 prior Revenge kills

Equipment

Pyrovision goggles
The Machina
The Razorback

Action time!

Take a teleporter
Take a fully-charged shot
Your fully charged shot must kill all of the following:

A sniper,

Whom you've killed 3 times
Who is wearing

Pyrovision
A Balloonicorn

A Spy,

Who recently tried to backstab you
who is now cloaked

A second Spy who just uncloaked
A Demoman

Who is parachuting with the Base Jumper, following a sticky jump
With a headshot

A second Demoman

Who is charging towards you
Who is also dominating you

A Medic

With full Uber

A Scout

During a double-jump

A sentry gun

Taunt (well, who wouldn't after all that?)

Sniper-specific Achievements

Australian Rules
Be Efficient
De-sentry-lized
Dropped Dead
Flight Cancelled
Jumper Stumper
Kill Everyone You Meet
Not a Crazed Gunman, Dad
Parting Shot
Self-destruct Sequence
Shock Treatment
Shoot the Breeze
Socket to Him
The Last Wave
Triple Prey
Überectomy
Sniper Milestone 1

General achievements

Nemesis
Riftwalker
The Great Deflate
Hardcore
Hard to Kill
Emergency Brake
BFF²
A Fresh Pair of Eyes

Total: 25 achievements


Keyboard shortcuts for docking windows

Question: Windows has a feature that allows you to press Win+RightArrow and have the active window dock to the right side of the screen.  In Ubuntu I can click and drag the window to the right edge of the screen and it will do the same thing, but is there a way to set up keyboard shortcuts for this?
I am using Kubuntu 16.04.
Answer: If you open up "Global keyboard settings", there is a section there for "Kwin" - the kde window manager.
Find the setting for "Quick tile window to the right" or "left", and assign it a shortcut key by selecting it and pressing the button that says "None". For example, "Win-Alt-Left" for quick-tiling to the left. Press "Apply" and you can now use this shortcut.

Keyboard shortcuts for docking windows


How to Convert Byte Array to Char in C++

Question: I don't know how to write a code that convert a byte array to a char array in C++ (using an Arduino board) and publish mqtt. I tried to search but I don't understand.
Example
byte Code[3] = {0x00 ,0x01 , 0x83};
char byteTochar[3];

for (int i = 0; i <= 2; i++) {
    Serial.printf("%d", Code[i]);
    Serial.println();

    client.publish("publish/data", byteTochar[i]);
}

Error message
converting to 'String' form initializer list would use explicit constructor 'String::String'(unsigned char, unsigned char)'

Comment: This is not `C`, i guess.
Answer: Its actually do c, ArduinoPlayGround  http://playground.arduino.cc/Main/Printf.
However, you can just use casting for each element:
char h = (char)Code[i];

Comment: sorry i don't understand use byte h = (byte)Code[i]; for convert to char array ?
Comment: My bad, i changed it. do it for each of the array elements throug a loop and youll get an array of byte. Or you can just convert right before passing the argument.
Comment: Thank answer, i will to try :)
Comment: i try write code for apply data not work, console not show data message.

http://pastebin.com/VkbyYg3U
Comment: Please explain what exactly this code should do, cause you passed the wrong params to `itoa` and you didnt use the char, so i dont get what are you trying to do. However, try to initiate the buffer (str) and read this: http://www.cplusplus.com/reference/cstdlib/itoa/