What exactly is a "cheese" in Starcraft 2?

Question: I seem to see commentators mention "cheese" with regards to Starcraft 2, but I'm not quite sure what they mean.
If a particular build/tactic is called a "cheese", does that mean it is a considered to be uncounterable?   Or does it just mean that it is considered to be a tactic that is "too easy" with regard to its effectiveness?   Or is there some other more subtle meaning that I am missing?
Comment: Real life example: Australian short-track speed skater Steven Bradbury stayed at the back of the Olympic 1000 metres final, hoping at least two competitors fall over so he could get a medal. It turned out all four competitors fell over, thereby giving him gold.
Comment: possible duplicate of [What attributes identify a "cheese build" in SC2?](http://gaming.stackexchange.com/questions/1691/what-attributes-identify-a-cheese-build-in-sc2)
Comment: Another example: [Scholar's mate](http://en.wikipedia.org/wiki/Scholar%27s_mate)
Comment: I disagree that scholar's mate is cheese. white doesn't really risk anything by doing it, and black has to practically cooperate for it to work.
Comment: @Peter: Scholar's mate is absolutely a cheese.  White brings his queen out to be pushed around in the hopes of an easy early win - if it fails, black will develop a piece or two with gain of tempo by attacking white's queen, as well as have more space and full control of the center after the inevitable pawn-push `d5`.  Black comes out of the opening *way* ahead.  If you are still unsure, ask a new question on the [boardgame SE](http://boardgames.stackexchange.com); I'd be happy to go into more detail there.
Comment: Should have the terminology tag but I don't have enough rep.
Comment: @PeterRecore Cheese has nothing to do with risk factor.  It's just often a symptom of the tactic, but not a qualification.  It just so happens that almost 100% of cheese strats in sc2 meet this, but not so much in other games.  Just realized this is 5 years late but thats ok...
Answer: The term "Cheese" comes from the adjective "Cheesy". The not-so-subtle innuendo there is that a victory via so-called "cheese" did not come from the players own skill, but was merely because the loser was unprepared for the "cheesy" tactics that lead to their loss.
What qualifies as "cheese" will undoubtedly vary from player to player, but generally the term refers to exploiting system mechanics in a way unanticipated by your opponent, or otherwise not balanced around.
Many people dislike cheese because it is hard to predict and counter if you are not prepared for it.
Several Examples:

Thor Rush -- build a factory near your opponent, attack with Thor + repair SCV's around 7 minute mark.
Photon-Cannon Push -- rushing a forge and placing photon cannons around your opponents base.
Banshee / Void Ray rush vs. Zerg -- takes adavantage of the fact that Zerg has little viable anti-air at T1 other than mass queens.
Proxy Rush -- Building a unit production facility much closer to your opponents base than your own so that you can reinforce your troops faster.
Worker Rush -- in 2v2 (or more), making no units, and instead attacking another player with your workers alone.
Comment: These sound exactly like the tactics Ender Wiggin would've used.
Comment: Just to be clear: so basically it's name-calling used by players who fail to anticipate their opponents' moves?
Comment: @tzenes I think kamens was referring more to the scenes where Ender did things that would only work once (like freezing his entire squad and using them as cover).  The larger point being that in a "real" war, you do whatever it takes to win, and unexpected tactics (even those that only work once) are generally seen as a good thing.
Comment: @kamens I don't like that analogy.  Ender considered using his weapons in a previously unconsidered manner, I'd say this is similar to JulyZerg's reinventing the way zerg is played.  At first opponents were unprepared and considered his tactics "Cheesy." However, those tactics continued to be effective even after opponents were prepared for it.  Likewise, using the MD Device on a planet, while unconsidered at the time, is a sustainable strategy (similar to using nuclear weapons on cities).
Comment: @Konrad Rudolph, yes, exactly.
Comment: A cheese build works best against people who do not scout
Comment: @bwarner Using frozen squad members became a standard play in the battle academies.
Comment: I think of cheese as relying on the difference between the game's model and the "reality" the game is trying to model. Cheese exploits the artificiality of the situation.
Comment: @tzenes The strategy of using the MD against a planet was most certainly considered and the generals knew it was the only possible victory.  The problem was the mental attributes required to actually carry out such a genocide were incompatible with the attributes required to be a good general.  Thus for many years before that battle they were manipulating Ender so that when the time came he would blast what he thought was merely a game planet.
Comment: I did the worker's tactic once while playing with friends on a LAN. we all LOLED :)
Comment: @Ross A Thor Rush actually turns into a sustainable strategy (strangely enough).  You rush Thor's and pump out a drop ship to harass with.  It actually works out very well
Comment: I can't see worker rush seriously working, unless maybe in conjunction with double 6 pool zerg.
Comment: @tzenes While freezing soldiers became a common tactic what Ender pulled was a one-time-only tactic.  Had they realized he was not frozen it would have failed.
Comment: @Loren a cheese is not defined by success, only by if the techniques used to gain an advantage _could_ be sustainable. Whether or not the player choses to sustain them is irrelivent
Comment: @tzenes:  The just about everybody frozen tactic could only work once--it was based on his only pretending to be frozen.  The counter is easy, the same as soldiers do: shoot to make sure.
Answer: I would have to strongly argue against those who say that "cheese" is an exploit in the game.
A cheese strategy is usually an all-in strategy.
Reaper rushes, zergling rushes, roach spam, proxy gate rushes are something lots of people consider cheese strategies.
If a cheese strategy is countered, then the game is usually easily won.  Cheese builds in SC2 have very distinct openings and you should learn to scout them and be prepared.
In short, cheese does not work against competent opponents.  The only reason they work is because the opponent was not expecting it.  However, being a competent SC2 player means that you should always know what your opponent is doing.
Answer: It's more about taking advantage of a flaw in the system to get a cheap win. Kicking someone's butt with a reaper-rush, which takes advantage of the fact that the defensive buildings are weak, is cheap. You're not showing skill, you're just exploiting a weakness in the game.
Edit: Reaper rushing is a dated example now, since they've done a good job of making that unit balanced.
Comment: reapers are meant to be a harassing unit.  watch some pro games to see how to fend off a reaper rush.
Answer: While the first answer has some good points, most cheesy tactics are not "exploiting system mechanics." To call it that would imply it needs to be fixed.
The simplest definition of cheese is any tactic that is considered to require more luck than skill. The example of early proxy rush is a good one. The reason is, you can do proper scouting of the enemy base and the area around your base, but if the enemy got lucky and you just happen to miss his proxy either because your search path just missed his building, or missed him timing-wise (you search a place just moments before his worker gets there). Same goes for something like Void Ray rush. It's very early in the game and the player will try to build it off in a place where they don't expect you to scout. If you don't see that starport early enough, that first void ray may be enough to end the game for you.
Answer: Cheese involves an attacker employing high-risk, high-reward tactics in order to win. Such tactics are typically difficult to detect by the victim and often leave the attacker extremely vulnerable. Thus, if the victim is able to preemptively detect that their opponent will be using cheese, the victim is typically able to formulate a strong counterattack.
Cheese receives its negative connotation from those who believe that the cost of preemptively detecting cheese is too high. However, in the case of Starcraft 2, this cost is typically very minimal, usually requiring the use of 1-2 workers and chaining scouting commands.
Answer: My feeling about Cheese is that is just as legitimate as camping in other types of games, and irritates other players for much of the same reason.  I like Daryl's explanation that it incorporates luck more strongly than the more stable builds many players prefer, but I'd like to extend that it works principally by exploiting to maximum advantage the asymmetries between the opposing forces.
A particular feature of cheese is that it works well before the opponent is able to get a reasonable sized, balanced and stable army, because it exploits the compromises players have to make in the early part of their builds.  By mid-game, those weaknesses will be covered by the composition of the opponents army.
For this reason, you see cheese play mostly in non mirror matchups.  There are more chances for asymmetric advantages in a TvP, PvZ or ZvT matchup than in TvT, PvP, and ZvZ.  That said, there are still some interesting things that can happen in mirror matchups that would typically count as cheese.
As a particular example, I'll compare TvT where the defending player is using a 1/1/1 build.  A cheesy terran player might bank on the opponent making marines out of their barracks until the factory is up in order to defend against early aggression.  Unfortunately for the defender, marines aren't very good against reapers.  If the cheesing player arranges for a handful of reapers to arrive before any addons are down on a factory or barracks, it will be very hard for the defending player to hold it off.
On the other hand, the cheesing player could be very unlucky and the defending player got a tech lab on his barracks immediately.  A very small number of marauders can hold off many reapers because reapers do so little damage to armored units.
Answer: How about this:
A simplistic tactic designed to get an quick win that unreasonably demands the opponent to adopt very specific and unbalanced countermeasures to survive. Consequently, it is not usually very fun to play against (unless one is expecting it, perhaps)
Answer: A little bit of trivia:
The Korean term for a cheesy strategy is 'strategic play' (as versus standard play).
Answer: I would say cheese would be proxy anything, or cannon rush. 2 gate proxy in their base, 2 rax proxy, cannon rush, etc. These are all strats that dont take much micro nor macro, and are hard to defend against early game and don't really get scouted either.


Tornado packaged in an executable egg - how reference templates

Question: I've created a Tornado web server, which I need to package as an egg (using setuptools)
The project contains a number of html templates and static images, which I've included in my egg as data files. Note the egg is executable, and will not be installed.
I.e.
python mytornadoserver.egg

The standard way of accessing html templates / static resources is to use the template_path and static_path settings. However within an egg this is not going to work.
I'm trying to play with resource_strings - but no success so far.
I'm stuck at the moment, because I cannot load the html/image files - so I'd be grateful for any help / advice anybody can give
Many thanks,
Marcus
Answer: finally resolved the issue:
from pkg_resources import resource_filename
template_dir = resource_filename(__name__, "templates")

# then assign the template_dir to your template_path as normal....

the resource_files extracts the entire directory to a physical file location, and returns that location.
Comment: It doesn't work for me: resource_filename returns an url like `/usr/local/.../myprogram-egg-info/templates` but the problem is that `myprogram-egg-info` is an egg file instead of a directory. I think I need a way to force egg extraction before calling resource_filename (or, better, install the program in a directory instead of an egg file...)


Find an equation of a plane normal to a given vector

Question: I have to find an equation for a plane normal to the vector $\vec{r(t)} = \langle e^{t}sin(\frac{\pi t}{2}),e^{t}cos(\frac{\pi t}{2}),t^{2}\rangle$ when $t=1$. I know I have to find the derivative and then plug in the value for t such that $\vec{r'(1)}$, then use each coordinate of the point with this vector to determine an equation. But since I don't have a point I don't know how to proceed. What is the best way to tackle this?
Comment: I'm not sure what point you are looking for. The point $r(1) = (e,0,1)$ is on the plane.
Comment: You need to find the plane passing through $r(1)$ that is perpendicular to the vector $r'(1)$. I am guessing that you meant $r$, not $r'$ above?
Comment: oops. yes. sorry about that.
Comment: I am still not clear on how to find this since you simply restated the question. All of the examples in the book give a known point to start with. Thanks.
Answer: The equation is $r'(1) \centerdot ((x,y,z) - r(1)) = 0 $
Comment: I see. r(1) itself is the point. That makes sense now.


How to make rating stars for 2 different question in react?

Question: I am creating a react app to rating questions. And I have tried rating stars with png image and it is working fine for 1 question. But when I add another question with that rating stars it's not working.
This is what I tried

import React, { Component } from "react";

import fullStarSrc from "../img/highlightedStar.png";
import emptyStarSrc from "../img/star.png";

class joinPage extends Component {
  rate = (event) => {
    const { id } = event.target;

    console.log("clicked: " + id);
    var i;

    for (i = 1; i <= 5; i++) {
      if (i <= parseInt(id)) {
        document.getElementById(i).setAttribute("src", fullStarSrc);
      } else {
        document.getElementById(i).setAttribute("src", emptyStarSrc);
      }
    }
  };
  pro1 = (event) => {
    const { id } = event.target;

    console.log("clicked: " + id);
    var i;

    for (i = 1; i <= 5; i++) {
      if (i <= parseInt(id)) {
        document.getElementById(i).setAttribute("src", fullStarSrc);
      } else {
        document.getElementById(i).setAttribute("src", emptyStarSrc);
      }
    }
  };

  render() {
    return (

How would you rate our Service?

How would you rate the quality of food?

    );
  }
}

export default joinPage;

How can I fix this problem?
Comment: Seems like the basic react features are missing in your implementation. You should almost never do DOM manipulation in react. Please read [React Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html), [Rendering lists in React](https://reactjs.org/docs/lists-and-keys.html), [React JSX](https://reactjs.org/docs/jsx-in-depth.html)
Comment: @sidath I quickly created an example on how I'd do it. take a look if you want: https://codesandbox.io/s/rough-bird-cy4yy?file=/src/App.js
Comment: thank you so much. I appreciate your help.
Comment: I would strongly recommend refactoring your code into something like @Christian provided. You did get an answer, but I think this is showing you the _right_ way of doing it _wrong_.
Comment: yeah, it's true. but I need to use png to make the rating. I already fix my problem with the @Viet answer.
Comment: It shouldn't be hard to switch to use png in this example...
Comment: how can I do it? I'm new to react
Comment: Give me a sec, and I'll write an answer for this
Comment: @sidath Added an answer now
Answer: Refactored code to use React hooks and state instead of mutating state, also adding the rating to a new component.
see the sandbox for demo https://codesandbox.io/s/rough-bird-cy4yy?file=/src/App.js:0-851
import { useState, useEffect } from "react";
import unstar from "./star-unselected.png";
import star from "./star-selected.png";
import _ from "lodash";
import "./styles.css";

function RatingStars({ initRating, onRatingChanged }) {
  const [rating, setRating] = useState(initRating);

  useEffect(() => {
    // if prop changed, we want to reflect that.
    setRating(initRating);
  }, [initRating]);

  function changeRating(newRating) {
    setRating(newRating);
    onRatingChanged(newRating);
  }

  return (

      {_.times(5, (index) => (
        = index + 1 ? star : unstar}
          key={index}
          onClick={() => changeRating(index + 1)}
        />
      ))}{" "}
      has {rating} of 5 stars

  );
}

export default function App() {
  return (

      <RatingStars
        initRating={3}
        onRatingChanged={(newRating) => {
          console.log(
            `NEW RATING (${newRating}) DETECTED FOR 1.. SAVING TO DB`
          );
        }}
      />
      <RatingStars
        initRating={1}
        onRatingChanged={(newRating) => {
          console.log(
            `NEW RATING (${newRating}) DETECTED FOR 2.. SAVING TO DB`
          );
        }}
      />

  );
}

Comment: In this case how we track each and every single rating star? That means when I rate the first one by 3 stars and the second one with 4 stars how can I save these things into the database?
Comment: You can add a function prop to the ratingStars for getting updates for it, I can modify the sandbox to reflect this
Comment: Could you please modify the code? It's really help me lot
Comment: Take a look at the sandbox demo now
Comment: That's a great job. Thank you so much for your help.
Comment: Do you know how to swipe between pages in react? that means when I visit the web page with mobile and I swipe to left it redirects to another page.
Comment: I'd look into this question https://stackoverflow.com/a/40475633/3010171 It addresses swiping..
Comment: ok, thank you so much, Christian Moen.  I'll check it. I really appreciate your help.
Answer: because it has the same id. You just update id in the second rate is

and update pro1:
pro1 = (event) => {
    const { id } = event.target;

    console.log("clicked: " + id);
    var i;

    for (i = 6; i <= 10; i++) {
      if (i <= parseInt(id)) {
        document.getElementById(i).setAttribute("src", fullStarSrc);
      } else {
        document.getElementById(i).setAttribute("src", emptyStarSrc);
      }
    }
  };

Comment: hey Viet, do you know how to swipe between pages in react? that means when I visit the web page with mobile and I swipe to left it redirects to another page.


How can I ensure precise alignment of wooden parts assembled with bolts?

Question: I am building a CNC machine (don't need to know what that is), and I have chosen wood to be what I make the frame out of. One problem that I am facing is joining the pieces together. It may seem like a simple solution (a few nails or screws) but for this project it might have to be completely disassembled for modifications/expanding it/maintenance/cleaning/storage/etc.
I don't want to ruin the wood in the process with plain screws, since it will be a normal storage procedure to disassemble parts of it when not in use. (I have a very small apartment and space is limited for storage.) I've decided to use bolts to fix this problem. However, bolts you have to drill a hole, and I would think that it would be rare that there is zero wiggle room for the bolt to move around in the hole. When assembling/disassembling often, this can be a problem with alignment, especially since a CNC machine should have the greatest accuracy possible within your budget.
Is there some sort of thing where I can put like a "long nut" all the way through the board so it will easily be removed, yet won't wiggle (noticeably)? What methods do I have?
Answer: Specialty Bolts

Some bolts have long smooth shanks and short threaded sections.  If you are able to find appropriately sized bolts like these, and able to buy a drill bit that is the same diameter as the shank for a sung fit, then this is simplest, if not the best, solution.  The key is a smooth shank of appropriate length.  If the threaded section is too long, it can, of course, be cut off with a hack saw and groomed with a file.  To straighten out threads at the tip, spin a nut all the up to the shank and leave it on until finished with the grooming.

Joinery

The craftsman approach would be to use shouldered joints.  This is a link to the wikipedia page.

Pins

Solid Pins

assemble with bolts
choose a nail size (diameter) and similarly sized drill bit for a snug (but not too tight) fit.  The match between the nail and the holes needs to be snug enough for good alignment, but not so tight as to prevent the joint from being disassembled by hand and the nails tapped out if so desired.
cut nails to length if necessary
drill two or more holes through one member and into the second member
tap the nails into their holes
Note: see @bib's answer for a "blind" variant of this

Tube Pins

choose the bolts
choose metal tubing through which the bolts easily fit.   Note: as suggested by @AnonomousPerson in a comment, PVC tubing such as 1/2" plumbing can be used with good results for large bolts
in both members, drill through-holes in which the tubing fits snugly
cut lengths of tubing matching the members combined thicknesses
tap in a section of tubing
bolt together through the tubes

Splines

Blind Rings

select 1/16" walled metal tubing whose diameter that is somewhat smaller than the narrowest member. For example, if the narrowest member is 2" wide, then select some tubing that is about 1.5" in diameter.
select a hole saw that matches the size of the tubing
temporarily assemble the members using bolts that match the diameter of hole saw's drill bit, typically 1/4".
disassemble
on each of the mating surfaces, using the bolts holes for guides, use the hole saw to drill 1/4" deep circular recesses
cut 1/2" long rings from the tubing
assemble with the rings sandwiched in between
if larger bolts are desired, re-drill the bolt holes

Blind Flats

same idea as blind rings but use 1/2" x 1/16" metal stock and saw-kerfs
Comment: @AnnonomusPerson -  for precise alignment, I'd choose a drill bit that would create a snug hole for the tubing. You might also want to take a look at the new methods that I added.
Comment: Thanks! Number two looks like it will work for me. I think that I will try to glue/fasten the tube on one end so it doesn't slide or fall out when not completely assembled.
Comment: Joinery might also help on some joints to make it easier to assemble in some spots too. Also, PVC seems easier to cut than metal, and has a cleaner cut. That part will be covered through (maybe some washers?). I know it wouldn't look pretty or anything but it is more for function than look.
Comment: @AnnonomusPerson - Good point on the PVC for large bolts. Tubing cutters make quick work, or the heavier pipe cutters.
Answer: Mikes answers all have merit. You might also consider using alignment pins.

On one surface of the pieces that will mate, drive in two or more finish nails, leaving about 1/4 inch protruding.
Clip off the head of the nails.
Align the pieces and clamp down with bolts, driving the protruding nails into the mating piece.
When disassembling, wiggle the pieces slightly to disengage.
When reassembling, align the pins with the holes before bolting.

This approach is not as versatile as those offered by Mike if constant assembly and disassembly is contemplated.  But if it is only occasional, this might do.
Answer: Bolting it together will make it easier to disassemble, definitely.
You might also consider adding metal to the wear surfaces. This starts with washers over both the bolt head and the nut. This reduces the amount the bolts will draw into the wood over time.
You could face the mating surfaces with metal, e.g., permanently screwing a metal surface into the groove of your rabbet to mate with another metal surface screwed to the other piece of wood. Since these screws won't be disassembled, they shouldn't shift.
One easy way to do this is with hinges; then you can pop the hinge pins for disassembly. You'll need to find hinges with minimal slop, however.
Comment: 1+ for hinges. Sounds like a good idea for some parts, however, it probably won't work for every joint.


When is convolution associative?

Question: Convolution is associative on e.g. integrable function on $\mathbb{R},$ but not on distributions.
What about the convolution of measures on an unimodular group $G$?
Answer: Convolution of finite Borel measures on a topological group is always well-defined and associative.
Comment: Thanks.Where is it written?
Answer: Not sure if it's the most general case but according to Kallenberg's Foundations of Modern Probability, convolution of measures (I suspect the measures need to be at least $\sigma$-finite here, it's not specified but the proof states that you should use Fubini's) on a measurable group (group endowed with a $\sigma$-algebra such that the group operations are measurable) is associative, so it's a bit more general than the answer above.
Comment: Thank you very much for the reference

When is convolution associative?


Firewall on existing building

Question: We are required to create a firewall on our building that is less than 5' from the property line. We removed a window and now need to know if we can just leave the old header and framing and insert studs at 16" centers within the old window opening. Can anyone offer insight into this?
thank you.
Answer: Absolutely, that is common practice. Not much insight required, sounds like you got this.
Comment: Thank you, I was just concerned they might cause a stink but this is good news
Comment: +1; but just make sure the wood is solid. So often it isn't!
Answer: Setbacks from property lines are based on the buildings "occupancy", (i.e.: residential, commercial, institutional, etc.) (IBC Table 601) AND what it is made out of, (i.e.: concrete, wood, etc.) (IBC Table 602.) When a building of a certain occupancy encroaches into this required setback, the exterior wall must be constructed a certain way...we call this a "firewall".
There are many kinds of "fire walls" and they are constructed in many ways. Most need to "protect" openings (i.e.: windows, doors, vents, electrical outlet boxes, etc.) based on the setback and type of construction. In addition, most firewalls need to extend a minimum of 30" above the roof...although that can be eliminated by installing gypsum board on top of the roof sheathing and on the bottom of the roof structure, (i.e.: roof trusses, roof joists, etc.)
You say your "Building" is within 5' of the property line. (You didn't say residence.) So, in order to answer your question about framing, I really need to know the type of occupancy.
In any event, just removing windows and infilling with framing, siding, etc. is NOT acceptable for ANY type of firewall. In wood frame construction, the minimum requirement for a firewall is one layer of gypsum board is required on the exterior (under the siding) and one layer of Type-X gypsum board is required on the inside.
I would check with your local Building Official to get a clarification of the type of firewall required and exactly how it should be constructed. All firewalls are designed and tested to meet U.L. Standards (or Warnock Hersey Standards) AND they must be constructed to match those specifications, (i.e.: thickness of material, nailing patterns, framing dimensions, framing spacing, etc.)
(Btw, you know there is no firewall required on the "front" of your building. Firewalls are for the sides and rear of buildings ONLY.)
Comment: This is a detached garage being converted into a business. The wall in question is a side wall close to the property line. We are aware of the fire wall requirements but specifically I had questions regarding the framing - we removed a window and I wanted to know if they were particular about how that was handled. i.e. - would we have to remove existing framing from window or could we just insert studs within the existing opening and then proceed with the required fire proofing .. I hope this helps.
Comment: Yes, you can "infill" an opening with framing that matches the "fire rating" of the rest of the wall, (i.e.: same size and spacing of other framing members).

Firewall on existing building


Settings in application.yml for spring.cloud.config aren't used when app is executing

Question: I have a problem with spring cloud: my settings in application.yml for spring.cloud.config aren't used when app is executing. let me put more detail here.
I'd like to my services could get settings from a remote ConfigServer. I've created the ConfigServer as a spring boot app with annotation @EnableConfigServer.
After that i've created client app with next config file:
    application:
      name: mw
    cloud:
      config:
        enabled: true
        uri: http://172.17.42.1:8888
        fail-fast: true

main class:
    @EnableEurekaClient
    @SpringBootApplication
    public class MwApplication

and extra configuration into app:
    @Configuration
    @EnableJpaRepositories(basePackages = {"com.sample.repository"})
    @EnableTransactionManagement
    @EnableScheduling
    public class AppConfiguration

also i have next dependencies:
    spring-cloud-starter-eureka
    spring-cloud-config-client
    spring-boot-configuration-processor
    spring-boot-starter-data-jpa

When i execute my client app, i've got this message: ConfigServicePropertySourceLocator : Could not locate PropertySource: I/O error on GET request for "http://localhost:8888/mw/default"
The app try to get data from default uri(localhost) instead of to use uri from my setting. I've looked at app in debug mode and saw org.springframework.cloud.config.client.ConfigServiceBootstrapConfiguration was creating ConfigClientProperties with default property and my settings from application.yml weren't used.
What am i doing wrong?
thanks.
Answer: You need to add the following to your application.yml file:
spring:
    cloud:
        config:
            enabled: true

Per comment chain, you also need to add the properties to bootstrap.yml instead of application.yml . The reason is that the former is loaded before the latter in the spring startup cycle. Here is another SO post answered by user Michael Isvy explaining why, and copied below for posterity: What is the diference between putting a property on application.yml or bootstrap.yml in spring boot?

I have just asked the Spring Cloud guys and thought I should share the info I have here.
bootstrap.yml is loaded before application.yml.
It is typically used for the following:

when using Spring Cloud Config Server, you should specify spring.application.name and spring.cloud.config.server.git.uri inside bootstrap.yml
some encryption/decryption information

Technically, bootstrap.yml is loaded by a parent Spring ApplicationContext. That parent ApplicationContext is loaded before the one that uses application.yml.
Comment: i've already tried it and added again, but nothing is changed, i've still had this problem
Comment: try moving the application.yml configuration to bootstrap.yml
Comment: Bootstrap.yml is loaded before application.yml . Here is another SO answer that is actually provided by someone who asked the Spring Cloud creators: http://stackoverflow.com/questions/32997352/what-is-the-diference-between-putting-a-property-on-application-yml-or-bootstrap
Comment: No problem. Since my answer worked for you, would you mind accepting it?
Comment: now it works, thank you! Could you say why it didn't work with application.yml?
i didn't create  application.yml by myself. it was created by spring constructor
Comment: @slippery So you are saying your application worked when you moved the app.yml configs to bootstrap.yml? I did the same but my application does not run.


Ruby Error: "no implicit conversion of Fixnum into String"

Question: I'm a beginner with Ruby, practicing looping and if statements.
I went a little off track with my course work, and tried to run the following code:
puts("Enter your age!")
age = gets.to_i
again = "Try again!"

while age <= 100

if age == 0
  puts("You are very very young. " + again)
  age = gets.to_i

elsif age >= 1 && age <= 5
  puts("You are quite small. Though you are breathing, you may not    understand this. " + again)
  age = gets.to_i
else
  puts("You are a capable of reading " + again)
  age = gets.to_i
end
end
puts("Your age," + age + " is a good one")

When I run it, I am prompted to enter an age.
If the age I enter <= 100 everything works according to the code.
If not, I get the error:

rehearsal.rb:20:in +': no implicit conversion of Fixnum into String
  (TypeError) from rehearsal.rb:20:in'

Other StackOverflow answers (solving this error message) I read suggested that the error was in misusing the "to_i" method. I made sure to include it, and my error is still here.
Where is my bug?
Answer: In Ruby, the + method for adding strings doesn't work on integers. In your example, the age variable is an integer. This might seem a little strange if you are used to working with JavaScript.
You need to use string interpolation
puts("Your age, #{age} is a good one")

This works.
Comment: It worked, with an added quotation mark at the end of the line. Thanks again!


Water not reaching the overhead tank from mains pipe- flow ground to top to the overhead tank

Question: The water flows from underground pipe when the water in main pipe is released to 1st floor of the building but not to the overhead tank which is on 5th floor.
The pressure seems to be not building up for the overhead tank - seen in the meter fitting on the pipe, but for the 1st floor it seems to be fine. What could be the reason?
Answer: Water pressure at the ground level is the issue here as your pipes go up you lose pressure at .445 pounds per foot 5 stories up ~50' your pressure would be ~22 psi less this may not be enough pressure to open the valve to the tank. If you are on a well you can increase the cut out pressure on your pump. If on a city water system contact them about the low pressure. Other than that a booster pump to increase pressure may be needed to provide enough pressure for the tank to fill.


Using Terraform attache the existing disk to the Windows VM

Question: After command the terraform init and terraform plan
The error message said

Error: Unsupported block type
on main.tf line 96, in resource "azurerm_windows_virtual_machine" "main":
96:   storage_os_disk {
Blocks of type "storage_os_disk" are not expected here.

prodivers.tf:
<code>terraform {
  required_version = ">=1.0"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>3.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~>3.0"
    }
  }
}

provider "azurerm" {
  features {}
}
</code>
main.tf :
<code># Create virtual network
resource "azurerm_virtual_network" "my_terraform_network" {
  name                = "${random_pet.prefix.id}-vnet"
  address_space       = ["10.0.0.0/16"]
  location            = "East Us"
  resource_group_name = "vm-terraform-demo"
}

# Create subnet
resource "azurerm_subnet" "my_terraform_subnet" {
  name                 = "${random_pet.prefix.id}-subnet"
  resource_group_name  = "vm-terraform-demo"
  virtual_network_name = azurerm_virtual_network.my_terraform_network.name
  address_prefixes     = ["10.0.1.0/24"]
}

# Create public IPs
resource "azurerm_public_ip" "my_terraform_public_ip" {
  name                = "${random_pet.prefix.id}-public-ip"
  location            = "East Us"
  resource_group_name = "vm-terraform-demo"
  allocation_method   = "Dynamic"
}

# Create Network Security Group and rules
resource "azurerm_network_security_group" "my_terraform_nsg" {
  name                = "${random_pet.prefix.id}-nsg"
  location            = "East Us"
  resource_group_name = "vm-terraform-demo"

  security_rule {
    name                       = "RDP"
    priority                   = 1000
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "*"
    source_port_range          = "*"
    destination_port_range     = "3389"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
  security_rule {
    name                       = "web"
    priority                   = 1001
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "80"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
}

# Create network interface
resource "azurerm_network_interface" "my_terraform_nic" {
  name                = "${random_pet.prefix.id}-nic"
  location            = "East Us"
  resource_group_name = "vm-terraform-demo"

  ip_configuration {
    name                          = "my_nic_configuration"
    subnet_id                     = azurerm_subnet.my_terraform_subnet.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.my_terraform_public_ip.id
  }
}

# Connect the security group to the network interface
resource "azurerm_network_interface_security_group_association" "example" {
  network_interface_id      = azurerm_network_interface.my_terraform_nic.id
  network_security_group_id = azurerm_network_security_group.my_terraform_nsg.id
}

# Create storage account for boot diagnostics
resource "azurerm_storage_account" "my_storage_account" {
  name                     = "diag${random_id.random_id.hex}"
  location                 = "East Us"
  resource_group_name      = "vm-terraform-demo"
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

# Create virtual machine
resource "azurerm_windows_virtual_machine" "main" {
  name                  = "${var.prefix}-vm"
  admin_username        = "azureuser"
  admin_password        = random_password.password.result
  location              = "East Us"
  resource_group_name   = "vm-terraform-demo"
  network_interface_ids = [azurerm_network_interface.my_terraform_nic.id]
  size                  = "Standard_DS1_v2"

  storage_os_disk {
      name            = azurerm_managed_disk.test2.name
      managed_disk_id = azurerm_managed_disk.test2.id
      caching        = "ReadWrite"
      create_option   = "Attach"
      lun             = 1
      disk_size_gb    = azurerm_managed_disk.test2.disk_size_gb
    }

  source_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2022-datacenter-azure-edition"
    version   = "latest"
  }

  boot_diagnostics {
    storage_account_uri = azurerm_storage_account.my_storage_account.primary_blob_endpoint
  }
}

resource "azurerm_managed_disk" "test2" {
  name                 = "demo-disk1"
  location             = "East US"
  resource_group_name  = "vm-terraform-demo"
  storage_account_type = "Premium_LRS"
  create_option        = "Copy"
  disk_size_gb         = "4"
}

# Install IIS web server to the virtual machine
resource "azurerm_virtual_machine_extension" "web_server_install" {
  name                       = "${random_pet.prefix.id}-wsi"
  virtual_machine_id         = azurerm_windows_virtual_machine.main.id
  publisher                  = "Microsoft.Compute"
  type                       = "CustomScriptExtension"
  type_handler_version       = "1.8"
  auto_upgrade_minor_version = true

  settings = <<SETTINGS
    {
      "commandToExecute": "powershell -ExecutionPolicy Unrestricted Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature -IncludeManagementTools"
    }
  SETTINGS
}

# Generate random text for a unique storage account name
resource "random_id" "random_id" {
  keepers = {
    # Generate a new ID only when a new resource group is defined
    resource_group = "vm-terraform-demo"
  }

  byte_length = 8
}

resource "random_password" "password" {
  length      = 20
  min_lower   = 1
  min_upper   = 1
  min_numeric = 1
  min_special = 1
  special     = true
}

resource "random_pet" "prefix" {
  prefix = var.prefix
  length = 1
}
</code>
I expect the existing disk can attach to the new VM.
Comment: I can only see an `os_disk` block and not `storage_os_disk` in the documentation.
Answer: can you please try creating azurerm_virtual_machine as resource (not azurerm_windows_virtual_machine)?
according with azurerm_windows_virtual_machine azurerm_windows_virtual_machine doesn't support storage_os_disk (as @marko-e suggested as well).
Comment: Thanks, but how can I add the existing disk attached to the Windows VM?
Comment: Hi Michael,
you should be able to attach an existing disk leveraging the [azurerm_virtual_machine_data_disk_attachment](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/virtual_machine_data_disk_attachment) TF resource.
Please, follow the example in that page and let me know if you find any issue.


A CSS table in one of parallel divs

Question: On a webpage I have a container div and inside it two divs next to each other. In the first inner div I am trying to set up a CSS table that has 4 columns that evenly fill the div.
The problem I am having is that the cells seem to get their width relative to the page's width, not the table/it's parent div. If I decrease the width from 25% to something lower, it will fit, but if I scale the page, they will still wrap, as the div on the right hits the rightmost table cell.
How should I setup the layout to keep them inside the div?

Cell1

Cell2

Cell3

Cell4

Answer: Remove
float: left;

from
.table-cell

Comment: That fixed the problem, however it broke the height of my columns (in a bigger page not pasted to this question). Can you answer this follow-up question?
Comment: Please, give me the whole HTML/CSS.
Comment: I created anoteher question, which I thought I linked to my comment. Seems I did't... Anyway I already got an answer on [that one](http://stackoverflow.com/questions/17777281/css-table-height-of-rows-not-even/17777938?noredirect=1#17777938)

A CSS table in one of parallel divs


How do I reset my keyboard layout?

Question: How can I reset my keyboard layout after modifying it with xkbcomp?
Is there a way to do this without restarting X?
Answer: Try:
setxkbmap us

(Replacing us with the keyboard layout you want). If using a variant (e.g. intl), try
setxkbmap -layout us -variant intl

Here's a list of keyboard layouts.
Comment: I created this list from the contents of /usr/share/X11/xkb/rules/xorg.lst: http://pastebin.com/v2vCPHjs
For USA International, do `setxkbmap us -variant intl`. (Only one dash!)
Comment: Where can I get a list of the names of the keyboard layouts? For example, how do I find out what to use for USA International?
Comment: this answer gives temporarily solution, after reboot system, possible switches would be default session
Comment: Could you please add the pastebin link or a `file:///usr/share/X11/xkb/rules/xorg.lst` link to your answer to improve readability?
Comment: This also works if you run synergy and you have a modifier key, e.g. the shift key, apparently stuck down.
Comment: is there any permanent solution to persist this changes, because it seems like after reboot it goes back to original state..
Comment: This is not a real reset command
Comment: Isn't the same list of keyboard layouts as in `man xkeyboard-config`?
Answer: Check current layout and options:
setxkbmap -print -verbose 10

Reset layout to US and reset options:
setxkbmap -layout us -option

(Without the empty -option parameter, no options would be reset.)
Use the first command to check the result.
Answer: Use setxkbmap -layout us. It looks to completely reset the changes

How do I reset my keyboard layout?


Detect if the mouse cursor is hidden or visible by any other application

Question: I want to detect if the mouse is currently hidden, something that is often done by 3D applications on Windows. This appears to be trickier than it sounds as I can't find any way to do this.
Preferably I want to do this using Python but if that's not possible I could resort to C. Thanks!
Answer: You'll need to call the GetCursorInfo function.  This can be done straightforwardly using the pywin32 library.  Or, if you'd rather not install external Python libraries, you can use the ctypes module to directly access the function from User32.dll.
Example:
import ctypes

# Argument structures
class POINT(ctypes.Structure):
    _fields_ = [('x', ctypes.c_int),
                ('y', ctypes.c_int)]

class CURSORINFO(ctypes.Structure):
    _fields_ = [('cbSize', ctypes.c_uint),
                ('flags', ctypes.c_uint),
                ('hCursor', ctypes.c_void_p),
                ('ptScreenPos', POINT)]

# Load function from user32.dll and set argument types
GetCursorInfo = ctypes.windll.user32.GetCursorInfo
GetCursorInfo.argtypes = [ctypes.POINTER(CURSORINFO)]

# Initialize the output structure
info = CURSORINFO()
info.cbSize = ctypes.sizeof(info)

# Call it
if GetCursorInfo(ctypes.byref(info)):
    if info.flags & 0x00000001:
        pass  # The cursor is showing
else:
    pass  # Error occurred (invalid structure size?)

Answer: The GetCursorInfo function returns a CURSORINFO structure that has a flags field that contains the global cursor state. Would this do what you need? I'm not familiar with Python so I don't know if you can call this function from Python.
Comment: Thank you, that worked excellent and is callable from python. http://docs.activestate.com/activepython/2.5/pywin32/win32gui__GetCursorInfo_meth.html


I have some question about absolute value (how convert it in another form correctly)?

Question: Hi maths people I write next week a test in linear algebra and I have question because when asked in test I want do it good.
We have for example $|x^2-1| + |x^2-1|$.
How can I write it in another way? Is this correct? $|2(x^2-1)|$ or is this correct $2(|x^2-1|)$. I think first is correct because from beginning we have all inside absolute value sign and so it must all be in absolute value sign after. But no sure..
What when we have multiplication instead of addition? $$|x^2-1| \cdot |x^2-1| = |(x^2-1)^2| \text{ ?}$$
Please need help I have no idea what is good and what not..
Answer: it is $$|x^2-1|+|x^2-1|=2|x^2-1|$$ like $$a+a=2a$$
Comment: this is right: $$|x^2-1|\cdot |x^2-1|=|x^2-1|^2=|(x^2-1)^2|=(x^2-1)^2$$
Comment: introducing new variables like $a=\vert x^2-1\vert$ is usually a good idea ;)
Comment: no you must add these terms like two of same variables
Comment: thank you how you make multiply? I think then the $^2$ must be outside also?
Comment: $$|x^2-1| \cdot |x^2-1| = |(x^2-1)^2| \text{ ?}$$
Comment: thank you very much i understand and i do it nice in exam!!!!
Comment: i wish you all the best for your exam!
Answer: The expressions
$$
|2(x^2-1)|
$$
and
$$
2(|x^2-1|)
$$
are completely equivalent and it's just a matter of taste which one to use; the latter is usually written $2|x^2-1|$, because the bars of the absolute value work as brackets.
What about $|x^2-1|\cdot|x^2-1|$? Well, both
$$
|x^2-1|^2
$$
and
$$
(x^2-1)^2
$$
are good, because of $(-a)^2=a^2$. Note that the even exponent is important: you're not allowed to write
$$
|x^2-1|\cdot|x^2-1|\cdot|x^2-1|=
(x^2-1)^3
$$
because in general $(-a)^3\ne a^3$.
Answer: Hint.-See about the function $f(x)=\sqrt{x^2}$. You know that
$$f(x)+f(x)=2\sqrt{x^2}\space \space \text{ and }\space \space  f(x)\cdot f(x)=x^2$$
Compare now $f(x)$ with $g(x)$. Are both functions the same? Look at the graph of both functions.


What does the is_sparse mean in StreamDef?

Question: I'm new to CNTK and quite confused about the is_sparse argument in StreamDef. Does it mean the input file has to be in some specific format?
Answer: Yes, it means that the corresponding field in the CTF file is expected to be formatted as zero or more feature_index:feature_value pairs.
Comment: What does `be formatted as zero` mean?  I haven't come across such examples.
Comment: For example you can have |name feature: value |other_name feature: value |one_more_name |last_name feature: value. This example has all features equal to zero for one_more_name.


Infestation Containment

Question: I ran into my first infestation last night. Now all but two of my colonists are downed. Those two are hiding in their bedrooms as everyone else bleeds out. This has raised a few questions about my new visitors that I haven't been able to find the answers to.
It sounds like if I had left them closed up in the storage room they appeared in, they would have left me alone. But now that they're out, can the be re-contained? They are currently closed out of the room with the hives. Will they attack the walls or door to get back in there? If I open it up for them, will they go back in? If they do, can I shut them in, or are they "triggered" now (break out to attack me some more)?
They have already attacked the windmill and solar cells that they could get to without opening doors. Will they attack other things? Will they break down doors or walls to get to stuff?
I understand they sleep at some point. Do they follow the usual day/night cycle? Is it safe to try rescuing people at that point?
Answer:
Bugs will actively try to attack you if you get too close. Even if
there's a wall in between they sometimes will try tunneling towards
you.
If you attack the hives they will try to get back to the hives to defend them.
Yes, they might at some point try to attack more things, although if it's far away from them they might just be content to wonder around.
Yes they sleep, usually during the regular day night cycle. It's safe to approach them and rescue colonists, as long as you don't walk into a tile next to them.

It's also safe to build a wall around them, fill the space they are
inside with wooden floors and wooden chairs, add a few incendiary traps
and then watch the chaos unfold once they wake up.
Be careful though, bugs will tunnel trough two doors to get away from fire before the succumb to the heat, make sure there's lots of layers so they can't get away once the fire start.
Comment: I would like to emphasize that a furnace room (lots of wooden things and floors plus incendiary/molotov) is the safest way to deal with them, but be careful that the fire doesn't get out of hand or catch your base on fire too. I've lost a couple of good colonists when they started trying to fight fire and bugs at once.
Comment: Note that as more bugs emerge, they wander in a bigger radius around their nest (so as to keep bug density fairly equalised). When they wandering takes them through a wall, they will attempt to burrow through it. This means that infestations can really get out of hand in the long run.

Infestation Containment


How to save a dictionary and a list in the same json file with python?

Question: I wish to save a dictionary and a list in one json file so that when I parse the file I could distinguish them.
This is the function I use to save the dictionary in the json file:
def save_callback():
    #folder = filedialog.askdirectory()
    file = filedialog.asksaveasfilename()
    with open(file,'w') as file:
        file.write(json.dumps(test_dict))
    os.rename(file.name,file.name + ".txt")

What should I add to this function to save the list too?
Answer: Since JSON objects can be arbitrarily nested, the easiest solution is to store both the dict and the list inside another object:
data = json.dumps([test_dict, test_list])

Then you can load it like this:
test_dict, test_list = json.loads(data)

Comment: @evgeny You're not giving it the data, you give it a file. If you wish to give a file, use `json.load(file)`. (Notice the lack of `s` denoting a string).
Comment: The first part worked but the load  returns an error: TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper


Authentication failed - OWIN - OAuth - Webapi 2.0

Question: I have created a WebAPI 2.0 service and a Windows Forms client. I can create a valid token request by the client.
But when I try to use that bearer token for accessing the WebAPI I get the following error:
Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware Error: 0 : Authentication failed
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey, KeyId: 'djaskjd', InternalId: 'djaskjd'. , KeyId: djaskjd
'.
Number of keys in TokenValidationParameters: '16'.
Number of keys in Configuration: '0'.
Matched key was in 'TokenValidationParameters'.
Server Validation:
<code>     public partial class Startup
        {
            public void Configuration(IAppBuilder app)
            {

                ConfigureAuth(app);
            }

            private void ConfigureAuth(IAppBuilder app)
            {
              public void Configuration(IAppBuilder app)
              {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = ConfigurationManager.AppSettings["Audience"],
                Tenant = ConfigurationManager.AppSettings["Tenant"],
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidIssuers = new[] { "https://login.microsoftonline.com/{ConfigurationManager.AppSettings[\"Tenant\"]}/v2.0" }
                }
            });
        }            }
        }
</code>
Client Authentication
<code> private static void GetAuth()
        {

            autth = PublicClientApplicationBuilder.Create(ClientId)
                    .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                    .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                    .Build();
        }
</code>
How can I solve the problem?
Comment: Please put your token [here](https://jwt.io) and check out the signature is alright first. Looks like it's invalid token that was signed by invalid key that the authority can't validate. Maybe you should check if there is any typo in the token when you use it.
Comment: Hi hina10531, I already checked the token. The token itself is correct. The signature can't be decrypted because it is encrypted by HS256. It that is maybe the same error that I get from the service. I can see that the key is downloaded by owin. But it is not used.
Answer: The client code was correct. Just the scopes was not correct. You have to use the API of the client that references the server / backend.


Animate scroll to hash inside div not working

Question: Why is this working only when the scrolling is of the page itself but not within a div? I does move to the right location only without the animation.
<code>$(document).ready(function(){

  $('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
      'scrollTop': $target.offset().top
    }, 5000, function () {
      window.location.hash = target;
    });
  });
});
</code>
http://codepen.io/ilyador/pen/OPpWKd
Answer: change the animate to the wrap class like this update of your pen
>> codePen  <<
 changed to
<code> $('.wrap').stop().animate({
</code>


Rearrange values in CSV file

Question: I am trying to read a CSV file like the one below and create a new CSV file by presenting the information differently. The focus would be the fruits and a list of users that consumed each fruit.
Fruit, Name, Status

Apple, John, eaten

Apple, Chris, eaten

Apple, Mike, not eaten

Pineapple, Laura, eaten

Pear, John, not eaten

Pear, Laura, eaten

Expected result should be a CSV file like this:
Fruit, Names

Apple, John; Chris; Mike

Pineapple, Laura

Pear, John; Laura

I am reading the CSV file and storing the information in a dictionary where the values are a list. I just can't bring all the names into the same Names field for each fruit. they are either replaced by the last fruit for all rows or all rows have all names. the result should be another CSV file. thank you
Comment: Please add your code to the question, and specify what exactly the problem is (i.e. any error messages or output that is different from what you expect)
Answer: While asking questions please do provide code snippets or anything that you have tried, as that is better approach for learning and more people will be willing to help you out. Please do keep this in mind and for now you can refer to the following
snippet to help yourself out.
Make sure you set up attributes like delimeter correctly or you might get unwanted result else modify the given script accordingly.
import csv
from collections import defaultdict

input_file = r"C:\Users\kartikey.s\Desktop\input.csv"
output_file = r"C:\Users\kartikey.s\Desktop\output.csv"

fruit_data = defaultdict(list)

with open(input_file, 'r', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        fruit = row[0]
        name = row[1]
        status = row[2]
        if status == 'eaten':
            fruit_data[fruit].append(name)

with open(output_file, 'w', newline='') as csvfile:
    fieldnames = ['Fruit', 'Names']
    writer = csv.writer(csvfile)
    writer.writerow(fieldnames)

    for fruit, names in fruit_data.items():
        writer.writerow({fruit,'; '.join(names)})

Rearrange values in CSV file


Can you buy multiple shares at once?

Question: If you have a lot of money and you want to buy all the ammo that you can you can just press square(ps3) when buying ammo, so you will buy all the ammo that you can carry for that gun.
But is there any way to do something like that with shares? If i have 2 millions and i want to spend it all in shares is there an faster way to do it other than just keep pressing X?
Answer: I've searched high and low for a faster way, as I repeatedly invested in the stock market post-game to build up my characters net worth into the billions.
However, the only way I'm aware of is to hold the button down while your cursor is over the "+" icon.  As you hold, the counter will accelerate.  It still takes a good 20-30 seconds to max out your shares bought if you're buying a cheap stock and you have a ton of cash, though.
Comment: you can hold it? i didn't know that, at least it's a bit faster while holding it
Comment: @LuccaDornelles, yes, you can hold it down on the plus icon, and it is super fast compared to tapping it.  Still slow, but man, I would not want to buy individual shares at the billions I was investing at a time :)
Comment: Thanks. Every time I would hold the button down, I'd let go evidently just before it started going real fast. I'd see it not doing anything, and let go.

Can you buy multiple shares at once?


Is merging Feature and Request specs supported rspec behavior?

Question: I was recently building out a feature spec inside "spec/features", and in the middle of the feature spec, I decided to try doing this
context "foo", type: :request do
  it "works" do
    get some_path
    expect(response.body).to eq("something")
    visit some_path
    expect(page).to have_content("something")
  end
end

To my astonishment, it actually worked.  Typically in a feature spec, you can't cal the get, post, etc... methods and in a request spec you can't call the capybara visit method.  It works the other way as well.  If I'm in a request spec inside "spec/requests", I can tag things with :feature and get the same behavior.
Is this supported rspec behavior?  I understand there may be design/conceptual problems with this, but are there technical downside to co-mingling the two?
Answer: The reason why what we now know as feature specs and request specs are split out into separate directories is outlined in this blog post.
In summary, though, splitting them out was done in Capybara 2.0 to alleviate confusion of having a single kind of spec, the request spec, be responsible for performing full-stack integration tests as well as high-level specs that would drive the application only using its external interface (usually done via a headless web browser).  So, the current generally-agreed structure of specs would be:

Put anything that uses the Capybara DSL (visit etc) to assert on a page object in spec/features
Put full-stack non-controller specs that use Rack DSL (get etc) to assert on a response object in spec/requests

It's probably best not to co-mingle the two if you can, even though it's possible, if for no other reason than to keep with convention and give your future colleagues less surprises.

As for why you can co-mingle the specs if you want to, it's mostly to do with RSpec configuration, so it is supported behaviour:

You will likely have the line config.infer_spec_type_from_file_location! in your rails_helper.rb somewhere, which means that RSpec will consider any files in spec/features to be feature specs and any files in spec/requests to be request specs
Therefore, even if you wrap a type: :request flag around a spec in the spec/features folder, hence giving that single spec access to the Rack DSL, it will still have access to the Capybara DSL

You could even use RSpec.config to allow the Capybara DSL into any spec type or directory path you wanted, though this is not recommended:
RSpec.configure do |config|
  config.include Capybara::DSL, type: :request
  config.include Capybara::DSL, file_path: %r{spec/requests}
end

Overall though, for the sake of your codebase, future you, and your future colleagues, it's probably best to try and keep everything in its right place.
Comment: since the link is no longer valid - https://web.archive.org/web/20150302031543/http://www.andylindeman.com:80/rspec-rails-and-capybara-2.0-what-you-need-to-know
Comment: Thanks for the great info.


using multiple table in SQL

Question: I've got three tables:
department, employee and telephone
employee has columns EmpNo, Surname, Firstname and DeptNo.
telephone has columns EmpNo and Extension.
department has columns DeptNo and DeptName.
What I am trying to get is the full name, department name and telephone extension.
I think I am almost there but its not working yet.
My query
SELECT e.Firstname, e.Surname, d.DeptName, t.Extension
FROM employee AS e
INNER JOIN department AS d
INNER JOIN telephone AS t
ON e.DeptNo = d.DeptNo
ON t.EmpNo = e.EmpNo;

Answer: To fix your problem, move one of the ON clauses before the next JOIN
SELECT e.Firstname, e.Surname, d.DeptName, t.Extension
FROM employee AS e
INNER JOIN department AS d
  ON e.DeptNo = d.DeptNo
INNER JOIN telephone AS t
  ON t.EmpNo = e.EmpNo;

Comment: Strictly speaking, the claim *"The ON needs to come before the next JOIN"* is not correct. `FROM department AS d INNER JOIN employee AS e INNER JOIN telephone AS t ON t.EmpNo = e.EmpNo ON e.DeptNo = d.DeptNo` is (unusual but) perfectly valid.
Comment: @ypercube - Doesn't this documentation (http://dev.mysql.com/doc/refman/5.0/en/join.html) : `join_table:
 table_reference [INNER | CROSS] JOIN table_factor [join_condition]` indicate it is optional but must come before another JOIN? (I profess to not be 100% up on my documentation analysis - but that is how I understand it)
Comment: @ypercube - tks - I changed the verbiage. I didn't realize how the syntax allows the JOIN's to be nested, thus allowing all of the `ON` clauses to appear at the end.
Answer: The ON clause must follow the JOIN that it is modifying.
So:
INNER JOIN department d ON e.DeptNo = d.DeptNo
and
INNER JOIN telephone t ON t.EmpNo = e.EmpNo;
Answer: Your query is wrong. Join is not in correct format. Use like below
SELECT e.Firstname, e.Surname, d.DeptName, t.Extension
 FROM employee AS e
   inner join department AS d
    ON e.DeptNo = d.DeptNo
    inner join telephone AS t
      ON t.EmpNo = e.EmpNo;

using multiple table in SQL


HP Deskjet 1010: print jobs are "held."

Question: My printer worked fine until today, when I upgraded to 14.04 (trusty tahr).  Now the print jobs say that they are "held" and will not print.  What can I do?
Comment: Is the printer paused? If you right-click on the printer's icon or go into tis settings, is there a "resume" option?
Answer: Had the same problem in 16.04. Guy helped me out saying that sometimes Ubuntu needs manual installation of HP printers, laserjets.
Try it:
<code>sudo hpsetup -i
</code>
(and follow instructions).

HP Deskjet 1010: print jobs are "held."


PVC Pipe for sprinkler system broken in multiple places

Question: Roughly 2 years ago I posted this question: Need Sprinkler Cracked PVC Pipe Repair Suggestions
There was a lot of good suggestions, but now the issue has gotten much worse.
In the image below I'm going to attempt to paint a timeline in which we have attempted to fix our PVC piping breaking issues.
Mid-2017 (BREAK 1). We discovered a pipe broken near the corner of the wall. The way we fixed it was to cut the pipe and replace it. This solved the issue for 2 years.
Jun 2019-Week 1 (BREAK 2). There was a peanut sized crack on top of PVC pipe, in which our handy man decided to drill a hole bigger than the crack and place an attachment on top and create a new sprinkler head instead of cutting the pvc pipe. Because the communication cable ran along the bottom of the pipe (stupid). After that was fixed, we tested our system, and discovered another break. Ironically enough the handyman still managed to cut the communicate cable.
Jun 2019-Week 3 (BREAK 3). After fixing break 2, we noticed the pipe was also broken at Break 3. We fixed this issue, by cutting from break 3 to break 2 and installing a flexible hose and glued it. Again we re-tested our system and discovered a water flowing under all the soil near "break 4", flowing into the ditch seen around BREAK 2.
July 2019 - Week 1 (BREAK 4?). This is where I need people's advice. I don't know where break 4 is, and i'm not interested in looking, because that 50 foot tall tree won't stop growing, and will continue to cause problems.
The big problem is the area where this tree is located. As you can see in this hand drawn image. The first image (real) shows top part of this hand drawn diagram. The line in the middle separates the 2 areas, where the roots are above the ground and where the grass starts below the line. I'm assuming the PVC pipe runs all the way down (somehow) to the rest of the sprinkler heads (which are large black dots).
I need to rerun this PVC pipe in a different way from the water source seen on the upper left, that avoids the top tree all together. But how is the question. That ditch you see near break 2 took almost 2 full days to cut the tree trunks in order to finally see the pipe. When break 1 occurred in 2017, that also took a good 3 or 4 days to finally reveal the break.
Any suggestions?
Comment: I have 12 sprinklers valves and probably  1000 + ft of buried pipe , 20+ years old in the Piney woods; I can't put down a shovel anywhere without hitting roots . Never had a leak or break caused by roots. Shovels have caused a couple leaks. I think you have some other problem.
Comment: It was the tree, not some other problem, I assure you. The solution to the problem  we took was to dig up the soil along the bricks and cut the roots that came into that path. From the North Wall, Along the edge of the rounded brings on the left side down to mid way. Then a sharp right turn to the existing pipe along the east wall. Avoiding the tree's roots all together. We used 2 flexable PVC for the rounded corners as well as normal pipe. And ended up installing 2 more sprinkler heads in the process. No more flooding and everything is getting much more coverage.
Answer: I do not miss those California sprinkler systems.
You have a long thin L shaped strip that needs to be watered, bounded by a wall on one side and concrete on the other.
My proposition: abandon the underground sprinkler system.  It is loudly telling you it is more trouble and expense than it is worth.
Underground sprinklers are nice and unobtrusive for expanses of lawn and formal gardens.  You have neither.  You can easily run an aboveground length of PVC along the base of your wall.  You could salvage sprinkler units from your old system and position them along the new PVC completely above ground, pointing away from your wall.
Everything will be in view and easy to maintain.  Leaks will be immediately obvious.  Your new pipe will be against the wall and so out of harm's way as regards people walking or mowing.  The roots can do what they want underneath.
Comment: Painter here.  Take a tray of that garden dirt to Sherwin-Williams and have them color match it in flat.  Paint the PVC pipe that color. Quite agree : trying to have this underground pipe play nice with the tree roots isn't going to happen.  If the client doesn't get that, in this economy,  fire him.
Comment: @Sickest:  your time on the front lines has earned you a field promotion.
Comment: ??? I'm the client!
Comment: Thanks for the answer by the way. But I don't think i'm going to take that route. I thought about that route before I posted this question, since it's the most obvious solution.
Comment: Old post. How did you solve this?


Why does rebuild after restarting PC cause network errors?

Question: Using Windows 10 Pro and VS2015 Pro with all updates at the time of writing. Ran VS in safe mode and repair install of Visual Studio with no luck.  Note that SSMS and other apps can access the database OK at any time.
The code can be reduced to open a SQL database connection;
Dim sqlCon As New SqlConnection("Server=server\instance;Database=database;User Id=…;Password=…")
sqlCon.Open()
'Works after reboot as many times as required but fails after build or rebuild!
Console.WriteLine("Connection Opened")
sqlCon.Close()
sqlCon.Dispose()

The error after rebuild is;
Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Comment: I suppose that it's a network related problem. The SQL Server service is set to "Automatic" start? Maybe is it set to "Delayed starting"?
Answer: Turns out our IT team had installed Bitdefender Endpoint Security Tools on the PC.  Fortunately it was straightforward for a suitable firewall profile to be added to the in-house Bitdefender management server.


Infinite Subsets of Countable Sets

Question: Does a subset of a countable set being infinite ALWAYS imply that the set of which it is a subset is also infinite?
i.e. $B \subset A $ , B is infinite $\iff$ A is infinite.
I know this is intuitively true, I'm just being super careful not to make false assumptions.
Comment: Yes. The cardinality of a superset is at least as large as the cardinality of any subset. But, it is not an if and only if. $A$ is not infinite only if $B$ is infinite. $\{1\} \subset \mathbb{N}$ is true, but $\{1\}$ is not infinite while $\mathbb{N}$ is.
Comment: Yes, that implication is true.
Comment: So would you say B is infinite $\rightarrow$ A is infinite?
Comment: Just take the contrapositive: if $A$ is finite is any subset $B$ necessarily finite?  That should be something you can have more confidence in.
Answer: We can think in infinite set $A$ when exist a map one to one
$$ g: \mathbb{N} \to A$$
If $B \subset A$ and B is infinite, then exist a map one to one
$$f: \mathbb{N} \to B$$
Now, take the inclusion map $\text{Incl}: B \to A$ where $\text{Incl}(x) = x$ and consider the composition $\text{Incl} \circ f: \mathbb{N} \to A $.
Thus, we say that A is infinite
By the other hand, if A is infinite, it is not always true that a subset of A is infinite.
@InterstellarProbe gave a good counterexample.

Infinite Subsets of Countable Sets


Why a trigonometric function doesn't satisfy a polynomial equation?

Question: Why can't I have a trigonometric function as an input to a polynomial equation?
Comment: You're title and question seem to be asking different things
Comment: Now it's okay :)
Answer: A polynomial has a finite number of zeros, trigonometric functions typically inifite many.


brightness problem in ubuntu 18.04

Question: I have recently started using ubuntu and my brightness controls on my keyboard are not working. The brightness control in the dropdown menu of ubuntu is also not working and the screen is too bright for reading. My laptop has a ryzen 3500u processor and a radeon vega 8 graphics card. The other answers regarding similar problems are all about intel graphics cards. Please help.
Comment: too bright or not bright enough? Pleas edit your question with further details.
Comment: it is too bright
Answer: Install the Gnome Extension Adjust Brightness Icon

After installation and setting to ON you will find a lightbulb icon on the top bar.
Left click with the mouse to reduce the brightness to that required and keep clicking to reset to default. 4 clicks completes the cycle.

Don't forget that you can also set the Night Light ON with the right most menu drop down on the top bar.

The Night Light On utility helps considerably in reducing glare from over-white background screens.

brightness problem in ubuntu 18.04


What is the cooldown on companion gifts?

Question: In Star Wars: The Old Republic, you can buy or acquire gifts for your companion characters. You can't give your companion a gift immediately after giving them one, but there's no cooldown indicators like there are for, say, medpacs.
How long do I need to wait between giving my companions gifts?
Answer: I don't know if it's changed since January, but it was 30 seconds when I was playing. I'm pretty sure it puts a debuff on you which you can hover over to see the countdown.
Comment: It puts the debuff on your player, not the companion.
Comment: Also, getting another companion out won't change it in anyway, before anyone asks.
Answer: This changed in Patch 1.2.  There is no longer any cooldown, and the activation time is 3 seconds.
Answer: You can actually see the timer on it as a debuff to your character.  The icon is above your health bar with the others.


How to call a custom dialog fragment from a RecyclerViewAdapter inside a fragment in Android

Question: I am trying to call a custom dialog fragment i have created from a dialog fragment adapter that extends a recyclerView. I'm using the latest android studio with androidx. the following code is for the Custom dialog Adapter
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import tino.varconn.com.instantecocash.R;

public class DialogSendMoneyFirst extends DialogFragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_send_money_first, container, false);

    // Do all the stuff to initialize your custom view

    return v;
}

The following code i am trying to use to call the dialog fragment
package tino.varconn.com.instantecocash;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import tino.varconn.com.instantecocash.dialogs.DialogSendMoneyFirst;

public class EcocashAdapter extends
RecyclerView.Adapter<EcocashAdapter.MyViewHolder> {

private List<EcocashModel> itemList;
Context context;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    public ImageView img;
    public CardView cardView;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.listtext);
        img = (ImageView) view.findViewById(R.id.logo);
        cardView = (CardView) view.findViewById(R.id.cardView);
    }
}

public EcocashAdapter(List<EcocashModel> itemList) {
    this.itemList = itemList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.my_list_row, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
    EcocashModel ecocashModel = itemList.get(position);
    holder.title.setText(ecocashModel.getName());
    holder.img.setImageResource(ecocashModel.getImage());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (position == 0){
                Toast.makeText(v.getContext(), "Send Money", Toast.LENGTH_SHORT).show();
                DialogSendMoneyFirst dialog = new DialogSendMoneyFirst();
                dialog.show(((AppCompatActivity)context).getFragmentManager(), "MyCustomDialog");

            }
            if (position == 1){
                Toast.makeText(v.getContext(), "Pay Merchant", Toast.LENGTH_SHORT).show();
            }
        }
    });

}

@Override
public int getItemCount() {
    return itemList.size();
}

And this is the error :
Attempt to invoke virtual method 'android.app.FragmentManagerandroidx.appcompat.app.AppCompatActivity.getFragmentManager()' on a null object reference

Comment: Your `context` is `null`. How do you pass `context` to `adapter`? Can you add more details about your adapter?
Comment: I dont know how to pass, i just declared the context as : Context context
Comment: I think it's a bad design to open dialogs inside the Adapter. you should probably call up to the Activity or Fragment to execute the show of the Fragment Dialog. Use interfaces/callbacks to propagate the click to the main view components that holds the adapter, and there you have the context already.
Answer: Try this
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.my_list_row, parent, false);
    context = itemView.getContext()
    return new MyViewHolder(itemView);
}

If not work :
1.Check your activity is AppCompact or not.
2.If you are calling your adapter from fragment then use getChildFragmentManager()

If you are calling your adapter from Activity then use getSupportFragmentManager()
Comment: Can you please tell me from where you calling this "DialogSendMoneyFirst dialog = new DialogSendMoneyFirst();
dialog.show(((AppCompatActivity)context).getFragmentManager(), "MyCustomDialog"); "
Comment: Don't use all together, try one by one
Comment: As you are using AndroidX then you need use number one option, its mandatory. And try other three with that.
Comment: You didn't initialize the context and you are using it.

 let me edit my answer
Answer: If your context arrives from Fragment, then you have to use below: [cast context to FragmentActivity]
dialog.show(((FragmentActivity) mContext).getSupportFragmentManager(), tag);

Answer: Your context is null
Try this:
getActivity().getSupportFragmentManager()

instead of:
(AppCompatActivity)context).getFragmentManager()


Barn reinforcement

Question: I have an old barn that was resting on a stone foundation that was in rough shape. The foundation was only about 3-4 feet tall but it was starting to deteriorate. The barn is 24x26 and has two stories.
We lifted the barn -> leveled it out and poured a new slab that it sits on and is fastened to. We removed the old floor that sat about 8 feet high and built a new floor that sits about 12 feet high.
Two trusses were built to support new floor.
Upstairs there were 2x6's running from peak down diagonally down to double plate. These have been converted into roof trusses as shown in pictures along with some continual lateral bracing that ties them all together.
What can I do to try and firm things up?
During the occasional 100km/h gusts we get, the barns moves quite a bit and pops like hell.
Here is a diagram of the barn. The new floor (3/4 inch tongue and groove plywood) sits on top of those two red trusses.
Comment: Fixing the sway problem requires what the IRC (a typical US code) calls "wall bracing." In the US, if you paid me to fix this, I would pretend that your exterior cladding provides no strength nor stiffening against sway and follow [IRC R602.12](https://codes.iccsafe.org/content/IRC2021P2/chapter-6-wall-construction#IRC2021P2_Pt03_Ch06_SecR602.12) to size OSB sheathing for the inside surface of the walls. Alternatively, people often install wire rope plus turnbuckle X-braces, or they threaded rod X-braces. Those are potentially cheaper options, but would require hand calculations.
Comment: Most of the stuff that you described are parts of the building's gravity system. The lateral system resists wind. That's the sheathing on the outside of the walls, the yellow diagonal braces, the roof sheathing, and the elevated floor's sheathing. Does the entire structure flex excessively (suggesting a problem down low like the wall sheathing)? Or does the entire structure only flex excessively above a particular elevation?
Comment: Are those 2x4 walls? You said that you increased their span from 8 ft to 12 ft? Is it that wall, maybe, with flexing 2x4s that don't like the 12 ft distance to the floor elevation?
Comment: Hey Popham! Yes, they are true 2x4's and I think what may be happening is that the new floor height has created a sort of hinge. If you look at the wall on the right there is a sort of beam that runs across the wall that creates a "break." The 2x4's don't run all the way up like they do on the south and north walls. Both left and right walls have that beam configuration.
Comment: Here is a link to some framing pics: https://imgur.com/gallery/MPbsdjt
Comment: That interruption in the 2x4 studs would get modeled as a hinge in an analysis, but the hinge is stable. The 2x4s from above spans from roof to hinge without interruption, where they cantilever past the floor elevation, bracing the tops of the lower studs.
Comment: Thank you for the help popham. I know the question is closed but you have been a huge help. You definitely pointed me in the right direction! Thanks again.
Answer: Braces not reconfigured in parallel with the change in floor elevation:
The yellow braces are odd in that they don't end at the floor's elevation. If your old floor elevation needed and had braces ending at the floor elevation for strength purposes, then the new configuration has inadequate strength. Rather than analyzing whether the braces were necessary for strength, my instinct is to look at the old configuration. For all braces that ended at the old floor elevation, the braces should be modified to reach the new floor elevation.
Plywood wall panels on the inside surface of the walls can serve the same purpose as the braces, so if you intend to finish the interior of the walls somehow, then that finish may be an adequate substitute for any braces.
Explanation:
For lateral loading, there's basically constant stress in the walls between each floor elevation. As you scan down a structure, the stresses step up at each floor elevation as more wind load accumulates (it accumulates through wall studs, into floor diaphragms, and then into the walls at each floor elevation, hence the step pattern in the stresses). At the bottom of the structure there's the largest stress, the "base shear" stress. Your yellow braces don't reach the new floor elevation, so they relieve some of the board stress over the elevations that the brace spans. Above the top of the brace and below the elevated floor elevation, however, the boards get no relief in the current configuration.
The lack of relief is fine if the diagonal braces were intended merely to prevent swaying. If the boards alone were insufficient for all of the demand, however, and the braces were installed for strength purposes, then the new configuration has a strength problem. The prescription provided earlier would fix any strength problem after filtering out braces that obviously weren't installed for strength purposes (or maybe they were incompetently installed for strength purposes).
Comment: Is this intended to be a different/competing answer to the one you already wrote?
Comment: @brhans, this answers the generic theme of "barn reinforcement," but not any specifics from the question's body text. The flawed bracing most likely manifests as a lurking strength problem, not a flexibility problem as mentioned in the question's body text. If the comment character limit was larger, then this "answer" would be a comment. This indirectly answers his question, though, in that bracing is the solution to sway issues (once there's a proper load path from the floor diaphragm into the wall).
Answer: Bad load path from elevated floor diaphragm into brace wall line:
Zooming in on the 2nd image, I see that there are no fasteners between the joist running parallel to the wall and the wall's framing. This is a mistake. For your balloon framing, that joist acts as a shear collector analogous to a top plate in a platform framed system. To transfer the diaphragm load of the floor sheathing into the wall, you need substantial fastenings between that joist and the wall's studs. Off the top of my head, I would use 3-16d common nails per stud analogous to nailing a bottom plate to joists (item 15 from the table below IRC R602.3).
Assuming that the joist parallel with the wall at the other end is in a similar condition, obviously you should implement the same detail there as well.
While you're at it, you should also verify that the floor sheathing has been nailed to that joist every 6" with 8d common nails.
How this stops the popping sounds:
Currently the edge joist diaphragm loads go into the trusses at the truss ends, where those little areas at the ends of the trusses are good candidates for your popping noises. The edge joist to truss connection should be tremendously over-stressed. The truss is pushing sideways against the king studs for load transfer into the wall, where the wall sheathing fasteners are over-stressed in the neighborhood of the truss ends.
My other guess for the popping noise source is at the corners of the elevated floor. I imagine that there's also substantial diaphragm load transfer happening there at the wall-to-wall fastenings.
This is all predicated on the bad diaphragm connection theory. I'm predicting the popping sound locations based on that theory, so fixing the bad connection (the edge joist without fasteners to the the studs) would resolve the described popping causes.

Barn reinforcement


How to trigger focusout event on a ul element?

Question: I have a plugin that changes the look of select html tag on all browser.
I'm trying to make the new styled set of elements behave like a normal select tag. I'm almost there, but I only need to figure one thing out and that's how to hide a ul on focus out.
First off, here is a demo of the new select element (not in English, but you can find it easily ^^) :
http://mahersalam.co.cc/projects/n-beta/
If you click the toggle button of the select element, and then click away, the ul element that has the options won't disappear. That's because I can't fire a focusout event on that ul.
Here is the code that controls how the events are handled:
// Make a div which will be used offline and then inserted to the DOM
$namodgSelect = $('

');

/* other stuff ... */

$namodgSelect // Handle all needed events from the wrapper
    .delegate('a', 'click focus blur', function(e) {

        // Type of the event
        var type = e.type,

        // Declare other vars
            id,
            $this;

        e.preventDefault(); // Stop default action

        // Make an id ot the element using it's tag name and it's class name
        // Note: Because we add a class on the active toggler, it's easier to remove it from here and the logic will still work
        id = e.target.tagName.toLowerCase() + '.' + e.target.className.replace(' toggler-active', '');

        switch (id) {

            case 'p.selected': case 'div.toggle-button':

                // Only accept 'click'  on p and div
                if ( type != 'click') {
                    return;
                }

                // Show and hide the options holder
                if ( $optionsHolder.data('hidden') ) {

                    $selectElem.focus();

                    // This needs to run fast to give feedback to the user
                    $toggler.addClass('toggler-active').data('active', true);

                    // Show the options div
                    $optionsHolder.stop(true, true).slideDown('fast', function() {

                        // Sometimes fast clicking makes the toggler deavtive, so show it in that case
                        if ( ! $toggler.data('active') ) {
                           $toggler.addClass('toggler-active').data('active', true);
                        }

                    }).data('hidden', false);

                } else {

                    $selectElem.blur();

                    // Hide the options div
                    $optionsHolder.stop(true, true).slideUp(function() {

                        // Only hide the toggler if it's active
                        if ( $toggler.data('active') ) {
                           $toggler.removeClass('toggler-active').data('active', false);
                        }

                    }).data('hidden', true);

                }
                break;

            case 'a.toggler':
                switch (type) {
                    case 'focusin':
                        $selectElem.focus();
                        break;
                    case 'focusout':
                        // Only blur when the options div is deactive
                        if ( $optionsHolder.data('hidden') ) {
                            $selectElem.blur();
                        }
                        break;
                    case 'click':
                        $selectedHolder.click();
                        $selectElem.focus();
                }
                break;

           case 'a.option':
               // Stop accept click events
               if ( type != 'click') {
                    return;
                }

                // cache this element
                $this = $(this);

                // Change the value of the selected option and trigger a change event
                $selectedOption.val( $this.data('value') ).change();

                // Change the text of the fake select and trigger a click on it
                $selectedHolder.text( $this.text() ).click();
                break;
        }
    })

The whole code can be seen from the demo. As you can see, I already use the focusout event on the toggler and the options, so I can't hide the ul when that happens (that will disable the tab functionality).
If anyone can help me with this , it will be appreciated. Thanks.
Answer: Try out the jQuery outside events plugin
Will let you do something like:
$(this).bind( "clickoutside", function(event){
  $(this).hide();
});

Comment: Thank you Petersen. After I saw how the outside events plugin works, it was easy to figure out a fix for my problem.
Answer: I was able to hide the options panel using this code:
$(document).click(function() {
    if ( $optionsHolder.data('hidden') || $optionsHolder.is(':animated') ) {
        return;
    }
   $selectedHolder.click();
})

This works because focusing on another input is like a click on the document.


Markov Process for a Shared Channel with Two Users

Question: Question: Consider a communication channel where two users, A and B are sharing. Their arrival rates are $\lambda_A$ and $\lambda_B$ and service rates are $\mu_A$ and $\mu_B$. Only one user can use the channel at a time and no waiting queues, so the arrival rate is dropped if the channel is busy.
After thinking about it a while I drew this transition diagram, and I wonder if it's correct?
My logic was that, for user B to enter, the channel should go to a state where user A was served and vise versa. So the state n-1 was when user A accessing the system and n+1 would be user B's.
Also what could be the transition matrix for this scenario?

Update:
Moved the updated work to an answer.
Comment: I think I am misunderstanding your description because I am missing the Markovian dependence here. Are the consecutive arrivals correlated?

Here is what I understand, please correct me: there is an arrival to user i with rate $\lambda_i$. Since you didn't mention any structure to the arrival processes, I'm guessing it is memoryless and basically at any given time-slot arrival to user $i$ is with prob. $\lambda_i$.  If only one arrival happens to user $i$, they get $\mu_i$ units of service. What happens if both users get an arrival? Do they just get a conflict and drop packets?
Comment: If I were to "reverse-engineer a problem formulation" I would assume this: Continuous time, arrivals are independent Poisson processes, and service times are independent and exponentially distributed. Then a better model is to have states $\{Busy_A, Idle, Busy_B\}$, meaning that at any given time, the channel can either be busy serving a type A job, idle, or busy serving a type B job.
Comment: What do the states $n-1$, $n$, and $n+1$ represent?  The system model is not clearly described.
Comment: Hi, the question I extracted from a question paper and that was all the information they have give. From the area in the paper where the question was, I could say that it is a memoryless system and the distributions are both independent exponential process. I guess it's an M/M/1/K system. I have updated the question with a diagram with state suggested by @Michael as it seems to make much sense. :)
Comment: Note that the transition state diagram was drawn by me. I'm not sure if it's correct. Need to figure out..
Comment: Yes, your updated work is correct.  If you like, you can cut-and-paste that work into an answer and then resolve the question by giving it "best answer."   That is standard practice when you solve a problem based on hints. I assume you define your matrix $P$ with respect to the embedded discrete time chain that samples the continuous time chain only at times of state changes.
Comment: Excellent.. Thank you @Michael for pointing me the right path :)
Answer: A (1) is the state when A is being served and B (3) is the state when B is being served. Idle (2) is when channel is empty.

So I came up with the infinitesimal generator of this process as,
\begin{equation*}
\mathbf{A}
=\begin{bmatrix}
-\mu_A & \mu_A & 0\\
\lambda_A & -(\lambda_A+\lambda_B) & \lambda_B\\
0 & \mu_B & -\mu_B
\end{bmatrix}
\end{equation*}
and the transition matrix as,
\begin{equation*}
\mathbf{P} =\begin{bmatrix}
\gamma_{00} = -\upsilon_0 & \gamma_{01} & \gamma_{02}\\
\gamma_{10} & \gamma_{11} = -\upsilon_1 & \gamma_{12}\\
\gamma_{20} & \gamma_{21} & \gamma_{22}=-\upsilon_2
\end{bmatrix}
=\begin{bmatrix}
0 & 1 & 0\\
\lambda_A/(\lambda_A+\mu_A) & 0 & \lambda_B/(\lambda_A+\mu_A)\\
0 & 1 & 0
\end{bmatrix}
\end{equation*}