How do i display a variable from a XML document using Javascript?

Question: So I got this XML file:
<CATALOG>
<CD>
    <TITLE Name="123">Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
</CD>
<CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
</CD>
<CD>
    <TITLE>Greatest Hits</TITLE>
    <ARTIST>Dolly Parton</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>RCA</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1982</YEAR>
</CD>
<CD>
    <TITLE>Still got the blues</TITLE>
    <ARTIST>Gary Moore</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Virgin records</COMPANY>
    <PRICE>10.20</PRICE>
    <YEAR>1990</YEAR>
</CD>
<CD>
    <TITLE>Eros</TITLE>
    <ARTIST>Eros Ramazzotti</ARTIST>
    <COUNTRY>EU</COUNTRY>
    <COMPANY>BMG</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1997</YEAR>
</CD>
<CD>
    <TITLE>One night only</TITLE>
    <ARTIST>Bee Gees</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Polydor</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1998</YEAR>
</CD>
<CD>
    <TITLE>Sylvias Mother</TITLE>
    <ARTIST>Dr.Hook</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS</COMPANY>
    <PRICE>8.10</PRICE>
    <YEAR>1973</YEAR>
</CD>
<CD>
    <TITLE>Maggie May</TITLE>
    <ARTIST>Rod Stewart</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Pickwick</COMPANY>
    <PRICE>8.50</PRICE>
    <YEAR>1990</YEAR>
</CD>
<CD>
    <TITLE>Romanza</TITLE>
    <ARTIST>Andrea Bocelli</ARTIST>
    <COUNTRY>EU</COUNTRY>
    <COMPANY>Polydor</COMPANY>
    <PRICE>10.80</PRICE>
    <YEAR>1996</YEAR>
</CD>
<CD>
    <TITLE>When a man loves a woman</TITLE>
    <ARTIST>Percy Sledge</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Atlantic</COMPANY>
    <PRICE>8.70</PRICE>
    <YEAR>1987</YEAR>
</CD>
<CD>
    <TITLE>Black angel</TITLE>
    <ARTIST>Savage Rose</ARTIST>
    <COUNTRY>EU</COUNTRY>
    <COMPANY>Mega</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1995</YEAR>
</CD>
<CD>
    <TITLE>1999 Grammy Nominees</TITLE>
    <ARTIST>Many</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Grammy</COMPANY>
    <PRICE>10.20</PRICE>
    <YEAR>1999</YEAR>
</CD>
<CD>
    <TITLE>For the good times</TITLE>
    <ARTIST>Kenny Rogers</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Mucik Master</COMPANY>
    <PRICE>8.70</PRICE>
    <YEAR>1995</YEAR>
</CD>
<CD>
    <TITLE>Big Willie style</TITLE>
    <ARTIST>Will Smith</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1997</YEAR>
</CD>
<CD>
    <TITLE>Tupelo Honey</TITLE>
    <ARTIST>Van Morrison</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Polydor</COMPANY>
    <PRICE>8.20</PRICE>
    <YEAR>1971</YEAR>
</CD>
<CD>
    <TITLE>Soulsville</TITLE>
    <ARTIST>Jorn Hoel</ARTIST>
    <COUNTRY>Norway</COUNTRY>
    <COMPANY>WEA</COMPANY>
    <PRICE>7.90</PRICE>
    <YEAR>1996</YEAR>
</CD>
<CD>
    <TITLE>The very best of</TITLE>
    <ARTIST>Cat Stevens</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Island</COMPANY>
    <PRICE>8.90</PRICE>
    <YEAR>1990</YEAR>
</CD>
<CD>
    <TITLE>Stop</TITLE>
    <ARTIST>Sam Brown</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>A and M</COMPANY>
    <PRICE>8.90</PRICE>
    <YEAR>1988</YEAR>
</CD>
<CD>
    <TITLE>Bridge of Spies</TITLE>
    <ARTIST>T'Pau</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Siren</COMPANY>
    <PRICE>7.90</PRICE>
    <YEAR>1987</YEAR>
</CD>
<CD>
    <TITLE>Private Dancer</TITLE>
    <ARTIST>Tina Turner</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>Capitol</COMPANY>
    <PRICE>8.90</PRICE>
    <YEAR>1983</YEAR>
</CD>
<CD>
    <TITLE>Midt om natten</TITLE>
    <ARTIST>Kim Larsen</ARTIST>
    <COUNTRY>EU</COUNTRY>
    <COMPANY>Medley</COMPANY>
    <PRICE>7.80</PRICE>
    <YEAR>1983</YEAR>
</CD>
<CD>
    <TITLE>Pavarotti Gala Concert</TITLE>
    <ARTIST>Luciano Pavarotti</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>DECCA</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1991</YEAR>
</CD>
<CD>
    <TITLE>The dock of the bay</TITLE>
    <ARTIST>Otis Redding</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Atlantic</COMPANY>
    <PRICE>7.90</PRICE>
    <YEAR>1987</YEAR>
</CD>
<CD>
    <TITLE>Picture book</TITLE>
    <ARTIST>Simply Red</ARTIST>
    <COUNTRY>EU</COUNTRY>
    <COMPANY>Elektra</COMPANY>
    <PRICE>7.20</PRICE>
    <YEAR>1985</YEAR>
</CD>
<CD>
    <TITLE>Red</TITLE>
    <ARTIST>The Communards</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>London</COMPANY>
    <PRICE>7.80</PRICE>
    <YEAR>1987</YEAR>
</CD>
<CD>
    <TITLE>Unchain my heart</TITLE>
    <ARTIST>Joe Cocker</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>EMI</COMPANY>
    <PRICE>8.20</PRICE>
    <YEAR>1987</YEAR>
</CD>

And this is my HTML/JavaScript File:
<!DOCTYPEHTLM>

<title>XML</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>

<link href="css/bootstrap.css" rel="stylesheet"></link>
<link href="css/bootstrap-theme.css" rel="stylesheet"></link>

Machines

  14
  14
  14
  141
  14            1

So what I wanna do is to take the value of the variable "Name" of the Title tag in the XML document and display it on the HTML site. Right now the code works fine for displaying the value of all the tags, but I can't figure out how to make it display the variables.
Answer: Try this-
x=xmlDoc.getElementsByTagName('TITLE');
for (i=0;i<x.length;i++)
{
  alert(x[i].getAttribute('Name'));

document.write(x[i].getAttribute('Name'));
document.write("
");
}

More infor: http://www.w3schools.com/dom/met_element_getattribute.asp


What is the most efficient strategy for winning in Campaign mode?

Question: I have access to Barbarians, Archers, Goblins, and Giants - but I still tend to have my entire army wiped out pretty quickly when playing the campaign.  I am stuck on "Brute Force" and "Gold Rush", and I can't seem to progress past them.  I'm sure there must be some strategy for how to use each unit, but generally mine just get cut down by the cannons - and typically they don't even fight back, instead focusing on looting other buildings.  What is an effective strategy for using units in Campaign mode?
Answer: Campaign levels are like puzzles, and typically require use of specific units and/or upgraded units to succeed - especially if you are seeking a 3 star result.  A few general tips for success -

Use Tier 1 troops (barbarian, archer, goblin) in hordes to attack
single target defenses (cannon, archer tower, spring traps).  You'll
loose a few, but the horde will overcome.
Use Tier 2 troops (giant, wall breaker, balloon) for their
specialized abilities, particularly to crack splash damage defenses
like the mortar, which can wipe out your hordes.  When using the
balloon, be sure to wipe out air defense first.
Campaign levels are not timed, so once defenses are down you can wait
indefinitely to win if you want to save troops.
Queue some troop production in your Barracks before starting a fight (even though you are full).  Some of these troops will already be ready and waiting as soon as you are complete.

For per level strategies, check out the level by level video guides here.
I will also add that upgraded units help a lot.  As I now attack the high-end levels, it is much easier to 3 star now that I have most units upgraded to level 4 or level 5.  I also make use of the Barbarian King, which I believe makes these levels much easier since he is a very good tank, and can draw a lot of fire while your hordes disassemble the defenses.
Answer: I noticed in the goblin single player battles that there are a lot of spring traps and bombs that kill my barbs and archers pretty quick. After I have done a single player level I check the next level and train what I think I need. Building a lab helps as you can upgrade your troops. In multiplayer battles I usually train 10-15 giants, 1 balloon, 1-4 wizards and the rest archers, oh and 6-10 wallbreakers.
Comment: Hi @Mgoudi10 , welcome to Arqade!  Thanks for the answer.  I edited out the clan advertisement since it is not really part of the answer.  Probably the best place for that would be [chat](http://chat.stackexchange.com/), although I'm not sure you'll find many clashers here in general.  Clash on chief!
Answer: I use 10 level 2 dragons and 10 level 5 archers its slightly overpowered but its better this way than underpowered!
Answer: A good strategy would be to use 16 Giants and 5 Wall Breakers, with the remainder being Barbarians or Archers.
Answer: Use level 4 barbarians, level 4 archers and, if you can afford them, level 3 balloons.
Answer: I normally use spells quite a lot my main attack force for online and campaign is 3 lv1 dragons with the rest wizards.


How to add an object to an array using data from user input?

Question: I am building a recipe app that allows a user to add custom recipes and then display them.
I am able to add one recipe just fine, but when I add a second recipe, it changes the first one to have the same data as the second.

The initial state of the list of recipes is set as an empty array:
recipeList: [],
  newRecipe: {
    title: '',
    source: '',
    id: ''

Every time I hit a submit Recipe button, I want to be able to add a new recipe to the array and display it as a thumbnail (see screenshot above). The new recipe is in the form of an object, and as seen above, the initial state of the new recipe object is set to empty. So essentially I want to be able to put new user input into the new recipe object, add it to the empty array, and display the entire array as recipe thumbnails.
In the React Dev Tools, I see both recipes in the array, so I know they are being added. But for some reason they are not being displayed correctly.

Upon submission, each item in the array is mapped over and returned as a thumbnail:
return (

      <Navbar />

      {this.state.recipeList.map((recipe) => (

          <RecipeCardThumbnail
          key={this.state.id}
          title={this.state.title}
          source={this.state.source}
          />
        ))}

So it could be a problem with the map() method as it seems it is not mapping through the correct array.
This is the function that fires when I submit a form to add a new recipe:
handleSubmitNewRecipe = e => {
e.preventDefault();
this.handleAddNewRecipe(this.state.title, this.state.source, this.state.id);

};
And here's the function for adding a new recipe:
handleAddNewRecipe = (title, source) => {

const newRecipe = {
  title: title,
  source: source,
  id: (Math.floor(Math.random()* 1000))
}
  this.setState({recipeList: [...this.state.recipeList, newRecipe] });
  console.log(this.state.recipeList)
};

When the array is mapped over, it returns a component called<RecipeCardThumbnail />. Here is the code for that component:
return (

{this.props.title}

{this.props.source}

{this.props.servings}

{this.props.prepTime}

{this.props.cookTime}

{this.props.totalTime}

  );

In addition to each item not being displayed, I also get an error saying that each child needs a unique key. I thought that the id that I have works as a key.
Not sure if this is enough code, but you can view the entire code here: Recipe App on Github
Answer: At a glance it seems you should be using properties of recipe here, not this.state.
So this:
{this.state.recipeList.map((recipe) => (
  <RecipeCardThumbnail
    key={recipe.id}
    title={recipe.title}
    source={recipe.source}
  />
))}

Instead of this:
{this.state.recipeList.map((recipe) => (
  <RecipeCardThumbnail
    key={this.state.id}
    title={this.state.title}
    source={this.state.source}
  />
))}


Are there any fast 256 bit decoders for Minecraft?

Question: I am currently working on a 256 byte RAM. To access one address i have to build a decoder. My current decoder is a big block of AND-Gates with redstonetorches to check each combination. Are there any faster ways?
Current version of my decoder:
Comment: [Using big blocks of AND gates is pretty much unavoidable.](http://cpuville.com/decoder.htm) That's why computers needed integrated circuits to get smaller and faster. ;)
Comment: is this guy seriously building a real life computer... IN MINECRAFT?
Comment: Their goal is to run Minecraft in Minecraft.
Comment: @Ender What if I told you, that you can build a computer/system in Minecraft?!
Comment: @Ender [A *lot* of people build CPUs or parts thereof in Minecraft. :)](https://www.youtube.com/watch?v=LGkkyKZVzug)
Comment: If you're looking for data transfer mechanisms, perhaps try one of these vids: http://www.youtube.com/watch?v=g_V8S4kZWjY http://www.youtube.com/watch?v=DM-V_17AtAI
Comment: Currently it only supports ping pong (written in a language like ASM) :)
Comment: Back to the original question: How you need to output your data would probably always be very specific to what that data is going to be used for... You don't always need 256 bits, but when you do - those memory cells are dedicated to that use and the output is custom to that purpose. However, that being said I'm sure that the minified and/or/nor gates are the best available in vanilla.
Comment: @Ender First reaction when I saw that screen shot... O M G... some people have way too much time on their hands.
Comment: Just how fast, is fast?  Without knowing just how fast you want it, there are many answers.  I'm happy with a system I've made, but it takes a second or two for writing/reading (12 bit addressing), but it may also be possible to have it almost instant (using instant wire/smaller addressing)
Comment: Maybe I meant faster or easier than my current approach. Too long ago
Comment: How long does it currently take?
Comment: Please have a look at the date of the question
Answer: Your problem is probably not the speed of and gates, they are usually just a few ticks.
I'd rather guess that the problem is that you set them up in a way that the decoder is sending the signal to the and gates one after another, instead of all at the same time.
Your screenshot doesn't relly show much about the design you used, however there are a lot of decoders out there. (really just google a bit and you'll find tons)
I've built one for you that is instant on the rising edge (but takes inverted input):
This one uses 3 bits, but can be expanded if required. The torches you see in front take an extra tick, but may be required depending on your design. The input is 000 so the far right one is selected.

In this design, a redstone block with dust on it is used for a 0, a block with a torch is used for a 1. (from right to left: 000, 001, 010)
The pistons in the middle (or the odd ones) have an extra piston on top so they're updated by the redstone above:

Some more screenshots:
Answer: As SevenSidedDie said in the comments, you pretty much cannot avoid using AND gates for decoders.
There is a way though: Use Command Blocks.
With the new setblock features you can set redstone blocks. These don't have the delay that redstone repeaters / torches have, so your redstone signals can travel large distances faster.
This is not a nice fix, because the point of building a redstone computer (is for me at least) to do it without any command blocks. But maybe this will still help.
Answer: Maybe this could help? In the current design it is set as ROM but I think you could easily change that with some block replacers
Comment: Could you explain what happens in the video you linked? Since not everyone has the time/patience to watch a youtube video for a *possible* solution.


What are the red lines for?

Question: I was digging underground in Terraria and when I was mining some stone, I noticed they had red spots on them called Active Stone Blocks. When I had it in my characters hand, there were red lines starting to go down the tunnel I was going down through. What are these red lines?
I'm a beginner of Terraria, so I don't know much about this.
Answer: Those red lines are wire, which is used to connect triggers and mechanisms. Wire is invisible unless you're holding something that can interact with it, like the Active Stone Block, which becomes non-solid when activated by wire. In the underground, you will usually find it connecting pressure plates to various traps. You can check the wiki for more information.
Comment: And if you see it underground, and you didn't put it there - its probably a trap... so watch out ;)
Comment: Thanks. I'm just a beginner at Terraria, and I don't know much about wiring. Thanks a lot for the answer.
Comment: @JimJones Use it as a trap finder- many a time I would of died, if it weren't for my wrench and light. (Sorry for trying to rhyme, I don't do it most of the time)
Comment: I know. The boulder traps (that's what I learned) I will avoid.
Answer: Sometimes they hold boulders, and when you're underneath the trap, the active block moves, and it drops the boulder. I'm guessing you dug through a boulder trap.
Comment: @9t. He did provide an answer (the red lines hold boulders). If it's wrong no need to flag it as "Not an answer", it's still an answer, just a wrong one
Comment: @Oak I may or may not have forgotten to read the whole question since I was in a rush. Apologies.

What are the red lines for?


Are loose teeth in a saw blade a safety concern?

Question: When I watch videos on using a table saw safely, it almost always is about kickback.
I realize, that kickback is the most dangerous hazard, but are loose teeth, that could become projectiles, when disconnecting from the blade really no issue ? For example in case of an manufacturing defect.
Or am i missing something?
Comment: A lot of things could have defects. The motor could have a shorted armature and catch on fire when you turn it on. Prevent what you can but you can't prevent everything.
Comment: I don't think anyone will think less of you for inspecting the blade.
Comment: If there is a manufacturing defect in the blade, it would potentially be hard to see.
Comment: Probably impossible but I suppose you could make sure it hasn't lost any tips
Comment: Yeah right (not really) ... that is more or less the question. Maybe there are a few ways to protect against this.
Comment: I have abused a number of carbide tooth blades and never seen a tooth come off, although I have chipped some. Same for carbide inserts on masonry drill bits. I would say failure of silver solder ( holding the carbide) is one of the least of your worries.
Comment: The carbide teeth are usually silver soldered or brazed on to the steel blade, can they come loose sure, I cut metal with my saw regularly both thin steel and aluminum. Yes I have chipped and broken teeth off when hitting a nail in a board but as far as inspecting the blade the only thing I ever do is inspect for sharpness. I don't think I have ever seen a loose one that was not broken.
Comment: I've never seen a loose circular saw blade tooth (though I've seen plenty of missing teeth). Therefore, I don't understand this question.
Answer: Loose teeth on a modern table saw blade are indeed a thing to be concerned about. It would be anybody's guess as to where the loose tooth would fly if it came off the blade. As many readers here may know the most popular blades in use today are the type with carbide tips bonded to the tooth cutouts on a blade core.
It is possible that there is a history of table saw safety over many years that has contributed to the current body of knowledge, articles and videos. Historically the saw blades in use twenty or thirty years ago were much more likely to be steel blades with teeth that were sharpened and set with alternate facing cutting edges that were bent slightly in each direction from the plane of the blade body. It is much less likely that a tooth on a blade would come flying off when the teeth are all cut and formed from the core material of the blade. So in the past it was less likely that saw blade destruction would be stressed in any particular way in safety information.
It is also true that warnings about trying to use blades that are dull and worn would have been more prevalent. The modern carbide tipped saw blades in common use today stay sharp much longer. And even if they do become slightly dull the integral design of the blades upon which the carbide tips are mounted prevents a lot of the binding of the saw blade in the kerf that is experienced with an all steel saw blade when the teeth have lost most of their set.
Answer: In theory it's not a serious issue. The tooth of a table saw blade travels at a linear speed around 146 feet/second, so if a tooth suddenly came loose you'd be faced with a tiny piece of metal travelling just under 100 mph. In reality the most likely result is it breaks and lodges in the wood when entering the kerf, or exits the kerf and travels straight down. [FWIW the teeth of a 7.25 circular saw blade would seem to be more of danger since they're similar size and run at much higher rpm.]
While a hundred mile an hour tooth sounds bad, it's not a huge amount of kinetic energy. It's much less than a baseball, probably more than a pellet gun. (A smaller mass travelling at 750 ft/s.) Certainly enough to merit eye protection, but highly unlikely to kill or seriously injure.
A much larger concern would be some sort of catastrophic blade failure flinging both lumber and large pieces of metal around. Large kicked back pieces have quite a bit more kinetic energy than a tooth. A prudent precaution is to let the saw spin freely for a bit prior to cutting. Grinders, which use resin blades typically suggest allowing the blade to run for 15s away from your face to be sure the glue isn't failing before you start grinding.
The real danger with a table saw is that accidents happen quickly in close proximity. That's compounded by the fact that the saw typically has enough power to accelerate anything on it to 100mph. While a tooth may present a limited danger getting hit by a 2x6 at 100 mph is an entirely different ball of wax. (Big leaguers shrug off baseballs, but don't want to be hit by a car travelling the same speed!)
Comment: I think your math is off.  My Grizzly table saw spins at 4200 rpm.  The blade is 10" in diameter.  By my calculations, that means that the teeth travel at 10 * pi * 4200 inches per minute.  This is about 11,000 ft per minute or 659,715 ft per hour or about 125 miles per hour.
Comment: Duh, brain cramp. It should be 146 ft/sec which works out to 99 mph.
Answer: The biggest problem with them is that they go missing on modern blades easily, causing kickback. Remember, the teeth are typically soldered on and if they come off, it's most likely going to be at the point of contact with the material you're cutting.
I recently had my miter saw kickback. I had bought a cheaper blade and discovered that several teeth had come off. None of the teeth I found were more than a foot from the saw.
If you want to reduce the chance of missing teeth, try buying higher quality blades.
Comment: @Criggie I was only missing 5 teeth on a 40 tooth blade. It was the two next to each other that did me in with kickback (block flew off the fence and hit my hand)
Comment: Could you feel any imbalance or wobble/shimmy while the blade was spinning?  Guessing not cos of the small weight of a tooth.
Answer: Anything coming off the blade is a problem, for sure. With table saw blades, though, there is little chance of that happening, so it doesn't get as much attention. Kickback is a much more prevalent issue, therefore it gets more attention.
Kickback (and most other well-known table saw dangers) is a preventable danger (for the most part), while a manufacturing defect is all but undetectable by the end user. You can certainly inspect the blade before use, to look for signs of metal fatigue, loose teeth, or other dangers, but most table saw blades are thrown out because they become dull, not because they break. Of course, if you happen to hit a piece of metal you'll most certainly want to inspect your blade and perhaps replace it, but during normal use the blade will remain in one piece, almost guaranteed.


Google script - Can't attach a PNG file from Google Drive to form email

Question: I've setup a trigger with the following code to send out an email everytime an employee submits a request. What this basically does is send out a brochure (in PNG format and stored in Google Drive). Somehow, the code does not work. Spent almost the entire day scouring the net for answers, but none helped. I tried the DriveApp.getFileByID method and it worked, but that was just for one file. The attachment depends on the product that the employee selects on the Google form, and that is dynamic.
Any help is much appreciated. Thanks!
function SendBrochure(e) {
    try {

        var email = e.values[1];
        var subject = "ABC Co - Information you requested";
        var msgcc = "firstname.lastname@example.com";
        var aliases = GmailApp.getAliases();
        var cxnm = e.values[2] + " " + e.values[3] + " " + e.values[4];
        var msgl1 = "Greetings from ABC Co, " + cxnm + ".";

        var emailText = "Greetings from ABC Co, " + cxnm + ".
With reference to your conversation
    with us and your request for information, please find attached herein the same.

 Should you
    require further assistance, please contact the undersigned, or refer to the brochure for pertinent
    site contact details.

We appreciate your interest and look forward to your visit soon.

 Thanks and regards,
ABC Co
Tel: +1 202 555 1212
Web:
    www.abc.com
";

        var brochurename = e.values[5]; //gets file name from form (already filled in - for e.g f_1.png)

        var brochure1 = DriveApp.getFilesByName(brochurename);

        GmailApp.sendEmail(email, subject, msgl1, {
            name: 'ABC Co',
            attachments: [brochure1.next()],
            htmlBody: emailText,
            from: aliases[1]
        });

        GmailApp.sendEmail(msgcc, "Email sent!", "Your email request to " + email + " has been completed successfully at " + e.values[0], {
            'from': aliases[1]
        });

    } catch (e) {
        Logger.log(e.toString());
    }

}

Answer: try getting the image as a blob with the right mime type, see [doc here][1],
in your code it would become :
...
attachments: [brochure1.next().getAs('image/png')],
...

PS : didn't have the opportunity to test this, please let us know it it does work. [1]: https://developers.google.com/apps-script/reference/drive/file?hl=fr-FR#getAs%28String%29

EDIT : here is a new version of your code that works, just change the image file names to suit your case.
I wrote a test function to be able to test without form submission.
function test(){
  var par = {};
  par['values']={};
  par.values[0]=new Date();
  par.values[1]='email@example.com';
  par.values[2]='xxxxx';
  par.values[3]='yyyyy';
  par.values[4]='zzzzz';
  par.values[5]='LOGO.jpg';// just for test I took a file I had in my drive
  SendBrochure(par);
}

function SendBrochure(e) {
  Logger.clear();
  var email = e.values[1];
  var subject = "ABC Co - Information you requested";
  var msgcc = "email@example.com";
  var aliases = GmailApp.getAliases();
  var cxnm = e.values[2] + " " + e.values[3] + " " + e.values[4];
  var msgl1 = "Greetings from ABC Co, " + cxnm + ".";

  var emailText = "Greetings from ABC Co, " + cxnm + ".
With reference to your conversation "+
    "with us and your request for information, please find attached herein the same.

 Should you "+
      "require further assistance, please contact the undersigned, or refer to the brochure for pertinent "+
        "site contact details.

We appreciate your interest and look forward to your visit soon.
"+
          "
 Thanks and regards,
ABC Co
Tel: +1 202 555 1212
Web: www.abc.com
";
  var brochurename = e.values[5]; //gets file name from form (already filled in - for e.g f_1.png)
  var brochure = false;
  Logger.log('brochurename = '+brochurename)
  var brochure1 = DriveApp.getFilesByName(brochurename);
  if(brochure1.hasNext()){
    var brochure = brochure1.next().getBlob();// get the blob
    Logger.log('brochure name = '+brochure.getName())
  }else{
    Logger.log("didn't find a file with name = "+brochurename)
  }
  Logger.log('email data = '+email+'  '+subject+'  '+ msgl1)
  if(brochure){
    GmailApp.sendEmail(email, subject, msgl1,{attachments:[brochure], htmlBody:emailText});
    GmailApp.sendEmail(msgcc, "Email sent!", "Your email request to " + email + " has been completed successfully at " + e.values[0])
  }
  GmailApp.sendEmail(msgcc, "Email not sent!", "Your email request to " + email + " has not been sent because of an invalid attachment\nSee Log below : \n\n"+Logger.getLog());
}

Comment: Thanks for the prompt response. I tried the same, but it gave me the following error: Cannot retrieve the next object: iterator has reached the end. I also put it into a separate file and ran - but it threw the same error. Is there anyway I can include the picture inline from Google Drive? Thanks. Much appreciated.
Comment: this error is different, it means that it didn't find a file with the required name. To prevent that use a condition like  if(brochure1.hasNext()){...
Comment: Thanks. I figured it out.. somehow. I used driveapp.getfilebyid. Now the problem is that it won't attach the appropriate file. my code: `code` var proj = e.values[5];

    if(proj = "RT.pdf"){
    var brochurename = "0B4F9WhlpOz3dZFR0WjJ1NUttWGM";
  } if(proj = "RA.pdf"){
      var brochurename = "0B4F9WhlpOz3dakRyTWtOT1ZCcVE";
    } if(proj = "RG.pdf"){
      var brochurename = "0B4F9WhlpOz3dYW5STGMybG5SdzQ";
    } if(proj = "RI.pdf"){
      var brochurename = "0B4F9WhlpOz3dQkZnbVdCWlh2NEU";
    } if(proj = "WC.pdf"){
      var brochurename = "0B4F9WhlpOz3dRndwazBaaFhwRDA";
    } `code`
Comment: It won't attach the appropriate file. Instead, it just does it at random. Could you please help me with the if / else statements? Thanks!
Comment: sorry for the delay, I'm meeting some ISP issues right now... very poor connection and no access to my Google drive :-/
Comment: No problem. I can wait. :-)
Comment: heheh.. silly me.. i forgot that the 'equals to' operator in jscript is '==' and not just '='. Thanks a ton @Serge insas! I'm calling it a day!
Comment: Thanks again Serge. Worked like a charm!


Proving convergence theorems

Question: Suppose that ${a_n}$ converges to a.
prove the sequence ${ca_n}$ converges to ca, where c is any constant.
Here is the start of my proof:
By definition of convergence of a sequence, $|ca_n - ca| < \epsilon$ where $\epsilon > 0$ Then we can factor to get $c|a_n - a| < \epsilon$
I am stuck at this point, where do I go from here?
Answer: The trick is that since we know that $a_n$ converges to $a$, we may choose how close they come together, that is, we may make $|a_n-a|$ very small:
Suppose $a_n$ converges to $a$. What this means is that for every $\epsilon'>0$ there exists an $N'\in\mathbb{N}$ such that for all $n>N'$, $|a_n-a|<\epsilon'$.
Now let $\epsilon>0$, and choose $\epsilon'=\frac{\epsilon}{|c|}$. Now choose $N=N'$ as above. Then for any $n>N$ we have:
$|ca_n-ca|=|c||a_n-a|<|c|\frac{\epsilon}{|c|}=\epsilon$. Completing the proof.

Proving convergence theorems


Installing a solid wood tabletop on this steel frame

Question: I would like to screw this solid wood tabletop (the long one in the back, it's beech wood)

onto this steel frame.

The slab's dimensions are going to be 200 x 80 cm. I read that "wood moves", so I would have to screw the table top on in a way that allows for movement.
The problem is that none of the methods that I've read about that allow for movement are compatible with the screw holes facing up in the frame.

How can I solve this? Should I worry about movement for this type of tabletop at all or can I just screw it fixed?
Here's another photo of how the wood is supposed to look after it's been oiled:
Comment: Does it have an OSB backing? If so, it may not shrink much. In any event, wood does not shrink along the grain. It shrinks and expands perpendicular to the grain. If that helps you any.
Answer: What do the purveyors of this table top say about mounting? If it might be a problem, one could consider straps which go over the metal frame and are attached to the underside of the table with two screws for each strap.
Personally, I would just mount it as shown in the picture and see how it performs. You could leave the table top in its intended location lying on the metal base, unattached, for a week or so to allow it to stabilize to the ambient temperature and (especially) humidity . Then drive the screws just barely snug for a month or so and only then tighten to full snug, but not hard tight. It looks like the screws shown have a little wiggle room in the holes in the metal frame.
Edit
You could consider using heavy, large flat washers between the heads of the screws and the metal frame so that the heads of the screws don't bite into the metal frame and so resist sliding.


Tika Solr Metadata mapping ignore document title

Question: I have the following config file for solr:
  <requestHandler name="/update/extract"
                  startup="lazy"
                  class="solr.extraction.ExtractingRequestHandler" >
    <lst name="defaults">

      <str name="lowernames">true</str>
      <str name="fmap.content">content</str>
      <str name="fmap.application_name">type</str>
      <str name="fmap.content_type">mime</str>
      <str name="fmap.stream_size">size</str>
      <str name="uprefix">ignored_</str>
      <str name="captureAttr">false</str>
    </lst>
  </requestHandler>

and this is my schema:
   <field name="id" type="string" indexed="true" stored="true" required="true" />
   <field name="access_type" type="string" indexed="true" stored="false"/>
   <field name="access_restriction" type="string" indexed="true" stored="false" multiValued="true"/>
   <field name="title" type="string" indexed="true" stored="true" multiValued="true" />
   <field name="tags" type="string" indexed="true" stored="true" multiValued="true"/>
   <field name="content" type="text_en_splitting" indexed="true" stored="true"/>
   <field name="created" type="date" indexed="true" stored="true"/>
   <field name="createdby" type="string" indexed="true" stored="true"/>
   <field name="modified" type="date" indexed="true" stored="true"/>
   <field name="modifiedby" type="string" indexed="true" stored="true"/>
   <field name="source" type="string" indexed="true" stored="true" />
   <field name="version" type="string" indexed="true" stored="true" />
   <field name="resourcelink" type="string" indexed="true" stored="true" />
   <field name="downloadlink" type="string" indexed="true" stored="true" />

   <field name="type" type="string" indexed="true" stored="true" />
   <field name="mime" type="string" indexed="true" stored="true" />
   <field name="size" type="string" indexed="true" stored="true" />

I want to set the title myself. But Tika keeps setting it's own title (that's why I set multiValued="true" temporarily), which I find strange because I have to manually map stuff like stream_size and content_type.
What solution is possible to this issue?
I'd like Tika to override the title I assign, like this:
I have 3 documents, for one of those, Tika doesn't extract a title, in this case, I have my own title I set passing literal.title, when Tika does extract a title, I want it to override the one I passed in literal.title. Is this possible?
Comment: Can you give the locations for solr config file and schema?
Answer: I was working on the same issue some time ago, but I hit a wall as well :(
I let Tika take "title", and use literal.other_title_like_field to store proper title.
This is not a best solution, but worked for me.
Comment: Maybe you can give an example how to do this? Or a link about this?
Comment: Sorry, I have not used it for longer while now
Answer: For those who are still struggling with this problem, I solved it by adding
<str name="fmap.title">ignored_</str>

in my ExtractingRequestHandler defaults.


KItchen backsplash tile cut too short and grout line too thick

Question: I just had my back splash installed in my kitchen and the tiler cut one section a bit too short. The grout went up today and the area is thicker then any other areas and very noticeable especially with a dark countertop. Unfortunately it is an area where there would be no appliance in front of it to hide.
Is there any way this can be fixed? Is it possible to remove the grout and put little pieces of tile in that section. I think that would be less noticeable then how it is right now. Any help is greatly appreciated. Also...I notice the tile is not as shiny as it was before the grout...do I have to wash it after the grout fully dries? I wanted to attach photos but they said to large to do so and I have no idea how to make smaller :)
Comment: Some photos might help. "*a bit too short*" is not a SI unit, so it's not clear how large the gap is without seeing it.
Comment: The dull haze is the cement in the grout mixture once the grout is dry you will be able to wipe it off. it is a good idea to seal grout in a kitchen to prevent or reduce staining.
Answer: The only right way is to pop those tiles off and reinstall them with a better fit. Any attempt to conceal the poor workmanship will look tacky.
In my opinion, the installer should handle this for you. A cut end should always have a matching or smaller grout line for just this reason.
Answer: Put up some sort of trim (quarter-round is canonical) to cover the gap.
Comment: What sort of trim are you referring to? Wood trim on a tile backsplash?
Comment: I think he was referring to 1/4 round tiles without a photo it is hard to guess what the correct path would be but 1/4 round sounds like a good idea to me.


Bijection between derangements and permutations whose first ascent is in even position

Question: Define an ascent of a permutation, $w$, to be an index, $1\le i\le n$, such that $w_i<w_{i+1}$. Furthermore, we adopt the convention that $n$ is always an ascent. This convention is not typical, but it makes this particular problem work out.
Let $\mathcal{D}(n)$ and $\mathcal{E}(n)$ be respectively the set of derangements of $n$ elements and the set of permutations of $n$ element whom first ascent is in even position. It's not so hard to see through a recursive reasoning that the cardinalities of this two sets are equal. But Stanley's Combinatorics volume 1 asks also for a combinatorial proof. I tried for hours but I couldn't figure it out so I checked the solution. He proposes the following bijection:

Let $w$ be a derangements.
Write it as a product of cycles in the standard way (the standard convention of Stanley is: "the cycles start with their biggest element").
Arrange the cycles in such a way that the elements of the smallest elements of the cycles are in decreasing order.
Move the smallest element of each cycle to the second position of its cycle.
Erase the parenthesis and you have your $w'\in \mathcal{E}(n)$.

Then he states that it's fairly easy to see that this is a bijection. The main question is:
-How do I construct an inverse to effectively see that this is a bijection?
Then there is a secondary question that is partially a "rant". How should you come up with these convoluted ideas? For sure I'm not an expert in combinatorics, but I studied the material covered in this course and I'm really trying hard to do the exercises in this book. This exercise is $[2+]$ that the author defines to be "somewhat difficult", but then the author states that it's published in a paper...
Maybe I'm simply mathematically immature but I simply can't understand if I'm studying wrong or it's simply the difficulty levels of this book that are skewed. This course feels so much different from any other course I've taken.
Comment: Richard Stanley taught at MIT :).  When I took his graduate classes, a typical problem set would consist of perhaps 10 or 15 problems, of which one was required to submit three.  On a good problem set I would submit three 3-, I don't think I ever solved a 3 for homework.  Now, when I teach graduate combinatorics (at some place decidedly less fancy than MIT), I mostly limit myself to assigning 2s and 2-s.
Comment: If Stanley gives an outline for the bijection, presumably that's because he thought it would be hard for his readers to come up with it. Or was that in an answer key?
Comment: It was in the solutions. It wasn't given as a hint. Sometimes the solutions seem like hints in this book (at least to me).
Comment: How are you reading the fourth step? Starting with $(345)(12),$ it seems to mean the result is $53421.$ But this would seem to make the first ascent at position $2$ for all $w,$ so that's obviously the wrong reading.
Comment: The standard convention in the book require cycles to start from their biggest element. So the second answer is the correct one. It's not true that the first ascent is always in position two. For example if the first cycle is a $2$-cycle then nothing can be said about the second element.
Comment: @ThomasAndrews $w=(1\;2\;3)(4\;5)\mapsto 54312$, the latter has its first ascent at position $4$.
Comment: Ah, so if the derangement was $(65)(4321)$ the result would be $654132?$
Comment: Yeah, I didn't recall Stanley's convention for cycles. It might be worth mentioning in the question, because the hint is useless without that, and it is natural, since sorting by lowest elements, to start with lowest elements.
Comment: @ThomasAndrews No, $(6\;5)(4\;3\;2\;1)=(6\;5)(2\;1\;4\;3)\mapsto 652143$. When moving the smallest element to the second position, you need preserve the cyclic order.
Comment: @MikeEarnest I didn't know this
Answer: This answer is roughly speaking a long-winded version of Mike's answer above, but I've tried to at least make a stab at saying where the bijection comes from in answer the rant part of the question :)
To fix notation, recall that $S_n$ is the group of bijections of an $n$-element set $[1,n] = \{1,\ldots,n\}$, and any permutation can be written as the composition of disjoint cycles, where a cycle $\mathbf e = (e^1,\ldots,e^l)$ denotes the permutation which maps $e^i$ to $e^{i+1}$ if $i<l$, $e^l$ to $e^1$, and fixes all $k \in [1,n]\backslash \{e^i: 1\leq i \leq l\}$. We write $|\mathbf e|=l = n -|\{k \in [1,n]: \sigma(k)=k\}|$.
Stanley's bijection $b\colon \mathcal D(n) \to \mathcal E(n)$ takes a derrangement $\sigma$, views it as the composition of its disjoint cycles, writes these down according to an ordering convention, and then reads the resulting list $t_1t_2\ldots t_n$ as the permutation $i\mapsto t_i$. This map, given by writing a permutation according to one labelling convention and then reading it off using a differnet convention, may feel bizarre to start with, but in this context it is actually natural enough: it is straight-forward to recursively build a derrangement by specifying its cycles one at a time, while to recursively build a permutation $\tau$ with even first ascent, it is simpler to iteratively build up the list $t_1\ldots t_n$ (where $\tau(i)=t_i$).
The subtlety is thus what order to choose to write the cycles in, and what convention to use to "cut" a cycle into a segment. The latter is in a sense more evident: if we place the smallest element of the cycle in the second slot (and for a derangement there are always at least two slots in each cycle) the this obviously creates an ascent at $2$ unless the first cycle has only two elements. In addition to this, Stanley's map then also places the cycles so that their minimal elements form a decreasing sequence, that is, if $\sigma = \mathbf c^1\ldots \mathbf c^r$ where $\mathbf c^i = (c^i_1,\ldots, c_i^{k_i})$, then $c_i^2 = \min\{c_i^j: 1\leq j\leq k_i\}$ and $c_1^2>c_2^2>\ldots >c_r^2$.
It follows that $b(\sigma)$ has $b(\sigma)(1)>b(\sigma)(2)b(\sigma)(3)$. But since $k_1=2$, $b(\sigma)(3)>b(\sigma)(4)$ since they are the first two terms in a cycle, so the first ascent is at least $4$. Iterating in this way we see that we obtain an even first ascent unless all the cycles have length $2$ and $c_2^i>c_1^{i+1}$, and since our conventions insist that $c_1^i>c_2^i$, we see that the list $t_1\ldots t_n$ is strictly decreasing and hence
$$
\sigma=(n, n-1)(n-2, n-3)\ldots (2,1)
$$
so that $n=2r$ and $n$ is an ascent by convention. It follows that $b\colon \mathcal D(n) \to \mathcal E(n)$.
To see that it is a bijection, consider first how our ordering convention can be used to recover the cycles from the list obtained by removing the bracketing they give: each cycle $\mathbf c^i$ is a segment of the list with its minimal element $c^i_2$ appearing second, and these minimal elements must decrease. We describe the inverse map $c\colon \mathcal E(n) \to \mathcal D(n)$ by recursively removing an initial segment of the remaining list.
Now suppose that $\tau \in \mathcal  E(n)$. We describe $c\colon \mathcal E(n)\to \mathcal D(n)$ recursively, where at stage $k$ we produce the $k$-th cycle of $c(\tau)$. Let $i_1=1$ and consider the list $t_{i_1}\ldots t_n$. Since $\tau$ has even first ascent, $t_1>t_2$, and we let $j_1 = \min\{k>2: t_k<t_2\}$.  If $j_1=3$ then let $\mathbf c^1= (t_1t_2)$ and let $i_2 = 3$. If $j_1\geq 4$, then let $\mathbf c^1 = (t_1\ldots t_{j_1-2})$ and $i_2=j_1-1$. In the latter case, the remainder of the list begins with a descent because $t_{j_1-1}>t_2>t_{j_1}$, while in the former, places $1$ and $2$ were not ascents, and the first ascent is even, hence $3$ is a descent. Iterating this process on $t_{i_2}\ldots t_n$ and
so on yields $c(\tau) = (\mathbf c^1\ldots\mathbf c^r)$, where each cycle $\mathbf c^i$ has length a least $2$, and $c^i_2$ is its minimal element.
Answer: For the inverse bijection, you follow the steps you listed in reverse. The only part that requires explanation is the "erase the parentheses" step. Given the output $w'$ whose parentheses have been erased, how do you tell where the parentheses were? To do this, we will scan $w'$ from left to right, looking for the entries of $w'$ that correspond to the smallest elements of their cycle. Everyone time we find such an entry, say at position $w_i'$, we will place a pair of closed and open parentheses, )(, between $w_{i-2}'$ and $w_{i-1}'$.
Note that $w_2'$ is always the smallest element of the leftmost cycle. This is because all cycles have length at least $2$, and since the smallest element of the cycle is written second.
Suppose that we just determined that $w_i'$ is the smallest element of a cycle. Here is how we find the smallest element of the next cycle. Let $j$ be the smallest integer such that $j>i$, and such that $w_j'<w_i'$. If no such $j$ exists, then $w_i'$ is in the last cycle. Otherwise,  there are two cases.

If $w_j<w_{j+1}$, or if $j=n$, then $w_j$ will be the smallest element of the next cycle.

If $w_j>w_{j+1}$, then $w_{j+1}$ will be the smallest element of the next cycle.

Example 1
Let $$w'=435261.$$ We need to place parentheses, so we start by placing them at the beginning and end to get $(435261)$.

The smallest element of the first cycle is always $w_2'=3$.

The smallest $j$ such that $j>2$ and $w_j'<w_2'$ is $j=4$. Because $w_4'<w_5'$, we are in case $1$, and we have determined that $w_4'$ is the smallest element of the next cycle. Therefore, we place )( between $w_{4-2}'$ and $w_{4-1}'$, obtaining $(43)(5261)$.

The smallest $j$ such that $j>4$ and $w_j'<w_4'$ is $j=6$. Since $j=n$, we are in case $1$, and have determine that $w_6'$ is the smallest element of the next cycle. Therefore, we place )( between $w_{6-2}'$ and $w_{6-1}'$, obtaining $(43)(52)(61)$.

Since $j=6$ is the end of the permutation, we are done. We have found that the input $w$ producing $w'$ is the permutation with cycle notation $(43)(52)(61)$.

Example 2
Let $$w'=435216.$$ We need to place parentheses, so we start by placing them at the beginning and end to get $(435216)$.

The smallest element of the first cycle is always $w_2'=3$.

The smallest $j$ such that $j>2$ and $w_j'<w_2'$ is $j=4$. Because $w_4'>w_5'$, we are in case $2$, and we have determined that $w_5'$ is the smallest element of the next cycle. Therefore, we place )( between $w_{5-2}'$ and $w_{5-1}'$, obtaining $(435)(216)$.

Since there does not exist $j>5$ such that $w_j'<w_5'=1$, we are done. We have found that the input $w$ producing $w'$ is the permutation with cycle notation $(435)(216)$.


gurgling sound in the power vent pipe

Question: My Furnace is a high eff furnace with a power vent. There is a gurgling sound in the power vent pipe, when it is  running.  I noticed that the vent slopes up then has a 90 elbow then slopes down before it goes outside.  I suspect water is being trapped should i fix this so the water flows back to the furnace so it can go into the drain.
Answer: There should be a slope so all the water can drain. With enough water in the pipe to gurgle the back pressure may cause the system problems including shutdown and early fan failure.
Comment: Just to be clear, down slope so the water will flow back toward the furnace and into the drain.
Comment: Yes that way the condensate will drain and not cause back pressure that can cause low flow and shut down the fire box or two much back pressure causing more pressure on the bearings in the motor leading to early motor failure.

gurgling sound in the power vent pipe


Android Studio quit unexpectedly

Question: My Android Studio is not opening anymore. giving me the error below:
Mac OS: OS X Yosemite version 10.10.5
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Error:

Process:               studio [10945] Path:
  /Applications/Android Studio.app/Contents/MacOS/studio Identifier:
  com.google.android.studio Version:               2.3 (AI-162.3764568)
  Code Type:             X86-64 (Native) Parent Process:        ??? [1]
  Responsible:           studio [10945] User ID:               502
Date/Time:             2017-04-04 11:25:14.467 -0300 OS Version:
  Mac OS X 10.10.5 (14F2109) Report Version:        11 Anonymous UUID:
  0DEE9C1D-5244-79A6-A842-6DDC55EC3113
Sleep/Wake UUID:       820EFB36-183A-4369-AE15-7858976DC7DA
Time Awake Since Boot: 17000 seconds Time Since Wake:       5600
  seconds
Crashed Thread:        0  AppKit Thread  Dispatch queue:
  com.apple.main-thread
Exception Type:        EXC_BAD_ACCESS (SIGABRT) Exception Codes:
  KERN_INVALID_ADDRESS at 0x0000303030353150
VM Regions Near 0x303030353150:
      VM_ALLOCATE            00000007c0260000-0000000800000000 [  1.0G] ---/rwx SM=NUL
  -->
      MALLOC_TINY            00007fa3e0400000-00007fa3e0600000 [ 2048K] rw-/rwx SM=COW
Application Specific Information: abort() called
Thread 0 Crashed:: AppKit Thread  Dispatch queue:
  com.apple.main-thread 0   libsystem_kernel.dylib
    0x00007fff8f4b2286 __pthread_kill + 10 1   libsystem_c.dylib
    0x00007fff8a0bd9a3 abort + 129

Complete:
https://docs.google.com/document/d/1cs0p-3vo6xfJH7GIs6TboP0_byqMoIfUbPR3hqhlXFQ/edit?usp=sharing
Thank you
Answer: Fixed the problem upgrading the OS to Sierra.

Android Studio quit unexpectedly


jQuery Draggable + Sortable - How to change the sortable items?

Question: I have a sortable list of videos initialised with the option:
items: '.videoBox:not(.isFirst, .isLast)',

The first and last videos are not sortable, neither are they draggable in any way - this is great!
This is connected to another draggable list of videos using the connectToSortable option. Some of the videos I want to be able to drag in between the isLast and isFirst videos (of which there are many) so for those I need these items sortable again, so I use:
start: function(event, ui) {
  if (// my test //)
  {
      $('#timeline').sortable('option', 'items', '.videoBox');
  }
},

This allows me to drag and drop amongst the items that were previously not sortable - great!
Now I want to revert the sortable to the initial set up once the drag has finished, so I put this in the draggable init:
stop: function() {
  if (// my test //)
  {
    $('#timeline').sortable('option', 'items', '.videoBox:not(.isFirst, .isLast)');
    $('#timeline').sortable('refresh');
    $('#timeline .videoBox.isLast, #timeline .videoBox.isFirst').draggable('destroy');
  }
},

This works great IF the draggable is not dropped into #timeline. However if it is dropped into #timeline then this callback does not seem to be called(?). I have added the exact same code into the sortable events: stop, update and deactivate, and while I can see that these callbacks are getting fired, the isFirst and isLast videos are still draggable.
However they are not sortable - so I think the problem lies with the .draggable('destroy') bit... Any ideas/suggestions?
Cheers,
Tom
Answer: I havent been able to fix or even identify the cause of the problem above. I have however found a workaround that seems fairly robust.
In the stop callback of the sortable init:
stop: function() {
    $('#timeline').sortable('option', 'items', '.videoBox:not(.isFirst, .isLast)');
    opts = $('#timeline').sortable('option');
    $('#timeline').sortable('destroy');
    $('#timeline').sortable(opts);
}

The first line sets the items option as I have been doing before. Then I save the sortable init options to a variable, destroy the sortable behaviour and reinitialise it with the correct options. This does what I want now - i destroys the draggable on the isFirst and isLast items). I have left the stop callback exactly as above in the draggable callback which is required for the case when the drag does not end up over the sortable.
Seems like a bit of a sledgehammer approach but struggling to find a nicer method. Be interested to know if anyone has any other suggestions though.
Tom


VBA Excel find date period in range and do calculations within

Question: I am performing a VB function to sort out cumulative amount within a specified period with different categories. The objective is for personnel account expenses.
For example, I have in a sheet "tmp" in column A some dates, in column B a category (eg. Salary, Transport ...) and in column C the values.
I want to define a function and I have tried to set:
Function Cumulatif(Categorie As String, Debut As Date, Fin As Date) As Double
    ' Do the sum of a category between a starting and ending date specified
    Dim Operations As Variant
    Dim SpecificSum As Double
    Dim i As Integer
    Operations = ThisWorkbook.Sheets("tmp").Range("A1:C3")
    For Each Row In Operations.Rows
        SpecificSum = 0
    Next
    Cumulatif = SpecificSum
End Function

But I don't really know how to get the values from another sheet and do the loop in the range to set this sum. Can somebody help me on this?
Comment: This way the function returns a #VALUE error ! I don't get why ?
Comment: If you want `Operations` to be assigned as a Range object, then you need to use `Set`.  If you really meant it to be a variant 2-D array (which you get by not using set), then that's not going to have a `.Rows` collection...
Answer:
The assigment to operations needs to be an object assignment, meaning: use Set (not Let/default).
Set Operations = ThisWorkbook.Sheets("tmp").Range("A1:C3)
You can get the values from the other sheet (assuming you mean "tmp") as follows
SpecificSum = SpecificSum + Row.Cells(1, 1)

I think you'd be better off having the function take an additional range parameter and supplying Sheet1!A as an argument; this way Excel will know when it needs to recalculate.
Function Cumulatif(Categorie As String, Debut As Date, Fin As Date, Operations As Range) As Double
    ' Do the sum of a category between a starting and ending date specified
    'Dim Operations As Variant
    Dim SpecificSum As Double
    Dim i As Integer
    'Set Operations = ThisWorkbook.Sheets("Sheet1").Range("A2:C3")
    For Each Row In Operations.Rows
        SpecificSum = SpecificSum + Row.Cells(1, 1)
    Next
    Cumulatif = SpecificSum
End Function

And call Cumulatif using such a formula:
=Cumulatif("hello9","10/1/2010", "10/31/2010",Sheet1!A2:A3)


Validation on SpringBoot API method does not work

Question: There's a createCar API below with a createCarVO as its request body. Usually, there's a @Validated annotation in front of the createCarVO parameter in the controller method. However, in my example below, the @Validated and the annotation are deferred to service layer, i.e. deferred to CarServiceImpl.createCar(). The validation is expected to work in CarServiceImpl.createCar(), but actually it doesn't.
@Validated
@RestController
@RequestMapping("/api/v1")
public class CarApiController {

    ...

    @PostMapping(value = "/cars", produces = MediaType.APPLICATION_JSON_VALUE)
    public CarVO createCar(@RequestBody CreateCarVO createCarVO) {
        CreateCarVO templateCarVO = templateService.prepareCarByTemplateId(createCarVO.getTemplateId());
        templateService.overwriteTemplate(createCarVO, templateCarVO);

        // Validation on templateCarVO is deferred from controller to CarServiceImpl
        return carService.createCar(templateCarVO);
    }
}

public interface ICarService {
    CarVO createCar(@Validated CreateCarVO createCarVO);
}

@Validated
@Component
public class CarServiceImpl implements ICarService {

    ...

    /*
     * Validation on createCarVO's attributes is expected to take effect.
     * However, it doesn't validate any attribute of createCarVO at all.
     */
    @Override
    public CarVO createCar(@Validated CreateCarVO createCarVO) {
        ...
    }
}

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import javax.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.Length;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CreateCarVO {

    public String templateId;

    @NotEmpty(message = "name cannot be empty")
    @Length(max = 64, message = "Max length of name is 64")
    public String name;

    @Length(max = 64, message = "Max length of producer is 64")
    private String producer;

    ...

    // Setters & Getters
}

Usually, if call the createCar API without a name, error like below is expected. However, in this example, there's none.
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [createCarVO.name,name]; arguments []; default message [title]]; default message [name cannot be empty]]
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:139) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) ~[spring-web-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:665) [javax.servlet-api-4.0.1.jar:4.0.1]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.2.12.RELEASE.jar:5.2.12.RELEASE]

So, if I insist on deferring the validation on CreateCarVO from controller to CarServiceImpl.createCar(), what shall I do? If there's no way to do it that way, is there any alternative solution?
Comment: Did you try by putting `@Valid` next to `@RequestBody` in controller?
Comment: If put `@Valid` next to `@RequestBody` in the controller, the validation will not be deferred to carService.createCar(templateCarVO). What I expect is that the controller will not do the validation, but deferred to carService.createCar(templateCarVO).
Answer: You can use @Valid like this and its simpler than others,
@RestController
@RequestMapping("/api/v1")
public class CarApiController {

    ...

    @PostMapping(value = "/cars", produces = MediaType.APPLICATION_JSON_VALUE)
    public CarVO createCar(@RequestBody @Valid CreateCarVO createCarVO) {
        CreateCarVO templateCarVO = templateService.prepareCarByTemplateId(createCarVO.getTemplateId());
        templateService.overwriteTemplate(createCarVO, templateCarVO);

        // Validation on templateCarVO is deferred from controller to CarServiceImpl
        return carService.createCar(templateCarVO);
    }
}

Comment: Actually, I hope to defer the validation from controller (CarApiController.createCar()) to carService.createCar(templateCarVO).

If add @Valid in CarApiController.createCar(), the validation is not deferred. So, I'm wondering how can I defer the validation to carService.createCar(templateCarVO).


Is React onClick more like a JavaScript addEventListener than like a standard JavaScript onclick attribute?

Question: In React is it better to think of onClick as setting an eventListener rather than as a standard JavaScript onclick attribute?
For example, consider these two code snippets, the first in standard JavaScript, the second in React:
<button onclick="activateLasers()">
  Activate Lasers
</button>

<button onClick={activateLasers}>
  Activate Lasers
</button>

In the top example, onclick is associated with an express CALL TO the activateLasers function.  However, in the React example, onClick is simply associated with the activateLasers function (the syntax is not expressly calling the function, even though behind the scenes it does call it).  In this sense, in spite of its name React's onClick is more like this conventional JavaScript code:
.addEventListener("click", activateLasers)

Or is this the wrong way to think about it?
Comment: Note that there's HTML's `onclick` attribute and the DOM's `addEventListener` method and React's `onClick` attribute.
Answer: Almost, it looks like this:
// mapEventToComponent implemented by React
document.getElementById("root").addEventListener("click", mapEventToComponent,...);

In React, event handlers (like onClick handler) are SyntheticEvent instances.
It helps achieve high performance by using event delegation. React attaches a single event listener to root of the document (and not to nodes themselves), when an event called, React maps it to the component.
Check it yourself!
const Component = () => {
  return <button onClick={() => console.log("hello")}>Click</button>;
};

Open dev tools
Fire the event to see if it's working.
Go to Event Listeners tab.
Check to which element all events attached.
Remove the click listeners from #root element.
Comment: Thanks! I think what I'm asking is more elementary. Which is whether it makes sense to regard React's onClick like the traditional onclick attribute one inserts in HTML.  They look nearly the same but are different.  The former attribute takes a value which is a reference to a function.  Whereas the latter attribute takes a value that's a call to a function.  This may seem obvious to an experienced React developer.  But the difference is a confusing adjustment to make for a newbie. IMO it might have been better for React to have called the attribute onClickFuncRef instead of onClick.
Comment: Not sure what kind of answer you expect
Comment: Again, thanks for all your feedback.  My question is a cognitive one:  does it make any sense to regard the React onClick attribute like a standard html onclick attribute?  Based on the feedback, the answer appears to be that it's best not to regard it this way.  This is because the value associated with a React onClick attribute needs to be a REFERENCE to a function.  In contrast, the html onclick attribute needs to be a CALL to a function as in this example: https://jsbin.com/zoxeruy/edit?html,js,console,output .
Comment: Yes, need to be a reference


Limit of function $(-0.1)^x$ as $x$ approaches infinity

Question: $\lim_{x\to\infty}(-0.1)^x = ?$
What does the overall function approach? I'm unsure if it approaches $0$ or if it's nonexistent
Comment: $f(x) = (-.1)^x$ doesn't have a very nice domain ...
Comment: "The overall function": how is it defined? Where is it defined? That should be the very first step: before asking for its answer, is your question well-defined?
Comment: You are going to have lots of problems with exponents of the form $\;x=\frac  m{2k}\;,\;\;m,k\in\Bbb Z\;,\;\;m\;$ odd.
Answer: In order to define $(-0.1)^x$ you must use a complex logarithm $\log z = \ln|z| + i\arg z$ with a branch cut that allows for negative numbers, say the natural branch with $\arg z \in (0, 2\pi)$.
Then you have
$$(-0.1)^x = e^{x \log(-0.1)} = e^{x(\ln|0.1|+i\pi)}$$
and consequently
$$|(-0.1)^x|=e^{x\ln|0.1|}=(0.1)^x \to 0 \ \mathrm{as} \ x \to \infty$$
Answer: It is $0$ because for every $\epsilon>0$ there exists $c>0$ such that $|(-0.1)^x|<\epsilon$ for $x>c$. Simply pick $c=\log_{10}(1/\epsilon)$.
Comment: What is $(-0.1)^{25.7}$? (In a way the answer is right but the explication is not sufficient in my opinion.)
Comment: How do you define $(-0,1)^x$ for, say, $x=1000+\frac{1}{2}$? The function given by the OP is not defined on any neighborhood of $\infty$, at least without much further detail -- e.g., on a restriction of the domain.


non-homogenous discrete difference equation

Question: I'm trying to solve the equation below:
$$ x[n] = ax[n-1] + b\theta^{n-1} $$
where $a,b,\theta,x[0]$ are known.
when $b = 0$ the problem is trivial:
$$ x[n] = x[0]a^n $$
Is this even possible to solve analytically or the numerical method is the only way to go?
Comment: It should have a solution of the form $x_n=C\theta^n$ for some constant $C$. Plug that into the recurrence, and solve for $C$.
Comment: Let $y[n]=x[n+1]-\theta x[n].$ Then use the recurrence to get $y[n+1]=ay[n].$
Comment: Oh sorry I meant $\theta^n$  @ThomasAndrews  $y(n)=x(n)/\theta^n$
Comment: @MtGlasser what do you mean by $\theta(n)?$
Comment: @GerryMyerson That is not correct.
Comment: @Thomas, on what grounds do you base that assertion? If you plug in $x_n=C\theta^n$, don't you get $C\theta^n-aC\theta^{n-1}=b\theta^{n-1}$? Doesn't this have the solution, $C=b/(\theta-a)$? Isn't $x_n=(b/(\theta-a))\theta^n$ a solution to the original recurrence?
Comment: A simple case was already presented in the user's ques ion. If $b=0,$ then $x_n$ is not of the form. Yes, $C\theta^n$ is a solution to the recurrence. The correct general solution  to the recurrence is $C_1a^n+C_2\theta^n.$ @GerryMyerson
Comment: Your specific $C$ doesn't even depend on $x_0,$ which it sort of has to do, since $x_0$ is an unknown constant, Indeed, the only solution possible is $C=x_0,$ not $C=b/(\theta-a).$ If $x_0(\theta-a)=b,$ maybe your answer is correct.
Comment: @Thomas, my answer is a particular solution to the recurrence $x_n=ax_{n-1}+b\theta^{n-1}$. When $b=0$ it gives the particular solution $a_n=0$ – but when $b=0$, we have a homogeneous recurrence, while the title of the question specifies non-homogeneous, so the case $b=0$ is irrelevant here. Now, if you want the general solution of the recurrence, you have to add in the general solution of the homogeneous equation. This gives $Ca^n+(b/(\theta-a))\theta^n$. And if you want the solution of the initial value problem, you have to evaluate $C$ from $x_0=Ca^0+(b/(\theta-a))\theta^0$. Continued.
Comment: "It should have a solution…" in response to a question, "It" is the question, unless you state otherwise. If you meant the recurrence, then your suggestion to solve for $C$ isn't much use, because that's not going to help answer the question. @GerryMyerson
Comment: Continued. That is, $x_0=C+b/(\theta-a)$, solve it for $C$, and you get the solution of the initial value problem.
Comment: This is the standard way to solve inhomogeneous first-order linear recurrences. You find a particular solution; you find the general solution to the homogeneous recurrence; if it's an initial value problem, you plug in the given data, and solve for the constant that comes up in the general solution. I didn't put all that in my first comment. I put enough to show OP how to do the first bit, which looked to be the bit OP was having trouble with. I'd rather OP do the work to get the full answer, than do it for OP.
Comment: I know how solve the general recurrence. (I posted an answer which I later deleted because I felt the question didn't warrant it. You should be able to read it.) My point was that your comment was misleading to the point of being wrong. @GerryMyerson And yes, this technique is the technique of linear recurrences, but this isn't a linear recurrence. Finding a way to make it a linear recurrence is the trick.
Comment: @Thomas, not a linear recurrence? $x_n=ax_{n-1}+b\theta^n$ is not a linear recurrence? I'm sorry, now you've lost me completely. What's your definition of linear recurrence?
Comment: @GerryMyerson a linear recurrence relation is of the form $$a_{n+k}=\sum_{i=0}^{k-1} c_ia_{n+i}.$$ This is basic terminology. The $b\theta^n$ makes the recurrence not a linear recurrence. But it can be shown that the sequence satisfies a linear recurrence. I'm sure you've encountered the concept, if not the term, but it is worth learning the term. Google it, you will find it used all over the place.
Comment: @GerryMyerson Wikipedia seems to call it homogenous linear recurrences, but here, for example, it is called just linear recurrence. https://brilliant.org/wiki/linear-recurrence-relations/
Comment: And here, @GerryMyerson https://mathworld.wolfram.com/LinearRecurrenceEquation.html
Comment: @GerryMyerson  In any event, you seem more interested in social domination than in recognizing the truth that your initial comment used "this" in a vague way that could easily mislead the OP to a wrong solution. I get that impulse, I really do. I've done it myself on occasion. Fallibility is sometimes unnerving. Best of luck!
Comment: @Thomas, good, we're making progress, now I know what you mean by "linear recurrence". So, what do you call something of the form $$a_{n+k}=p(n)+\sum_{i=0}^{k-1}c_ia_{n+i}$$ where $p(n)$ is a given function? When $p$ is not identically zero, I call it an inhomogeneous linear recurrence – what do you call it? [and I could do without the pop psychology – can we keep personalities out of this, please?]
Comment: As for citations, Grimaldi, Discrete and Combinatorial Mathematics, 2nd ed., p. 361, says, "$c_na_n+c_{n-1}a_{n-1}+\cdots+c_{n-k}a_{n-k}=f(n)$ is a linear recurrence relation". Brualdi, Introductory Combinatorics, p. 89, lists some equations, including $D_n=nD_{n-1}+(-1)^n$, and then says, "Each of these is an example of a recurrence relation." Tucker, Applied Combinatorics, p. 49, says, "The following equations display some of the forms of recurrence relations that we will derive to model counting problems in the chapter," and one of those equations is (continued)
Comment: (continued) "$a_n=ca_{n-1}+f(n)$ where $f(n)$ is some function of $n$."
Comment: @Thomas, please; if you don't call $D_n=nD_{n-1}+(-1)^n$ a recurrence relation, what do you call it?
Answer: The homogeneous have as solution
$$
x_h(n) = c a^n
$$
To find a particular solution we assume $x_p(n) = c(n) a^n$ and substituting into the complete recurrence we obtain
$$
c(n)a^n = a c(n-1)a^{n-1}+b\theta^{n-1}
$$
then $c(n)$ obeys the recurrence
$$
c(n)-c(n-1) = \frac{b}{a^n}\theta^{n-1} = \frac {b}{\theta}\left(\frac{\theta}{a}\right)^n
$$
and solving $c(n)$ we obtain
$$
c(n) = \frac{b}{\theta}\left(1+\frac{\theta}{a}+\cdots +\left(\frac{\theta}{a}\right)^n\right) = \frac{b}{\theta}\frac{\left(\frac{\theta}{a}\right)^{n+1}-1}{\frac{\theta}{a}-1}
$$
and then
$$
x(n) = x_h(n)+x_p(n) = c a^n + \left(\frac{b}{\theta}\frac{\left(\frac{\theta}{a}\right)^{n+1}-1}{\frac{\theta}{a}-1}\right)a^n
$$
Comment: Thanks. I managed to solve it by starting from the beginning and trying to find a pattern as n increases but this systematic approach was really helpful.


CMIS Workbench properties editor shows 3 cmis:name

Question: I want to edit the cmis:name of a document in CMIS Workbench, so I selected the document, opened its Properties tab (left window in the screenshot below), and double-clicked on cmis:name.
The Property Editor showed up (right window in the screenshot below), and surprisingly to me it contains 3 rows for the field cmis:name:

What is the difference between each of the three?
(remark: as you can see, the same happens for cmis:description)
Comment: How many versions does your node have ? (Just an idea)
Comment: @Akah: Just one version (1.0) it seems, as Alfresco Share shows "This document has no previous versions".
Answer: It is a bug in Alfresco.
I reported it at https://issues.alfresco.com/jira/browse/ALF-21974
The issue is currently marked as "In progress".


awk command while ((getline < "gpsoutput.tr") > 0 for constantly updating file contents

Question: I am currently using a G-STAR IV globalsat GPS which gives me the following output (which is coming from the GPS every 1 second) and I save this output by redirecting to a file name  "gpsoutput.tr". This file gets constantly updated each time it receives a GPS signal. The content of this file is as follows:
$GPGSV,3,2,10,14,43,184,,27,33,314,,29,21,152,,16,17,263,*7D
$GPGSV,3,3,10,24,10,092,,19,06,322,*79
$GPRMC,095827.000,A,2335.2440,N,05809.8432,E,0.55,103.38,091114,,,A*66
$GPGGA,095828.000,2335.2443,N,05809.8433,E,1,04,5.2,89.5,M,-34.7,M,,0000*46
$GPGSA,A,3,21,22,18,15,,,,,,,,,6.4,5.2,3.6*3C
$GPRMC,095828.000,A,2335.2443,N,05809.8433,E,1.21,102.44,091114,,,A*63
$GPGGA,095829.000,2335.2446,N,05809.8434,E,1,04,5.2,89.5,M,-34.7,M,,0000*45
$GPGSA,A,3,21,22,18,15,,,,,,,,,6.4,5.2,3.6*3C
$GPRMC,095829.000,A,2335.2446,N,05809.8434,E,0.92,102.44,091114,,,A*69
$GPGGA,095830.000,2335.2448,N,05809.8437,E,1,04,5.2,89.5,M,-34.7,M,,0000*40
$GPGSA,A,3,21,22,18,15,,,,,,,,,6.4,5.2,3.6*3C
$GPRMC,095830.000,A,2335.2448,N,05809.8437,E,1.25,102.12,091114,,,A*62
$GPGGA,095831.000,2335.2450,N,05809.8441,E,1,04,5.2,89.5,M,-34.7,M,,0000*49
$GPGSA,A,3,21,22,18,15,,,,,,,,,6.4,5.2,3.6*3C
$GPRMC,095831.000,A,2335.2450,N,05809.8441,E,1.47,101.80,091114,,,A*67
$GPGGA,095832.000,2335.2455,N,05809.8446,E,1,04,5.2,89.5,M,-34.7,M,,0000*48
$GPGSA,A,3,21,22,18,15,,,,,,,,,6.4,5.2,3.6*3C
$GPGSV,3,1,10,21,55,052,18,22,54,297,14,18,53,011,22,15,18,042,18*72
$GPGSV,3,2,10,14,43,184,,27,33,314,,29,21,152,,16,17,263,*7D
$GPGSV,3,3,10,24,10,092,,19,06,322,*79
$GPRMC,095832.000,A,2335.2455,N,05809.8446,E,2.36,100.07,091114,,,A*6D

this file ("gpsoutput.tr") keeps getting added with new lines each time it receives a GPS signal.
Now, I have a bash file which runs an awk program continuously to extracts the (speed), the (latitude, longitude) and the (UTC timestamp) in three different files. This is the bash script:
#!/bin/sh
echo "Starting GPS info gathering"
while true; do
    awk -F, -f gpsgetinfo.awk gpsoutput.tr

 done

Finally, my awk program is very simple which I want it to constantly read the latest record from the gpsoutput.tr file and extract the above mentioned infos, in the three separate files. the awk program (gpsgetinfo.awk) is as follows:
BEGIN {
    FS = ",";
    OFS = " ";

    while ((getline < "gpsoutput.tr") > 0) {

        if($1=="$GPRMC") {
                converted = $8*1.852;
                printf $4 " " $6 "\n" >> "data1.txt";
                printf "%.3f \n", converted >> "speed.txt";
                printf $2 "\n" >> "gpstime.txt";
        }

    }
}

END {
    fflush();
}

The problem is, that in my output files (data1.txt, speed.txt and gpstime.txt) from the awk program, the same output is repeating several times and within a few seconds, the file size is reaching to the size of Mega bytes. To make it clear. This is how my utc time output file looks:
095546.000
095547.000
095546.000
095547.000
095546.000
095547.000
095546.000
095547.000
095546.000
095547.000
095546.000
095547.000
095546.000

and it repeats for several 100 times in the file.
While the expected output in gpstime.tr should just be :
095546.000
095547.000
095548.000
095549.000
095550.000
095551.000

and so on.. since the gps signal is received every 1 second.
The gpsoutput.tr file where the nmea data is being saved, is just a few kbs, and without any recurrences in data.
Can anyone tell me . why the output files are having so many repeated values?  I have also tried using printf $4 " " $6 "\n" > "data1.txt"; (single > instead of >>) but didn't work for me.
Comment: How did you get the original, raw GPS data, output to your terminal (or `gpsoutput.tr`), in the first place? Where does it come from? Some additional utility/software?
Comment: Or did you just `cat /dev/input/gps1 > gpsoutput.tr`, or something like that? If not, maybe that information would help lead you to solve your problem somehow.
Answer: The problem is indeed what @Lekensteyn explained. Since your file is constantly growing, your awk will always repeat the lines it has already processed. Unfortunately, using tail -f is not a solution since that will go on for ever and awk will not print anything.
Instead, use the same script as suggested by @Lekensteyn but with > instead of >>:
#!/usr/bin/awk -f
BEGIN {
    FS = ",";
}
$1 == "$GPRMC" {
    converted = $8*1.852;
    print $4, $6 > "data1.txt";
    printf "%.3f \n", converted > "speed.txt";
    print $2 > "gpstime.txt";
}

You then run that script every second to re-create your output files:
#!/bin/sh
echo "Starting GPS info gathering"
while true; do
    ./gpsgetinfo.awk gpsoutput.tr
 done

Comment: thanks,, this works good..But , the file gets filled up and suddenly all the data gets blank for a couple of seconds, and again the file gets data into it. Is there a way to avoid the file from getting blank during running the shell script?  Since I am using another C program which is constantly taking data as input from these output files generated through the awk script..And if the file is empty,, my c program would return an error and terminate.. what can be done?
Comment: @Shezwan91 OK, what we have here is an [XY problem](http://meta.stackoverflow.com/questions/66377/what-is-the-xy-problem). Yes, this approach will recreate the file every time the script is run and that can break downstream functions. This is why you need to explain what your final aim is when asking instead of giving us only the intermediate steps. Anyway, I suggest you post a new question explaining everything you need to happen. For example, you might be able to run your C program only when the file changes by using `inotify` or `bash_script.sh && c_program`.
Answer: If the GPS data file only grows instead of overwritten, then you will write the same data over and over again, that is why you get duplicates.
You must somehow keep feeding new lines to awk. This can be done using tail --follow:
tail -f gpsoutput.tr | ./gpsoutput.awk

Your gpsoutput.awk should then be this executable script:
#!/usr/bin/awk -f
BEGIN {
    FS = ",";
}
$1 == "$GPRMC" {
    converted = $8*1.852;
    print $4, $6 >> "data1.txt";
    printf "%.3f \n", converted >> "speed.txt";
    print $2 >> "gpstime.txt";
    # Optional: add fflush() here.
}

Comment: I have tried running the above.. But the output files(gpstime.txt, data1.txt etc) are empty. no data is getting saved in them at all.


Calculate total for multiple entries to a field

Question: I have a database that looks like this:
Employee_id  dev_hours Pm_hours
1                2         2
1                3         3
2                3         3
3                2         1
3                1         1

How would I used php to find the total hours that each individual employee had worked on? For example employee 1 would have worked for a total of 10 hours and employee 3 worked for a total of 5 hours?
Comment: Clues: SUM(dev_hours + Pm_hours) and GROUP BY Employee_id
Comment: Would this be a MySql database?
Answer: You need to use SUM()and GROUP BY. Try:
SELECT Employee_id, SUM(dev_hours + Pm_hours) as total_hours FROM tbl GROUP BY Employee_id

Answer: A slight variation taken from w3 schools PHP guide here:
http://www.w3schools.com/php/php_mysql_select.asp
<?php
$con = mysql_connect("server","user","password");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT Employee_id, SUM(dev_hours + Pm_hours) as Hours FROM EmployeeTable GROUP BY Employee_id");

while($row = mysql_fetch_array($result))
{
  echo $row['Employee_id'] . " " . $row['Hours'];
  echo "
";
}

mysql_close($con);
?>


Is it ok to use a shower that just has the backerboard installed and not yet tiled?

Question: I'm trying to figure out the timing of redoing my shower. I'm looking at installing a new tub with a tile surround. I'd like to demo the current setup and install the tub and backerboard (and sealant) one weekend and then do the tiling the next weekend.
Since this is my only shower, can I use the shower after putting up the backerboard and sealing it without yet tiling and not mess up the backerboard?
Comment: Get a membership to a local gym, and shower at the gym. If you hang out and exercise a bit, you'll also be a bit healthier as well as clean. Or hang some sheets of poly to cover the walls while you shower. Make sure the seams overlap, and no moisture gets behind the poly.
Comment: See also [How soon can I use my shower that I recently grouted and tiled? Should it cure first?](http://diy.stackexchange.com/q/4980/2196)
Comment: take a bath instead
Answer: Given that you have a pan that is finished and given that your walls have either a membrane or a painted on membrane that is waterproof you could very lightly use the shower.  I would never endorse this if I was doing the job but if you are doing it yourself, then go ahead.  Make the showers short/light and make sure that it is bone dry before tiling.  (This is all given you have a waterproof membrane installed - the answer is no if you will be showering right on the backerboard.)
Answer: It's the soap scum and body oils that I'd be worried about.  Residues could affect the how the tile bonds to the wall.  Put up some plastic sheeting over the wallboard for the week.


Sum different items in two different columns

Question: I'd like to have two columns that show the sum of different items purchased. For example
DB Name: Purchases

CustomerID
Shirt

123
Red

123
Red

123
Red

123
Blue

123
Blue

The result I'd like to get is the following

CustomerID
Red
Blue

123
3
2

I am able to create one column but I am having difficulty creating two different columns.
Thank you.
Answer: Just use conditional aggregation.  This is particularly simple in MySQL:
select customerid,
       sum(shirt = 'Red') as red,
       sum(shirt = 'Blue') as blue
from t
group by customerid;

Here is a db<>fiddle.
The above uses a MySQL shortcut.  The general syntax uses case:
select customerid,
       sum(case when shirt = 'Red' then 1 else 0 end) as red,
       sum(case when shirt = 'Blue' then 1 else 0 end) as blue
from t
group by customerid;

Comment: @irishninja002 . . . I added a db<>fiddle with that *exact* code and it works fine.  Are you sure you are using MySQL?
Comment: Ok, that's what a tried but it's telling me that there is an incorrect syntax near ')'  but my code is identical to yours.
Comment: thanks @Gordon Linoff I was using Microsoft SQL server. The expanded query worked actually.
Comment: @irishninja002 . . . Is there a reason you unaccepted this answer?
Comment: I'm sorry if I did - this is only my second time on Stackoverflow. what you provided was very helpful. I thought I clicked the check mark to accept it.
Answer: Maybe you should complete the sum statement with that :
select customerid,
   sum(case when shirt = 'Red' Then 1 Else 0 End) as red,
   sum(case when shirt = 'Blue' Then 1 Else 0 End) as blue
from t
group by customerid;


Thermostat won't always start heater on its own

Question: I have a gas furnace that seems to work fine; it keeps the house warm when things are running as expected. Sometimes, however, we'll notice the house is getting cold.
The temperature on the thermostat is set to 68., When we check the temperature reading on the thermostat, it could be as low as 64. Normally, the heater would have kicked on well before that, so we change the thermostat from "Heat" to "Off" then back to "Heat" and the heat turns on immediately.
This makes us think that it's something with the thermostat itself, but it's quite the nuisance at night. It did this a couple of times last winter, and has been happening much more this year. We've noticed no problems during the summer with it turning on the AC.
Comment: Have you tried changing the battery?
Comment: It is possible it is the thermostat however more likely it is a problem with the furnace itself. Most modern furnaces will try to light 3 times and if they fail to light then turning the furnace off and on again will reset the furnace. It could be any number of problems. If your furnace has a diagnostic light look for the code it is flashing before you reset the thermostat. Some of the higher end furnaces will keep a record of the codes.
Comment: I had not, however, I just changed the batteries before typing this.
Comment: New batteries, same issue.
Answer: You need to preform a test that will tell you if the thermostat is bad or is the problem in the furnace.  If you can find a time when the t-stst is calling for heat and the furnace is not responding, at the furnace check to see if you have 24-volts on the white lead coming back from the t-stat.  If you do, the problem is in the furnace.  If not, the problem is in the thermostat.  These thermostats are mass produced with an emphasis on mass part.  They do fail.
Comment: I agree the problem needs to be narrowed down I was thinking of a flakey contact in the stat but a no light problem would cause this issue the control board needs to be checked prior to resetting the stat.+


Is there any penalty for losing your UAV in Multiplayer Rush?

Question: I love using the UAV in Bad Company 2 multiplayer Rush mode, it's great for taking out tanks or entrenched positions.  Sometimes, I get a little risky and it gets shot down pretty quickly.  I figure that it doesn't really hurt my team as long as I'm using it, because I'm not really dying and we don't lose a ticket.
Is there any penalty to losing a UAV in Rush mode other than having to wait for UAV respawn?
Answer: No particular penalty. You just lose the bonus it represents. It's really useful for spotting enemies and mark them so your teammates have intel information on the field. It's also useful as you say to attack tanks and soldiers with the mounted MG.
I usually succeed in keeping it alive the time my friends blow up up to 4 MCOM stations. The only drawback is that when it explodes, you have to run during a few minutes to join back the action which is now far away from your position :)


What is the difference between git rm and git restore?

Question: Since both those commands are used to remove files from staging area, what is the difference between in them?
Comment: The thing that looks like a magnifying glass at the top of your browser window is a search field.
Answer: A quick look at the documentation yields that git rm is used to remove a file from the working tree and from the git index (docs), whereas git restore changes the files in the working tree back to match how they are in the restore source (usually the most recent commit) (docs).
So, as the names suggest, git rm is to remove something and git restore is to restore how it used to be.
I'd recommend reading docs for questions like this.


Is there any reason to choose Naga over the Genie in Heroes IV?

Question: In Heroes IV one playing Academy must choose between the Genie and the Naga. But I have never actually bothered with Nagas.

Naga is slow on the adventure map, which means that I can make less in one move than if I have chosen Genies.
Genies can cast Create Illusion, finish many battles with the Ice Bolt very quickly, all without spending Hero's mana, and even one Genie can switch entire stacks off with Song of Peace. They are versatile, they can do everything. Naga, at the same time, can only melee, this makes taking battles without losses a lot harder.
Because Naga is slow on the battle map as well, some ways to transport them are needed, such as the Teleport spell. It's not good.
After all, Naga can be cloned if you need them and somehow get at least one in your army, or enemy army. Anyway, they are not even the nearly the best creature to be cloned.

But I have never actually played competitively, so I would like to know if there is any sense in choosing the Naga over the Genie. Any specific economical situation? Any specific enemies? Something else?
When you describe any situation where you consider Nagas good, please also tell me why do you consider them to perform better than Genies in such a situation.
Answer: Naga is in a bad spot. It's inferior to a genie in pretty much every way.
Even against magic immune enemies genies can just summon creatures to take hits, whereas you need to spend mana on nagas to get them into a fight and then you have a decent damage dealer.
That doesn't even account for strategies, where you split your genies into several stacks, using single genies to song of peace an opponent for several turns, while other creatures pick them off.
Nagas get the upper hand, once Genies run out of mana, but usually battles do not last long enough for that to make a difference. I always pick Genies over Naga 100% of the time.
But HoMM 4 is full of decisions like this. Cyclops vs ogre mage is another, where the ogre is so much weaker than the other choice, that you should never consider it. Griffin/Unicorn, Angel/Champion, Vampire/Venom spawn, Medusa/Minotaur, Gold Golem/Mage are other very lopsided matchups in favor of the first creature.
Comment: What's more important than a need to spend mana -- you need to spend turns casting stuff.
Answer: Personally, I've always been a naga fan. Combining them with a cast of haste or flight gives you a powerful shock unit that has the "No Retaliation" skill. Plus they are quite capable of taking a hit with 90 hp and 22 melee and ranged defense.
However, overall I would say it would depend on army comp, if you have magi, halflings, and titans, you would probably want nagas.


Problem while installing vlc player

Question: I can't install vlc player on my Ubuntu(14.04).
I have read this and try to run the commands, but while I run this command:
sudo apt-get install vlc

I got something like this:
    Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 vlc : Depends: vlc-nox (= 2.1.4+git20150226+r54594+19+11~ubuntu14.04.1) but 2.1.6-0ubuntu14.04.1 is to be installed
       Recommends: vlc-plugin-notify (= 2.1.4+git20150226+r54594+19+11~ubuntu14.04.1) but 2.1.6-0ubuntu14.04.1 is to be installed
       Recommends: vlc-plugin-pulse (= 2.1.4+git20150226+r54594+19+11~ubuntu14.04.1) but 2.1.6-0ubuntu14.04.1 is to be installed
E: Unable to correct problems, you have held broken packages.

What is the problem? Have you any Idea to solve this or Could you please tell me the right procedure by which I can install vlc media player?

Update:
After removing the PPA, this is the output of apt-cache policy vlc:
vlc:
  Installed:  (none)
  Candidate:  2.1.2-2build2
    Version table:
      2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
      2.1.2-2build2 0
        500 archive.ubuntu.com/ubuntu trusty/universe i386 Packages
      2.0.1-4 0
        500 archive.ubuntu.com/ubuntu precise/universe i386 Packages

And The command:
apt-cache policy vlc-nox vlc-plugin-notify vlc-plugin-pulse

gives me the following results:
vlc-nox:
  Installed: 2.1.6-0ubuntu14.04.1
  Candidate: 2.1.6-0ubuntu14.04.1
  Version table:
 *** 2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
     2.1.2-2build2 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
     2.0.1-4 0
        500 http://archive.ubuntu.com/ubuntu/ precise/universe i386 Packages
vlc-plugin-notify:
  Installed: 2.1.6-0ubuntu14.04.1
  Candidate: 2.1.6-0ubuntu14.04.1
  Version table:
 *** 2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
     2.1.2-2build2 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
     2.0.1-4 0
        500 http://archive.ubuntu.com/ubuntu/ precise/universe i386 Packages
vlc-plugin-pulse:
  Installed: 2.1.6-0ubuntu14.04.1
  Candidate: 2.1.6-0ubuntu14.04.1
  Version table:
 *** 2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
     2.1.2-2build2 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
     2.0.1-4 0
        500 http://archive.ubuntu.com/ubuntu/ precise/universe i386 Packages

Comment: You upgraded from 12.04 to 14.04? There are still the old 12.04 repositories left enabled. Run `sudo sed -i '/precise/d' /etc/apt/sources.list` to remove them from your configuration.
Comment: Try this first: http://askubuntu.com/questions/140246/how-do-i-resolve-unmet-dependencies-after-adding-a-ppa
Comment: Oh no its not working.
Comment: What did you try and what did you get as a response. Kindly edit your question and include that information.
Comment: I've run all the commands step by step according to the post but still unable to install the vlc.
Answer: Don't use the PPA, install vlc from the Ubuntu repositories.

Remove the PPA you have installed:
sudo add-apt-repository --remove ppa:videolan/stable-daily

Empty the package cache:
sudo apt-get clean

Update your package lists:
sudo apt-get update

Downgrade/install all vlc packages to/in the repository version:
sudo apt-get install --reinstall vlc=2.1.2-2build2 vlc-data=2.1.2-2build2 vlc-nox=2.1.2-2build2 vlc-plugin-notify=2.1.2-2build2 vlc-plugin-pulse=2.1.2-2build2

Depending on your Ubuntu version, you might currently (Nov 20, 2015) get a VLC version up to 2.2.1-3 on Wily (15.10). Older Ubuntu versions might have older VLC versions in their repositories.
You check the versions available for you with the command:
apt-cache policy vlc

An example output on my 15.10 64bit system would be:
vlc:
  Installed: (none)
  Candidate: 2.2.1-3
  Version table:
     2.2.1-3 0
        500 http://[YOUR REPOSITORY SERVER URL]/ wily/universe amd64 Packages

Comment: I have followed your instructions but still got the same problems....
and

'apt-cache policy vlc'

gives me the following info:

'vlc:
  Installed: (none)
  Candidate: 2.1.2-2build2
  Version table:
     2.1.6-0ubuntu14.04.1 0
        100 /var/lib/dpkg/status
     2.1.2-2build2 0
        500 http://archive.ubuntu.com/ubuntu/ trusty/universe i386 Packages
     2.0.1-4 0
        500 http://archive.ubuntu.com/ubuntu/ precise/universe i386 Packages'
Comment: That's strange. You get the exactly same error as above in the question? And the precise (12.04) repositories should not have been enabled. Anyway, please edit your question to provide new command outputs, the formatting gets destroyed in comments and it's harder to find. Add the output of `apt-cache policy vlc-nox vlc-plugin-notify vlc-plugin-pulse` to your question please and leave ma a comment here after you finished the edit. Thanks.
Comment: Oh, and run `sudo apt-get clean` and perform steps 2 and 3 of my answer again.
Comment: You need to downgrade the installed versions of these three packages from the version in the PPA to the version in the repositories: `sudo apt-get install vlc-nox=2.1.2-2build2 vlc-plugin-notify=2.1.2-2build2 vlc-plugin-pulse=2.1.2-2build2`. I edit my answer and insert steps 2 and 3.
Comment: I think vlc has installed now, but I still have some problem to run vlc. :(
Comment: What problem? Please describe, if it's related to the VLC installation, or ask a new question if it's different. Then also don't hesitate to accept my answer by clicking the grey tick button on the left of it. Also make sure you have read the [tour] page of AskUbuntu to learn a bit more about our site.
Comment: After finishing installation, I run command: vlc and it shows:
VLC media player 2.1.6 Rincewind (revision 2.1.6-0-gea01d28)
[0x834b910] main libvlc: Running vlc with the default interface. Use 'cvlc' to use vlc without interface.
[0x836f438] skins2 interface error: no suitable dialogs provider found (hint: compile the qt4 plugin, and make sure it is loaded properly)
[0x836f438] skins2 interface error: cannot instantiate qt4 dialogs provider
[0x836f438] [cli] lua interface: Listening on host "*console".
VLC media player 2.1.2 Rincewind
Command Line Interface initialized. Type `help' for help.
>
Comment: You need to downgrade the VLC package as well, it seems: `sudo apt-get install vlc=2.1.2-2build2`. After that it really should work.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/31863/discussion-between-shikhor-roy-and-byte-commander).

Problem while installing vlc player