Characterizing an unknown LTI system

Question: What are the best approaches to characterize an unknown discrete time LTI system? I believe one of the approaches is to input a known input and measure the output to find a transfer function. What are some more approaches to better characterize this black box system?
Comment: This is super broad. It's 90% of what the scientific field *system identification* is about. I know a library with literally multiple 100 kg of books on how to identify systems. You need to narrow things down, with a model of what it *might* be, and restrictions on what you can and can't do.
Comment: Giving an impulse input to your black box will give the impulse response of the system which can be used to calculate the output for an input x[n]
Answer: One option from the realms of adaptive filtering is the Least Mean Squares (LMS) filter depicted below:

The idea is you take the output of the unknown system, compare it with the output of your adaptive filter and minimize the difference by tweaking the filter coefficients, using a LMS algorithm. When the error $e(n)$ is zero (or more often, lower than a threshold you define) you found your unknown system's response.
There are countless resources where you can learn about LMS. In this case, given
the input vector: $$X(i) = [x(i) \space x(i-1) \ldots x(i-N+1)]^T$$ and the coefficients vector: $$W = [w_0 \space w_1 \ldots w_{N-1}]^T$$
The output of the adaptive filter is: $$\hat{y}(i)=X(i)^TW$$
Now define the cost function to be: $$e(i)^2 = \big(d(n)-\hat{y}(i)\big)^2$$
It can be shown that the gradient of the cost function with respect to the coefficients is:$$\hat{\nabla}(i) = \frac{\partial e(i)^2}{\partial W} = -2e(i)X(i)$$
Since the gradient points towards the maximum of the cost function you update the coefficients in the opposite direction: $$\hat{W}(i+1) = \hat{W}(i)-\mu\hat{\nabla}(i) = \hat{W}(i)+2\mu e(i)X(i)$$
where $\mu$ controls the adaptation speed. I've ignored a lot of details but this is the idea.
Note that the filter will produce a frequency response that is adapted to you input signal $x(n)$. It's not guaranteed for any other frequency. For example, in the response depicted below, my $x(n)$ is composed of 3 tones. You can see only at those particular frequencies does the filter (N=3,6,10) match the true response (H1(z)). So consider feeding it a wideband signal like white noise.

If you want to learn more you can check for example:
Wikipedia article
B. Widrow, Adaptive Signal Processing, Prentice-Hall, 1985
Answer: I think the best possible way to get the transfer function of a LTI blackbox would be giving complex exponential as input. Because complex exponential $Ae^{j\omega_0}$ are eigen functions of LTI systems. So output will be
$$
Ae^{j\omega_0} \rightarrow H(e^{j\omega_0})Ae^{j\omega_0}.
$$
If you have a reasonable idea of the LTI Blackbox, can restrict your $\omega_0$, to a range of frequencies. The magnitude response of output will be
$$
M(\omega_0) = |H(e^{j\omega_0})|A
$$
and the phase response will be
$$
\angle(\omega_0) = \angle(H(e^{j\omega_0})).
$$
If you have magnitude and phase response of output, you can easily remove the known input magnitude/phase to get the Black-box system's characteristics.

Characterizing an unknown LTI system


Serialize Java objects into Java code

Question: Does somebody know a Java library which serializes a Java object hierarchy into Java code which generates this object hierarchy? Like Object/XML serialization, only that the output format is not binary/XML but Java code.
Answer: Serialised data represents the internal data of objects. There isn't enough information to work out what methods you would need to call on the objects to reproduce the internal state.
There are two obvious approaches:

Encode the serialised data in a literal String and deserialise that.
Use java.beans XML persistence, which should be easy enough to process with your favourite XML->Java source technique.
Comment: The objects are java beans, so for all fields there are getters and setters. I don't care about deserialization, I just want to provide a way to help our developers with writing mocking code :)
Answer: I am not aware of any libraries that will do this out of the box but you should be able to take one of the many object to XML serialisation libraries and customise the backend code to generate Java. Would probably not be much code.
For example a quick google turned up XStream. I've never used it but is seems to support multiple backends other than XML - e.g. JSON. You can implement your own writer and just write out the Java code needed to recreate the hierarchy.
I'm sure you could do the same with other libraries, in particular if you can hook into a SAX event stream.
See:
HierarchicalStreamWriter
Comment: Or apply a XSL transformation to whatever XStream outputs and so generate java. whichever you're appeals more to you.
Answer: Great question. I was thinking about serializing objects into java code to make testing easier. The use case would be to load some data into a db, then generate the code creating an object and later use this code in test methods to initialize data without the need to access the DB.
It is somehow true that the object state doesn't contain enough info to know how it's been created and transformed, however, for simple java beans there is no reason why this shouldn't be possible.
Do you feel like writing a small library for this purpose? I'll start coding soon!
Answer: XStream is a serialization library I used for serialization to XML. It should be possible and rather easy to extend it so that it writes Java code.

Serialize Java objects into Java code


What Mathematical Object Does a "Functional Calculus" Correspond to Precisely?

Question: I'm somewhat confused on what specific mathematical object a/the Borel/Continuous/Holomorphic functional calculus corresponds to. Based on my understanding so far, I would say that it corresponds to some sort of mapping between a Banach algebra to the space of eigenfunctions of the operator in question. However, I haven't seen that definition in a text and everything I've read makes it seem more like a concept than an actual mathematical object. So what exactly is it? Also is there only one "Borel functional calculus" for a given class of operators or does each operator define it's own?
Comment: This wikipedia article seems to give a solid description of what a functional calculus is in general: https://en.wikipedia.org/wiki/Functional_calculus
Answer: In the three cases you ask about, a functional calculus of an element $x$ in some algebra $B$ can be seen as a algebra homomorphism $\Phi_x \colon A \rightarrow B$ between some algebra of functions $A$ (that contains complex polynomials) and $B$. When you impose more restrictions on $B$ and $x$, you get a larger functional calculus. More explicitly,

If $B$ is a Banach algebra and $x \in B$, the holomorphic functional calculus is an algebra homomorphism $\Phi_x \colon \mathcal{A}(\sigma(x)) \rightarrow B$ between the algebra $\mathcal{A}(\sigma(x))$ of holomorphic functions defines on a neighborhood of $\sigma(x)$ and $B$. This map extends the polynomial functional calculus in the sense that if $p \in \mathbb{C}[z]$ is a polynomial, then $\Phi_x(p) = p(x)$ where the right hand side is defined by plugging in $x$ into the polynomial $p$. In addition, if $f_n,f \in \mathcal{A}(\sigma(x))$ and $f_n \rightarrow f$ uniformly on compact subsets then $\Phi_x(f_n) \rightarrow \Phi_x(f)$ with respect to the norm topology on $B$. These properties determine $\Phi_x$ uniquely and we have a spectral mapping theorem that states that
$$ \sigma(\Phi_x(f)) = \sigma(f(x)) = f(\sigma(x)). $$
If $B$ is a $C^{*}$-algebra and $x \in B$ is a normal element, the continuous functional calculus is a $C^{*}$-algebra homomorphism $\Phi_x \colon C(\sigma(x)) \rightarrow B$ between the $C^{*}$-algebra $C(\sigma(x))$ of continuous complex-valued functions on $\sigma(x)$ (endowed with the supremum norm and the obvious conjugation) and $B$. Again, this map extends the polynomial functional calculus and also the holomorphic functional calculus and the spectral mapping theorem continues to hold.
If $B = \mathcal{B}(H)$ is the $C^{*}$-algebra of bounded operators on a Hilbert space $H$ (or, more generally, a von Neumann algebra) and $x \in B$ is a normal element, the Borel functional calculus is an algebra homomorphism $\Phi_x \colon B(\sigma(x)) \rightarrow B$ between the $C^{*}$-algebra $B(\sigma(x))$ of bounded complex-valued measurable Borel functions on $\sigma(x)$ (endowed with the supremum norm and the obvious conjugation) and $B$. Again, this map extends the polynomial functional calculus and also the continuous functional calculus. It preserves the involution $((f^{*})(x) = \overline{f}(x) = (f(x))^{*})$ and is continuous but not an isometry and the spectral mapping theorem fails to hold. It also satisfies a stronger continuity property analogous to the dominated convergence theorem

From the point of view I described above, each element $x \in B$ (for example, a normal operator in $\mathcal{B}(H)$) defines a functional calculus of its own. However, there are properties that connect the functional calculi of different elements. For example, if $x,y$ are normal commuting elements in a $C^{*}$-algebra, you can define a joint continuous and Borel calculus on the space of continuous/Borel measurable and bounded functions on the joint spectrum of $x$ and $y$ which is a subspace of $\sigma(x) \times \sigma(y)$. In this way you can show for example that if $x,y$ commute then so does $f(x),g(y)$ and so on.
Comment: Can't thank you enough..great answer
Comment: @Pseudo-IntellectualBS: You're welcome! Note that I've edited slightly slightly my answer for part $(3)$ as you need some more conditions on the algebra $B$ for the Borel functional calculus to be well-defined. It works if $B = \mathcal{B}(H)$ or a von Neumann algebra but not in general.


Why does voltage not increase when batteries are connected in paralell?

Question: Having seen this question often on this platform, but never read a statisfying answer.
Comment: What questions have answers you aren't satisfied with? Maybe someone could clarify or improve an answer. If we don't know what your confusion or dissatisfaction is, we probably can't help. Don't make us guess!
Comment: It really boils down to the Kirchhoff's 2nd law. Try drawing a simple diagram with one resistor and two batteries in parallel.
Comment: What kind of satisfaction are you looking for? Because it's the same reason that two columns of of water side by side doesn't increase their height or pressure, whereas stacking the columns will.
Answer: First of all, you should write your questions in a clear manner. It isn't clear what voltage difference you are talking about, whether there is an emf source or not etc.
But in general note that the term "parallel" in the context of electric circuits implies that the elements that are parallel have the same potential difference between their terminals. To elaborate:
Kirchoff's 2nd Law states that the voltage differences through a loop should add up to 0 meaning a charge should have the same potential energy that it started with when it comes back to its initial position. Note that this takes both energy loses through circuit elements and gains through emf sources into acount.
When you connect two capacitors in parallel and loop through them you would see that V1-V2=0.

This means when you connect another capacitor it doesn't increase the voltage but you provide "extra space" for the charges to go. Since they are less dense, the same amount of charge will create a smaller voltage across the capacitors.
Or if you connect a battery, since there is more "space", you can store more charge using an identical battery.
This "space" is the capacitance of the capacitor and it determines how much charge it will hold for a certain voltage. And when you add another capacitor, you increase this space. To be precise, the equivalent capacitance value is the sum of the capacitances of our original capacitors.


Can I format the Google Docs Table of Contents to only include certain headers?

Question: I would like to have the Table of Contents only include Heading 1 and not any of the others.
Is there a way to set the Table of Contents to exclude the rest of the headings?
Answer: Unfortunately Google Docs does not support hiding specific heading levels.
The only "solution" would be to change the headers you want to hide to the "Normal" style, then manually set the font formatting for each heading.

The only way to avoid all headings from being added to the TOC is to manually apply the style you want rather than using the set styles. Change those headers to "Normal" style by select each one individually and pressing Ctrl + \ (Control plus the backslash key). This will remove the formatting. Then manually add the point size, font, and bolding that you want.
To easily copy formatting from one place to another, you can use the Paint Tool. So once you manually change one heading, you can use the Paint Tool to change others that are the same level heading.
- Source: Google Docs Forums: How to show only Heading 1 in table of contents
Comment: The links are broken, and apparently the answer is obsolete.
Comment: you can also use the "subtitle" format
Answer: What I did to solve the problem which is probably doc specific, but I was using H1 through H3, what would have been H4 I didn't want to show up in the TOC.  I converted all the H4's to Subtitles, then styled Subtitles the way I wanted it.
Subtitles don't show up in the TOC.
How to convert all headings into another heading:
Answer: The previous answers suggests setting the style of headers to "Normal" and manually setting their style to look like a header. If you do so, you will lose the ability to link to that header from within the document.
It looks like you can actually manually delete items from the table of contents. I think that's a simpler approach.
Comment: Yet then you'll have to do this each time you update the table of content.
Comment: Also, when inserting the table of contents, the page numbers are calculated. So if your table of contents with the extra headings is moving things around, the page numbers will be wrong after deleting the extra lines.
Answer: Table of contents in Google Docs really is very half baked.
The only way to select header levels or to change the formatting from defaults is to REDO any such action(s) MANUALLY after every time the table has been updated. But, to the point made by "Laura" earlier in this thread, that also does not work as the page numbering is calculated right after the table of contents have been inserted and is thereby impacted by the height of the table in its default format. So here is (sadly) what you need to do to have a controlled look of your Google Docs table of content as far as I have been able to take it:

Finish your text.
Insert an empty page for as a place holder for the table of content at the desired place in the document.
Append a blank page after the very last character of the document and insert the table of content there
Do whatever modifications necessary to the table of content (manually)
Manually cut the updated table of contents from the last page and paste it to the previously created place holder page.

This works but it makes you cry... :(
Answer: From what I can, tell this action is impossible on Google Docs, as other answers have mentioned. However, it would appear that there is another way if you have access to Microsoft Word:
Export the document into a .docx from Google Drive, which can be done when selecting what form you wish to download the document in. Then open this in Word and alter the table of contents using the following guide: https://support.office.com/en-us/article/format-or-customize-a-table-of-contents-9d85eb9c-0b55-4795-8abb-a49885b3a58d#layout

Guide Outline:

Select the drop down list from References>Table of Contents from the top bar.
Select Custom Table of Contents... from the list.
To change the number of levels displayed in your table of contents, click Show levels, and then click the number of levels you want.

I haven't tested this so I'll edit the answer with more feedback.
Answer: Yes, there's a workaround for this, and you can keep your heading structure.

At the top of your doc, write out the text that you want to show in your table of contents. For example Chapter 1, Chapter 2
Select the first phrase, and make it a hyperlink.
You'll see options for the link, including selecting an existing heading.
Answer: 2023 update: Google has announced this feature in the Google Workspace Updates blog post dated March 20, 2023: Improvements to content organization in Google Docs
The blog introduces Include and indent headings based on levels and has a visual walkthrough, but here are the steps:

Click your TOC and a tab will appear to the left with a refresh icon and three dots.  Click the three dots, then more options.

Expand Heading Levels in the right sidebar and select only the heading levels you want.

Note: I was able to set heading levels in the table of contents successfully on March 30, 2023, but the feature may not yet be rolled out to your instance.
Additional new features introduced are:

Toggle between three default styles
Toggle page numbers
Toggle tab leader styling (adds lines between a heading and the page number)

Google Docs help: Add, change, or delete a table of contents
Comment: this is perfect and should now become an accepted answer to the question!
Answer: 5 years later, and there still isn't an option to limit the heading levels, so I am putting my two cents in.
This solution still requires the manual deletion of unwanted lines at the end of the writing process, but at least it maintains proper page numbers in the TOC.
Since Google Docs let you decide where to put the TOC, you can use this to avoid the page numbers being off at the end. The solution that worked for me was this:

Finalise your document
Add a placeholder (e.g. blank newlines) at the place in the document where you eventually want your TOC to be. The placeholder needs to take that many pages as the final version of TOC will consume – this will probably take a bit of trial-by-error guessing.
Generate the TOC at the end of the document.
Edit it the way you want (that is, remove the unwanted headings etc).
Finally, replace the placeholder with the generated TOC. This way the page numbers will remain correct.

Link to original source: Customize the Table of Contents in a Google Docs Document
Answer: Here's what I have come up with to make a TOC that uses only one specific heading style. It works pretty well and I included the code (onOpen) that makes this a custom function that appears at the top with the document menu bar.  So once you have this code tweaked for your document, you can actually run the function from the document and not go back to the script.
Note you have to use Style sheets (and any headers you want) and you must first create/refresh a Google TOC first.
WARNING:  These items in ANY HEADING STYLE will cause Script Failures:
Parentheses, blank line, space(s) at end of line, Horz Rule in Heading style, etc.
I could probably catch these with a try{} function but haven't messed with that enough to go forth with it.
Here is the typical message I put at top just as a reminder of how to build the specific TOC.
"Specific HEADING TOC" will fill-in above this line – Cut & Paste to Desired Location
Heres the code
function onOpen() {
  // will need to set up a trigger (alarm clock) to make this run on Opening the doc or refreshing it
  var docId = DocumentApp.getActiveDocument().getId().toString()
  var doc = DocumentApp.openById(docId);

  // create a custom menu item at the end of the menu row of the doc (avoids having to "run" through this script)
  var ui = DocumentApp.getUi();
  ui.createMenu('CustomFunct')  // note, no semi-colons at the end of each ".add____( )" below
      .addItem('Heading2 Only TOC -- "As Is" Order', 'menuItem1')
      .addItem('Heading2 Only TOC -- "Reverse" Order', 'menuItem2')
      .addSeparator()
      .addItem('Heading3 Only TOC -- "As Is" Order', 'menuItem3')
      .addItem('Heading3 Only TOC -- "Reverse" Order', 'menuItem4')

      /* // Saving this in case you would expand the menu item with other functions and/or submenus
      .addSeparator()
      .addSubMenu(ui.createMenu('Sub-menu')
          .addItem('Temp Sum Menu Item', 'menuItem5'))
      */
      .addToUi();
}

function menuItem1() {DocumentApp.getUi(); parseText("As Is","HEADING2");}
function menuItem2() {DocumentApp.getUi(); parseText("Reverse","HEADING2");}
function menuItem3() {DocumentApp.getUi(); parseText("As Is","HEADING3");}
function menuItem4() {DocumentApp.getUi(); parseText("Reverse","HEADING3");}

function menuItem5() {
  DocumentApp.getUi()
     .alert('You need to create a script function for this submenu item!'); // just saving this as a reminder
}

function parseText(indexOrder,headStyle) {
  var docId = DocumentApp.getActiveDocument().getId().toString();  // Use this line when access the CustomFunct menu item
  var doc = DocumentApp.openById(docId);

  // Define the search parameters
  var searchElement = doc.getBody();
  var searchParas = doc.getBody().getParagraphs();

  // Look thru ALL Paragraphs to LOCATE AND SAVE all of the links and anchor points based on Heading Style
  var urls = [];
  var urlsText = [];
  for (var i = 0; i < searchParas.length; i++) {
    // Get values for the NEW TOC using only "headStyle" Styles (see UI menu items above)
    // Note: items in any HEADING#'s that cause this to fail:  parentheses, is a blank line, space at end of line, Horz Rule in any Heading style, etc.
    if (searchParas[i].getHeading() == headStyle) {
      var searchedText = searchElement.findText(searchParas[i].getText());
      var dropParens = searchParas[i].getText();
      var getAnchor = searchedText.getElement().asText().getLinkUrl(searchedText.getStartOffset())
      if (dropParens.indexOf("/##/") == -1){
        urlsText.push(dropParens); // builds the array of link text
        urls.push(getAnchor); // builds the array of link anchors
      }
    }
  }

  // Inserts the NEW TOC at the top of the Document -- then you can copy/paste to a location of your choice
  for (var i = 0;i<urlsText.length;i++) {
    if(indexOrder == "Reverse"){var indexToUse = i;} // Produces a TOC in the reverse order as they are in the document
    if(indexOrder == "As Is")indexToUse = urls.length-1-i;  // Produces a TOC in the order they are in the document

    if (i==0){doc.getBody().editAsText().insertText(0,"\r");doc.getBody().editAsText().insertText(0,"\r")}

    doc.getBody().editAsText().insertText(0,urlsText[indexToUse]).setLinkUrl(0,urlsText[indexToUse].length,urls[indexToUse])
    doc.getBody().editAsText().insertText(0,"\r")

  /* Adapted from --> https://stackoverflow.com/questions/32602495/how-to-add-a-hyperlink-in-a-google-docs-using-a-google-script
    var text = "link text\n";
    var url = "www.google.com";
    DocumentApp.getActiveDocument().getBody().editAsText().insertText(0, text).setLinkUrl(0, text.length, url);
  */
  }
  doc.getBody().editAsText().insertText(0,"TOC using only " + headStyle + " (in '" + indexOrder + "' Order)\r")
}

Answer: I have really tried to achieve a better solution for this and got a bit further. I think it is as far as you can get without Google addressing the shortcomings properly. My solution is not great but not entirely appalling. The customized TOC is designed in a separate Google Doc (like a template) and is fulfilled with data and added to the actual document by a script.
Shared a google doc that explains the solution and that also can be used for testing the solution.
https://docs.google.com/document/d/1mlJ3rI04isifgncHHP0VWhO8NEmt395Re8lapuTcG3w
The code here (also in the doc):
function onOpen() {
  DocumentApp.getUi()
    .createMenu('My menu')
    .addItem('Custom Table of Contents', 'customTableOfContents')
    .addToUi();
}

function customTableOfContents(){
  var ui = DocumentApp.getUi();

  //fetch content for the toc
  var textDoc = DocumentApp.getActiveDocument();
  var tocData = getTocData(textDoc);
  if (!tocData.content) {
    ui.alert(tocData.alert);
    return;
  }

  //fetch the "style sheet" for the toc and render the content accordingly
  var styleDoc = DocumentApp.openById('1chKuIuJDpQJEcHqn2AW1-W6exDyiknKLrmBXX-3KEDs');
  var renderResult = renderToc(textDoc,styleDoc,tocData.content);
  if (!renderResult.success) {
    ui.alert(renderResult.alert);
    return;
  }

  //clean up empty rows at document end
  var textDocBody = textDoc.getBody();
  var lastElement = textDocBody.getChild(textDocBody.getNumChildren()-2);
  while (lastElement.getText() == "") {
    textDocBody.removeChild(lastElement);
    lastElement = textDocBody.getChild(textDocBody.getNumChildren()-2);
  }

  if (tocData.dataCollectionStep == 1) {
  //position cursor at the end of the document, prompt user to insert a native table of content
  //and to run the function again.
    var position = textDoc.newPosition(textDocBody.getChild(textDocBody.getNumChildren()-1), 0);
    textDoc.setCursor(position);
    ui.alert(tocData.alert);
    return;
  }

  //we are done!
  if (renderResult.customTocPosition > 0) {
    var position = textDoc.newPosition(textDocBody.getChild(renderResult.customTocPosition), 0);
    textDoc.setCursor(position);
  }
}

function getTocData(doc){
  //build an array of data for the toc
  var docBody = doc.getBody();
  var paragraphs = docBody.getParagraphs();
  var statusMessage;
  var nativeToc;
  var dataCollectionStep = 0;
  try {
    //if a native table of contents exists we assume we are running the function for the second time
    dataCollectionStep = 2;
    nativeToc = docBody.findElement(DocumentApp.ElementType.TABLE_OF_CONTENTS).getElement().asTableOfContents();
  } catch(e) {
    //if no native table of content exists we assume we are running the function for the first time
    dataCollectionStep = 1;
    statusMessage = 'Table of content has been generated but is missing page references and interactive links.' + String.fromCharCode(10) +
      'To add the missing parts, please select "Table of content" from the "Insert" menu.' + String.fromCharCode(10) +
      'Then run the "Custom table of content" again.';
  }

  var customTocData = [];
  for(var i=0;i<paragraphs.length;i++) {
    if (paragraphs[i].getText().trim() == "") continue;
    if (paragraphs[i].getHeading() == DocumentApp.ParagraphHeading.NORMAL) continue;
    if (paragraphs[i].getHeading() == DocumentApp.ParagraphHeading.SUBTITLE) continue;
    if (paragraphs[i].getHeading() == DocumentApp.ParagraphHeading.TITLE) continue;

    if (dataCollectionStep == 2) {
      //extracting url-data and page numbers from the native table of contents
      var nativeTocRecord = nativeToc.getChild(customTocData.length).asParagraph();
      var textAndPage = nativeTocRecord.getText().split(String.fromCharCode(9));
      if (paragraphs[i].getText().trim() != textAndPage[0]) {
        statusMessage = "Error at row " + i + String.fromCharCode(10) + 'Please manually refresh the table of contents and try again!';
        return {
          content: null,
          dataCollectionStep : dataCollectionStep,
          alert: statusMessage
        };
      }
    }
    customTocData.push({
      heading : paragraphs[i].getHeading(),
      description : paragraphs[i].getText(),
      hyperlink : (dataCollectionStep == 2) ? nativeTocRecord.getChild(0).asText().getLinkUrl(2) : "",
      page : (dataCollectionStep == 2) ? textAndPage[1] : "N/A"
    });
  }
  //removing the native table of contents
  if (dataCollectionStep == 2) docBody.removeChild(nativeToc);
  return {
    content: customTocData,
    dataCollectionStep : dataCollectionStep,
    alert: statusMessage
  };
}

function renderToc(textDoc,styleDoc,tocData){
  var textDocBody = textDoc.getBody();
  var styleHeaderText = styleDoc.getBody().getChild(0).getText().trim().toUpperCase();
  var styleTable = styleDoc.getBody().getChild(1).asTable();
  var customToc;
  var tocIdx = -1;

  var featuredHeadings = [];
  for (var i=0;i


OSM tiles offline display using c++

Question: I have openstreetmap tiles for offline (png images), how can I display these images (tiles) on my application with zooming and rotation functionality as on openstreetmap.org using c++?
Comment: Welcome to GIS.SE .Please take the [tour] to learn how to ask as question. Your question as it stands is too broad for this format.
Comment: crosspost: https://help.openstreetmap.org/questions/47949/display-slippy-osm-tiles-offline-c
Comment: legitimate question
Comment: not a crosspost, this was first. and it's another website
Answer: You could use CartoType (http://www.cartotype.com/index.html). The library supports map rendering, routing, turn by turn navigation, and geocoding.
For a comprehensive list of frameworks visit http://wiki.openstreetmap.org/wiki/Frameworks. There are numerous other frameworks in the OSM environment depending on your needs.
Comment: :Thanks for your answer. I need a osm map tiles viewer (as on openstreetmap.org) for my application on c++, but tiles (png images) should be loaded not via Internet, but from my local directory. Also I should add some graphics(polylines, rectangles etc.) to this map using C++. How can I do it? Thanks.
Comment: You can accomplish all of your requirements (incorporating offline tiles, drawing features) with cartotype. Visit the features page (http://www.cartotype.com/features.html) for more information or contact the developers (http://www.cartotype.com/contact.html). Your question "How can I do it" is to broad you should be a bit more concise.
Answer: As far as I have understood your question is mainly about zooming and rotating a png-image in C++. If this is correct the problem boils down to finding the proper image-processing library. I can suggest libpng for displaying, but for manipulation (including rotation) you may want to have a look at openCV or at Magick++.
Answer: Marble is open source, written in C++ and supports online and offline tile viewing. Apart from that there is a long list of desktop software for OSM in the OSM wiki.
Answer: Maybe you van also have a closer look at libosmscout.
(found via Frameworks in the OSM wiki)
Not sure myself whether it has tile display, but at least own offline vector map rendering in C++.

OSM tiles offline display using c++


MongoDB: Lost dry run election due to internal error

Question: I am trying to solve a Replication issue here in MongoDB 4.2, but I can no longer get my Primary server back to primary, it always stays in SECONDARY mode. I've tried several types of solutions, like this Or here
But without success.
In the logs, I came across these messages:
<code> Scheduling remote command request for vote request: RemoteCommand 729 -- target:mongo2:27021 db:admin cmd:{ replSetRequestVotes: 1, setName: "MyReplicaSet", dryRun: true, term: 2, candidateIndex: 0, configVersion: 125668, lastCommittedOp: { ts: Timestamp(1570799675, 1), t: 2 } }
 2019-10-11T11:17:25.041-0300 I  ELECTION [replexec-2] VoteRequester(term 2 dry run) received an invalid response from mongo2:27021: NotYetInitialized: no replset config has been received; response message: { operationTime: Timestamp(0, 0), ok: 0.0, errmsg: "no replset config has been received", code: 94, codeName: "NotYetInitialized", $clusterTime: { clusterTime: Timestamp(1570799675, 1), signature: { hash: BinData(0, 0000000000000000000000000000000000000000), keyId: 0 } } }
 2019-10-11T11:17:25.041-0300 I  ELECTION [replexec-2] not running for primary, we received insufficient votes
 2019-10-11T11:17:25.041-0300 I  ELECTION [replexec-2] Lost dry run election due to internal error
</code>
How to fix this?
Answer: It looks like this problem was fixed in mongodb 4.2.10: https://jira.mongodb.org/browse/SERVER-47263


How to reset munin graphs

Question: I'd like to reset all graphs for a certain host in Munin. Anyone who knows how I can do this?
Comment: The simplest resolve, is waiting for a year, this is a time when data is by default completly rotated :) But how to real reset data, descriptions you have bottom in answers :)
Answer: Munin data is stored in Round Robin Database files (.rrd).  These are stored under /var/lib/munin.
Each host and hostgroup will have it's own subdirectory under /var/lib/munin
Delete the .rrd files under the hostname in question, and your data will be zeroed out.  Graphs will be re-generated after a few minutes.
Comment: Notice, /var/lib/munin is defined by property  dbdir in /etc/munin/munin.conf . dbdir /var/lib/munin is the default set, but can be changed. Real path to RRD files is similar to URL path to graphical draw on web interface.
Answer: Or alternatively if you just want to fix the data in the RRD files (for example spike on the network graph on the server reboot), just run:
rrddtool dump /var/lib/munin/xy/z.rrd >z.xml

edit the data in xml file (fix big values, but remember they are in scientific notation)
and then just re-create the RRD file:
rrdtool restore z.xml x.rrd

and overwrite the original RRD with this new one. Using this, you can fix the values and still preserve your old data.
EDIT: You can find detailed description and howto here: https://guide.munin-monitoring.org/en/latest/howtos/remove-spikes.html
Comment: spikes is problem with badly constructed  node plugin.
Answer: Yes, delete all the *.rrd files in the folder where munin generates the graphs (where the .html files are). /var/lib/munin/xyz/. It's defined in your munin.conf (dbdir).
The rrd files are regenerated on the next run.
Answer: You should also remove the html files that have been created. They are usually located under /var/www/munin/. In that directory, you will find your hostgroup directories. delete the .png files and the .html file of the graph you want to reset.
Comment: The files might indeed be anywhere, if you installed from source, they are likely to be in `/opt/munin/www/docs//`. You especially might want to delete the web files (and the directory) if you have messed with the node's plugins and your new definitions refuse to appear in the host's web page.
Comment: What for removing those files? Main question is, how to reset draw data, not removing or renaming/moving monitored host.
Answer: I remove a single type graph with next at master server:

Login as root:

sudo su

Backup current status:

cp -rp /var/lib/munin /var/lib/munin.bak

Search and confirm all files to delete for plugin graphs nginx_*:

find /var/lib/munin -name *nginx_*.rrd

Confirm all files to delete!
Delete graph files for plugin nginx_*:

find /var/lib/munin -name *nginx_*.rrd -exec rm {} \;

How to reset munin graphs


How much money can I send to India without paying taxes?

Question: I need to send $28000 to my brother in India. I pay the necessary federal and state taxes in the U.S. Can I send this money in a period of one calendar year without paying gift tax? Can I send $14000 each from me and my wife to my brother and his wife respectively? My wife does not earn any income.
Comment: You can send $14K to your brother and $14K to your sister-in-law in two separate checks without incurring gift tax in the US. Or, you can send $14K to your brother and your wife can send $14K to your brother (again in separate checks) without either of you incurring any gift tax. Gifting does not require earned income, just assets.
Comment: @DilipSarwate Asking because I don't know the answer, and I can see it may affect the OP's plans: You say "_Gifting does not require earned income, just assets_", which presumably leaves the wife free to gift any assets _she owns_. From the tone of the question, it seems probable that the $14,000 she might gift would have been originally earned by the OP. Under US (marriage/tax) law, is that sufficient to count as "her assets" (e.g. "_what's mine is yours, what's yours is mine_") or would he have to "gift" the money to her (and if so, would "chain-gifting" cause a problem?)
Comment: @Tripe, even if the husband's and wife's property are considered separate, one is allowed to transfer assets in any amount to one's spouse, so there is no problem. Exception: apparently there is a $149,000 limit in the case of a spouse who is not a U.S. citizen.
Comment: @Tripe, even if the husband's and wife's assets are considered separate, a gift from either of them can be treated as a gift from both of them, as described in my answer.
Comment: You don't mention the reason for the gift, so I want to point out the following from the Form 709 instructions: "The gift tax does not apply to an amount you paid on behalf of an individual to a person or institution that provided medical care for the individual. The payment must be to the care provider." See those instructions for more details. (https://www.irs.gov/pub/irs-pdf/i709.pdf)
Comment: Josh is the intent of this transfer a gift. i.e. you are not expecting anything back from your brother. He is free to spend this as he wishes.
Answer: Combining information from both @Dilip Sarawte and @prl:
You have (at least) two options:

You can send $14k to your brother and $14k to your sister-in-law as two separate cheques without incurring Gift Tax liability in the US.

Both you and your wife can send $14k to your brother (as two separate cheques) without either of you incurring Gift Tax liability. In your wife's case, gifting does not require earned income, simply available assets.
(Even if the husband's and wife's property are considered separate, and the money the wife wants to gift was originally earned by the husband, there is no problem as you are allowed to transfer assests in any amount1 to one's spouse).

More information of U.S. Gift Tax can be found at this IRS page, including a link to the Instructions for Form 709 (PDF). In most cases, you would only need to file this form if a gift would attract Gift Tax, but there are some exceptions.

1 There is a $149,000 limit in the case of a spouse who is not a U.S. citizen.
Answer: Yes, in 2018, you can send $30,000 to both your brother and his wife ($60,000 total) without paying gift tax, as long as you and your wife are both U.S. residents (or citizens). It is not necessary to send separate gifts from you and your wife, but you may need to send separate gifts to your brother and his wife.
From the instructions for Form 709:

If you and your spouse both consent, all gifts (including gifts of
  property held with your spouse as joint tenants or tenants by the
  entirety) either of you make to third parties during the calendar year
  will be considered as made one-half by each of you if all of the
  following apply.

You and your spouse were married to one another at the time of the    gift.
If divorced or widowed after the gift, you did not remarry    during the rest of the calendar year.
Neither of you was a    nonresident not a citizen of the United States at the time of the    gift.
You did not give your spouse a general power of appointment    over the property interest transferred.

If this choice is made, it applies to all gifts made during the year.


Sharepoint Online, Power apps multiple forms on different screens, does not work

Question: I need help, I have an application that needs to have multiple different screens for users to fill out a `` New Employees '' form I have the forms on different screens and this is causing me a serious problem, because in PowerApps, on each separate screen, It is a separate form control, so the goal is to make sure that while browsing from screen to screen, you are editing the same form and not creating a new one each time. Could anyone help me please? If this way it is not working for me, how do I make my application succeed?
Answer: You can only create multiple screens in one form instead of using one form on multiple screens. You cannot share one control on multiple screens as it will lead to duplicate error.
To create a list form with multiple screens, please see the references below.
Is it possible to split the Edit Form into multiple screens?
Display SharePoint Online List Columns in multiple screens in Microsoft PowerApps.
Answer: It's not possible to use one single form on multiple screen. I assume you want to Edit/Save all data just on one single submit Click to a list. Use custom controls create all fields, You will have to use a Collection so that you go on collecting data from each screen and then use a Patch() function to save that collection to list.


Continuously log data from an oscilloscope

Question: I have a pin which is being toggled every 100ms by an MCU. I need to plot a graph which consists of the variation from the desired interval . That is the number of times it moved away and was toggled for 101ms or 98 ms and so on. I tried to do it with a scope but the memory seems to be limited. I can capture a maximum of 50000 lines as csv . Even if I reduce the sampling rate , it is nowhere close to the 4 hours of data I need to capture. What kind of an instrument should I be looking for? Is there any easy way to achieve this?
Comment: Few instruments have hours of memory, but your PC probably does.  Get yourself a basic CY68013A eval board / "logic analyzer" and use the open-source sigrok package to stream to disk, then analyze in your language of choice.  Actually at your timing rate you could consider using the sound card recoding at 44.1 KHz and look for the peaks of transients (the input circuit will A/C couple the signal).
Comment: Does your scope have a GPIB interface or similar that you can use to stream the data to a workstation?
Comment: It has a GPIB interface but I am unsure as to whether the GPIB interface supports continuous data logging. The scope I am using is http://www.home.agilent.com/en/pd-1945059-pn-DSOX2012A/oscilloscope-100-mhz-2-channels
Comment: The Open Logic Analyser from Dangerous Prototypes would be ideal for this.
Comment: For 4 hours? Does it have that kind of memory?
Answer: Streaming data constantly to a computer rather than using one long acquisition will most likely be easier to implement and makes use of a computers large available storage. Because you only need digital data a usb logic analyzer is probably the cheapest and easiest option.
Couple of options come to mind:

Depending on your oscilloscope you should be able to stream data to a pc to analyze quickly enough so that your 50000 sample buffer never fills up. I would contact your scope manufacturer and read through the manual to see if this is possible and if so the best way to implement it.
Use a data acquisition card from national instruments or some other company to continually acquire and analyze data. The benefit here is that you can use a program such as Labview to make set up and testing a bit easier if you don't have much programming experience. Make use of the digital logic pins, no need to use analog acquisition.
Use a usb logic analyzer. Cheap. Easy to implement. There might even be one out there that comes with software which can do the analysis you need out of the box.
Comment: The Saleae logic analyzer is great for this.  It has no storage in itself, it only streams to PC.  This allows for very long capture times.
Answer: You're describing a histogram of the pulse widths. Both the timing and the counting would be well within the capabilities of a modest micro-controller, either a ready-built experimenters board, or build it on a bread-board. Taking an interrupt at 10 Hz would barely use the capabilities of a $5 chip. In 4 hours, a 10Hz pulse train would fire 144000 times and if it's a rock-solid 10Hz, your histo will count only one bin which would need to be able to accumulate that big a number. That's bigger than a 16-bit int (you'd need 18 bits) but easily handled by using long ints (32 bits). Figure the timing resolution (bin size) and maximum departure 1.0ms you need to quatify and decide how many bins you need. You'll need 4x that number of bytes to hold the histo. Assuming you need ~20 bins, you're still well within the resources of a modest micro-controller.
It isn't an off-the-shelf solution if that's what you need, but it will be way less money than buying a bench instrument. Lots more fun, too! (Unless you need the data yesterday...)
I'm assuming you have a computer with a USB port at your disposal for programming the chip, as well as for collecting the data.
Update:
You'd arrange for the signal to interrupt the MCU whenever it changes. You'd keep one of the timers running continuously a timer at 1KHz (for 1ms resolution). On every rising edge, your ISR would read and save the timer. On every falling edge, it would read the timer again and subtract the saved value from it to get the pulse width. Assign that value to one of your histogram counters and increment the counter.
Something like
histo[width_ms]++;
will histograph the actual pulse widths in msec (as opposed to the deviation from 100 ms]. Plotting a histo of deviation only requires relabeling the t-axis.
Obviously, pick the timer resolution & bin sizes that make sense for your application. I chose 1ms buckets from 0ms to [as many as you need], representing -100ms to +?? of deviation.
Comment: I am still a little lost as to how the departure from 100ms can be calculated. Could you please explain this a little more? How do I use the interrupt to determine the deviation from 100ms?


If chemical bonding is quantum mechanic, is saying they bend and vibrate like springs wrong?

Question: I don't know much about quantum mechanics, but I do know that it's quite far removed from the easily observable and that anything "quantum" involves things that are discreet. So, how close is the analogy between molecular bending and vibration with that of springs? Is there maybe a better way to think, maybe a better analogy, to describe molecular bonds?
Comment: I am reminded of this (unfortunately true) [xkcd comic](https://xkcd.com/895/).
Comment: The "nasty" fact is that there isn't any one model that creates an adequate analogy for chemical bonding. What model to pick depends on what phenomena you're modeling. So the spring model is useful in thinking about infrared spectra, but useless in pondering NMR spectra. Just adding "springs" to atoms though doesn't describe spring lengths or coil tension either. So "physical models" must be used with care.
Comment: @NicolauSakerNeto Those moments when you realise that a flaw of a visualisation was directly on the tip of your nose for years but you didn't see it … Oh the pain ^^'
Answer: That's a good question, but remember, an analogy is just that: comparing dissimilar things on the basis of structure or function. Though there may not be a physical similarity, the analogy is effective in describing what happens, and can even be used to calculate outcomes, within limits.
In a similar way, the concept of a mass and a spring are used to describe an electrical R-L-C tuned circuit. Both have resonant frequencies and other properties that can be calculated from the physical properties of the components.
One of the difficulties in describing quantum phenomena is that until the physical properties are measured, they may be indeterminate. An electron is not in a specific place, but has a probability of being detected in a specific place. So though the analogy is not physically comparable, it helps understanding of the chemical bond, and can even produce useful results, such as IR spectra, and its use is valid.
This begs the question, though; perhaps there is another analogy that you might find more useful... Any suggestions from others are welcome!
Answer: I think there are two important points I would add to the good answer presented already. First is that this idea of modeling molecular vibrations as springs has been used to describe quite complex things in a fairly simple way. So, to some extent it is a good analogy. One example of this is an idea that Einstein actually came up with to find the heat capacity of solids. He treated every atom in a solid as a spring system which, as you point out, had to vibrate at discrete frequencies... and that's pretty much it. Using that idea alone he came up with an equation which predicts the heat capacity of solids quite accurately (gets worse at low temperatures). You can read about Einstein solids at that link if you want. It's kind of dense though...
One other thing is that molecular vibrations are clearly more complex than just a simple harmonic oscillator, but, as it happens, one can make corrections to the simple harmonic oscillator and end up with quite a good description of reality.
Specifically, the energy of a vibration is described by:$$E(v)=(v+\frac12)\omega-\omega_{xe}(v+\frac12)^2$$where $v$ is the vibrational energy level (things are discrete as you point out) $\omega$ is the vibrational frequency in wavenumbers, and $\omega_{xe}$ is the anharmonicity of the vibration. The interesting thing is this correction to the harmonic oscillator which the second term makes can be further expanded so that one has an infinite series which converges to the exact energy value of the vibration. So, in the sense that this can give the correct answer and is built on the idea of a simple harmonic oscillator, a spring is very much how atoms vibrate. Hope that is helpful.
That above equation coms from the Morse potential
Here is a picture comparing the two


Dark Energy and Wormhole stability

Question: Is it possible that the "negative energy" needed to create stable wormholes as theorized by Morris and Thorne (?) could be dark energy?  Could this be the "exotic" negative energy matter referred to?
Answer: Your title asks about dark matter, while the question asks about dark energy. The two are very different!
I'd guess you mean to ask about dark energy because this does behave differently from matter (as far as gravity is concerned dark matter behaves just like ordinary matter). If so, the answer is that dark energy does not behave like exotic matter and cannot stabilise a wormhole.
The effect that matter/energy have on the spacetime curvature is described by the stress-energy tensor. This tensor contains terms related to energy density and terms related to pressure. Dark energy behaves as if it has a negative pressure, which is why it is causing the expansion of the universe to accelerate, but the energy density term from dark energy is positive just like regular matter. The exotic matter that we need to stabilise wormholes has to have a negative energy density.
Answer: Absolutely not.
Dark matter has the same gravitational effects as regular matter it just doesn't interact electromagnetically. We expected a certain amount of dark matter, such a neutrinos, bit there weren't enough neutrinos so it seemed like there must be something else besides things like neutrinos. Something that interacts in the normal way gravitationally but just doesn't interact electromagnetically.
Light is an electromagnetic wave so when something (like a neutrino) doesn't interact electromagnetically you can't see it with light.
We needed something like a neutrino but not any if the things we've seen before, there's just weren't enough of the things we've seen before to explain how massive the galaxies seem to be.
Exotic matter with negative energy densities would just make it worse then we'd need even more dark matter to compensate for the exotic matter.
Now sometimes people might say exotic dark matter to mean the new stuff, the stuff we haven't seen before to contrast it with neutrinos and such which would work fine but there just isn't enough of it. But they don't mean negative energy density that would do the opposite of what we need them to do.
Comment: You discuss dark matter, but Rich asked about dark **energy**.
Comment: @JohnRennie Ah, distracted by the title my bad.
Comment: Sorry about that, I did mean DE.
Comment: @rich_markle You can still edit the title.
Answer: Maybe, the alcubierre drive can use both negative matter and dark energy. I don't see why not dark energy is accelerating the universe faster than light.
The only problem is you might not be able to make it

Dark Energy and Wormhole stability


Server room door security

Question: I wanted to know if anybody had any recommendations as to how to keep the server room secure from employees.  There is a lock on the door, however, anybody with a building master (maintenance, owners, custodians, etc) can open it.  It would be nice if it required the key and also had a proximity card lock so that we could log entry and restrict it further.  Has anyone done this before?  What are some other ways to make sure it is secure?
Comment: Our building used to be a bank, so we keep our servers in the vault. nothing like a 3" steel door to keep people out..
Comment: @Dentrasi: My last office was an old bank. The vault door is awesome until you fool around and get a board wedged in it...Last time I fool around with a vault-door. I had to chip the board into pieces to get the door back opened.
Comment: We have an old vault in our building.  The vault door is about 8-10 inches thick and probably weighs in the neighborhood of 10 tons.  I would not want to have to open that door on a regular basis.  It's sheer mass is impressive and scary at the same time.  I cannot imagine getting any body part "stuck" because once that door starts moving, it's moving until it shuts...there is no stopping it.
Answer: Are those nice biometric and what have you devices of yours attached to UPS power? Is the entire chain, from reader, electric lock, any switches / distribution layer, to the authentication server and its database on emergency power?
I'm just asking because a few years ago we had the largest regional power loss in 25 years around here. I know of one major installation where they to their horror discovered that they couldn't enter their server room while the electricity was out. Their emergency procedures required them to power down non-essential servers, because their UPS power couldn't run the air conditioning at full output, so the server park heat output exceeded the A/C cooling when on emergency power. So they stood outside their server room, and wondered how hot it was getting in there...
I would suggest to keep it simple, with a good certified steel door, a steel door-frame that is well fastened to solid walls, and 2 good mechanical locks on the door (say 1 Medeco and 1 Kaba).
You can of course replace one of the mechanical locks with a swipe card, to gain a entry log during normal operation. Just be sure that the electric lock automatically disengages if power is out. Strictly speaking, this makes you more vulnerable against a James Bond style burglary, where the attackers cut power to the building before going in. This is a small risk, but one I'd much rather take than risk being locked out of my server room during an emergency.
Comment: A Kaba X09 plus a badge reader will take care of most anything.
Answer: Proximity cards are your best bet.  The logging is there in a clean, concise format.  Our data centers are secured by the same badge system that our external doors are secured with which allow for group access configurations.
Security cameras are another option, but the maintenance is problematic and it takes a little longer to sift through the video to find what you're looking for.
EDIT:
Bioscanners are another option, as Zypher pointed out, but then you start getting into privacy issues.  In many countries this quickly gets legal involved.
Answer: Don't try to secure things too much, put the usual swipe or promixity card on and audit access. Lots of swipe locks can be further secured with a pin for trusted employees.
I know of a site where the server room is secured by the outsourced company, and access has to be requested in advance and a key provided to gain entry. As a result a minimum of 2 employees are required to be in the room at any given time - if 1 person went in, fell or had a server fall on him or otherwise was unable to get to the door to open it, they'd have to raise an emergency request to get a new key sent over, which would take far too long (personally, I'd smash the door open in such a case). Don't try to restrict access too much.
Answer: I'm a big fan of simple solutions that don't require too much extra hardware to function. I like strong doors, strong locks, and large, intimidating security guys named 'Larry', who can bench press the entire IT staff.
Locks do have a problem that many lock manufacturers are in denial about how easy their products are to pick right now, but that's where Larry comes in - you can't use a lockpick when Larry is around because he'll turn you into a pretzel.
Further, if the number of people who go in and out of the special door is small, Larry will learn to recognize them. And when someone who doesn't normally go through that door approaches, Larry will ask them what they are doing. And if they don't have a good explanation for their presence, well, it's pretzel time again!
Larry does have the downside of being an ongoing expense for your organization, but if you really need that door protected, then Larry can be a really big contributor to that protection.
Answer: We have our door at the local office setup with a badge reader that ties into our normal system. The lock is also keyed so that a master key cannot open it and only IT has a copy of the key as a just in case backup. In our data center we additionally have a hand scanner that ties into the system so you need both your hand and badge ID to get into the door, along with being in the group that allows access.
I would talk to whoever provides your normal badge entry systems for options on how to integrate it to your existing system (if you have one)
Answer: In response to jesper.mortensen:
I agree that a good steel door, steel door frame, supported by solid walls, is ideal. That said, I don't see the point of having two mechanical locks on the door. A single swipe/proximity reader should be sufficient unless your business rules require both a physical key and an electronic key. Biometric access would be a good addition to proximity, IMO. I simply see no need for physical keys for routine access.
As for auto-disengage on power failure -- I think that's a horrible idea. If someone wanted in the office, they'd be able to defeat most or all of the locks just by finding a way to cut power to the facility. What we've done in some of our facilities is replacing the steel door frame with one that is specifically designed to permit key override. I've honestly not examined the mechanism to see how it works, but I do know that our electronic key system is set to fail-secure. If we need to get through a secured door and electronic locking is unavailable, we still have physical keys that we insert into a lock on the door frame, and the lock is released. Definitely more secure than just fail-insecure.
In any case, I'd also very strongly advocate a monitoring system in the room for both motion and entrance -- if anyone uses an electronic bypass key while the system is operational, an alarm would sound.
Comment: Auto-disengage on power failure - depending on the room, the lock configuration and local fire codes, you may not get a choice on this one. In any sane jurisdiction, you CAN NOT lock people in just because the power failed. So unless the lock is also configured with a manual exit, it MUST auto-open on power fail. You'd be surprised how uncommon the manual exit is. I've worked at places with electronic locks, where someone gets a call to come in when the power fails so no one can rob the place. Stupid? Oh yea. But a consideration none the less.
Comment: I did know about those regulations existing in most places, but they didn't come to mind. Those places that I've seen electronic w/ key override have been 1) equipped with one-direction keyless override, or 2) been in a jail.
Answer: SmartCards etc so it's per-employee and logged.
Remember:

your entire business probably relies on the kit there
"need to have" only: not "I'm the boss"
your sysadmins need somewhere private to sleep off hangovers
Comment: Heh.  If I'm hung-over, though, typically I'm in no condition to negotiate the swipes :)
Comment: @squillman, That's why you use RFID, no contact required.
Comment: Good point.  I think that's still even a bit doubtful.
Answer: All good answers.  I would also install a camera inside the server room.  They are relatively inexpensive and can record on event and can be monitored remotely.
We have installed a mechanical push-button lock on one of our server room doors.  The lock has number and letter buttons.  Authorized personnel do not need a key and changing the combo is very easily done if staff leave or get fired.
Comment: If using that kind of mechanical lock, make sure you change the combo regularly, otherwise wear and tear on the keys will tell people which numbers are in the combo.
Comment: also make sure that whatever the camera is recording to (hard disk, video tape, etc) is in another room or secured in a separate cage/box/safe with a separate key so it can't be stolen or destroyed by anyone who realises that they've just been caught on camera breaking into the room.
Comment: good insight MK
Answer: We install S,E,A,P rated doors and partitions for many list x cxompanies ,these are approved by the Home Office asnd no one is getting in with out permission
Answer: I'd recommend the Handscan Biometric reader - for example: Handpunch 2000. You can ntework it, use modems or a serial link. Perfect for user verification tasks. There's a SDK available (and even an api for .Net/c# etc..). We use it for our employees clock in/out.
-js
Comment: I don't know if these are suited for security applications... they seem to be used exclusively for employee in/out punching
Comment: We use a unit similar to this on our data center door. It works well and integrates with the badge system.
Comment: It is meant to be a Identity Verification System. It is definately suited to verify your identity so it can open the door. Time/Attendance mode is simply a feature that makes use of this service. T&A is disabled by default but can be enabled. We use this a lot of I have actually developed a lot of our own code to interface with these systems (14 devices so far...)
Answer: I recommend anti tail gating solutions.

Server room door security


Remove problem PHP code entered into footer via Theme

Question: A friend of mine has a WordPress site using the Theisis theme. Recently he added a bit of problematic PHP code to the footer via the Theme (not into a PHP file). The PHP code is erroring out causing the site to WSOD (White Screen of Death). Because the footer is on every page, he can't get back in to remove the PHP code to fix the site. I'm not super familiar with WordPress (use mostly Drupal myself) so I'm not 100% sure how to help him. I'd guess the PHP snippet got stored in the database and needs to be manually removed from there. But I don't know the WordPress schema all that well. Can someone point me in the right direction? Where in the database would this code be store so I can remove it?
Comment: Where exactly did he add this code? The footer's PHP code can be edited in the theme editor, are you sure it's not in `footer.php`?
Comment: he said he added it through the site's interface. Again, I haven't used WordPress much, but he said there was a text box and a save button. That makes me think it's stored in the database.
Comment: If you can still go into the admin, activate the default theme. This should at least show up your site, naturally not with the theme that was destroyed.
Answer: Use FTP to rename the Thesis theme folder and then WP will use the default theme and you will be able to get back into admin.
If he edited the theme file via the theme editor in WP admin, then replace the file he edited in the Thesis folder from a fresh copy and try and reactivate the theme.
If that doesn't work and the added code was saved to the Thesis theme options, use a plugin called Clean Options to clear out the old Thesis theme options and start over: http://wordpress.org/extend/plugins/clean-options/


What is the rationale between the ninty degree at the elbow for pressing motions?

Question: Considering the dumbbell overheadpress, benchpress and so on.  I find that in all these exercises, an important point is to not go beyond ninty degree at the elbow. Why is this?
Answer: It's fine to go past 90 degrees.
There is no reason to avoid degrees of elbow flexion beyond 90 degrees in pressing movements. Your elbows and shoulders were made to do that just fine. One thing to consider is that taking a joint through a greater range of motion means that you are doing more work in the same number of reps than a set with less range of motion.
Comment: @TrystwithFreedom Most of the material on the internet is nonsense, so you shouldn't be surprised when reality contradicts it. As for the origin, it is likely related to my last sentence, a greater range of motion means more work per rep, and often takes the joints through the weakest portion of their range (usually the portion with the longest muscle lengths). So when you compare the same weight through a greater range of motion, that's like lifting a heavier weight through a shorter range of motion, which could lead to injury if not adequately prepared for it.
Comment: Hmm this contradicts a lot of material I read on the internet. Why do people advise the ninty degree thing at all then? What is the origin of it?
Comment: So, what is actually the ideal angle for bench pressing ? @Thomas
Comment: @TrystwithFreedom That depends somewhat on what your goals are, but is mostly personal preference.
Comment: @TrystwithFreedom I incorporate both longer and shorter range of motion variations of the bench press into my training.
Answer: There is something to it, but clinging to 90 degrees is nonsense.
Consider how muscles work: the myosin filaments glide in between actin filaments. Now, if muscles are stretched beyond a certain threshold, not all heads of the myosin can make contact with the connection points on the actin. The result is that beyond a certain length of the muscle, it cannot exert as much strength as it can when it is shorter.
That can become problematic when you train with max weights and go "too low" as it means the potential strength of your muscles may become lower. At some point, the muscles won't be up to the load anymore and you collapse at the lowest point although the muscles, as such, had more reps in the.. Therefore, it can cost training volume.
Another point is wrist angles: ideally, your index and middle finger knuckles should roughly stay in line with the ulna and radius bones of your forearm to load the wrist optimally. Grip width and full range of motion can lead to odd angles in the wrist which can become a problem with high load and volume.
Why is the 90 degree dogma nonsense, then?
Well, first of all, you don't train with max weight only. The structures don't have a problem with going below 90 degrees  even with load as such. As a matter of fact, muscles (or rather: moving structures as a whole) tend to react better to training stimuli when going through their "full" range of motion.
The more important point, though, is that individual proportions can be very diverse: depending on how long your upper arm is, and how long the forearm compared to that, the leverage can be very different. Same for the wrist: If your grip width is adjusted to your proportions, you can easily go beyond 90 degrees flexion and still have your wrist aligned well. This means that while the tipping point may be at 90 degrees for some, it can be much more (or less) for others.
Therefore, you need to try out what works for you and your body. Nobody can give you magical formulas that tell you what to do.


What is the difference between Spin and Spin Duplicates?

Question: In Blender 2.81 there are spin tools. The first one is Spin tool and the other is Spin Duplicates. I used both of them and didn't see any difference. What is the difference? If you know the answer please share with me. Thanks :)
Answer: Spin tools creates a revolution surface from the selected geometry, while the Spin Duplicate operator creates a circular duplication kind of "polar array" of the selection.

Current issue I see is that apparently using the tools from the toolbar doesn't seem to automatically set the correct operator preferences, making them by default behave the same unless you manually untick the Duplicate option which seems like a bug.
Comment: Thanks for the answer. I think this one is a bug too. Both Spin and Spin Duplicates have use duplicate option. How can I call Spin Duplicate operator then? (Not from toolbar)
Comment: Spacebar menu, like all operators, otherwise create a dedicated hotkey


Atmosphere on fire

Question: Supposedly Edward Teller was worried about the atom bomb setting the atmosphere on fire. Apparently he was wrong, but I was wondering what it would take to burn the earths atmosphere?
Comment: The physicists weren't worried about atmospheric combustion, but of a nuclear chain reaction using the oxygen and nitrogen in the atmosphere. The two phenomena are quite different; do you want to set this atmosphere on fire, or start a nuclear reaction?
Comment: Welcome to Worldbuilding, mendohomobavonez, your question may be a duplicate of https://worldbuilding.stackexchange.com/questions/47424/how-to-ignite-the-atmosphere or https://worldbuilding.stackexchange.com/questions/87917/what-would-it-take-to-set-the-atmosphere-aflame or https://worldbuilding.stackexchange.com/questions/68262/what-if-the-trinity-test-had-ignited-the-atmosphere-could-we-survive I suggest you check them out. They might answer your question.
Comment: This is the first time I've seen that it was suggested Edward Teller did this calculation. I know Fred Hoyle did. Possibly some scientists working on the Manhattan project did so. Teller was part of the Manhattan, so he may have.
Answer: Scientists weren't worried about igniting the atmosphere, they were worried about the nitrogen and oxygen being sent into a chain fusion reaction. turns out even the center of the sun is not hot or pressurized enough to cause hydrogen and oxygen to begin fusion. Maybe the center of very old very large stars reach those kind of pressures and temperatures required to cause a fusion event with those elements. When those elements are fused it takes more energy to force them to do that than they put out when it happens too.
As for actual ignition, There is very little fuel in the atmosphere (nitrogen is not combustible, oxygen is not a fuel but an oxidizer, and other possibly flammable gases are in only minute quantities.) The atmosphere is also too efficient at diffusing heat for any sort of sustained chain combustion reaction to occur. To "ignite the atmosphere" you would need to heat it up uniformly across the entire (or at least most of ) the atmosphere at once. A nearby super nova might be able to do that, but that is going to obliterate the entire planet anyways so its a bit of a moot point.
Answer: Atmosphere as it is (i.e. without adding combustible) can be "set on fire" using three mechanisms:

the one Konopinski, Marvin and Teller worried about, a runaway fusion reaction involving either nitrogen, oxygen, or both. The conditions for such a reaction are too energetic to set up even with a fusion device, and if they were, those same conditions would also vaporize the planet.
a reaction between atmospheric N2 and O2, which combine to give e.g. NO2, thus asphyxiating every oxygen-breathing organism. This is a plot device in one of John Campbell's Aarn Munro novels (the Teffels try burning the atmosphere of their enemies' planet), but it will not work because the enthalpy of the reaction product is higher than that of the reactants by about 34 kJ/mol. You need to supply heat to make it work (that's why combustion engines, wherein there's heat aplenty, give off nitrous oxides, while a passive catalyzer is able to break them off again to nitrogen and oxygen without needing any energy).
a reaction between any suitable atmospheric component (nitrogen and oxygen being the only reasonable candidates) and another minority component, either naturally present or (semi-)artificially added, to yield a stable compound with negative net enthalpy change. This is posited in a ST:TOS novel, where the reaction is between oxygen and trace silica dust in the air. The book handwaves away the fact that the reaction is not thermodinamically possible (silica dust is already an oxide).

If you added combustibles enough, of course, it would work. That is 'what it would take'. But you would need a lot. About 25g of hydrogen for every kilogram of atmosphere (or 32g for each cubic meter of atmosphere) to get all oxygen burned to water. Between the heat and the drop in oxygen partial pressure, probably a tenth of that would make the Earth uninhabitable.

Atmosphere on fire


Something I don't understand about Epiphany

Question: I like to try out different web browsers, on windows sometimes I had 4 or 5 of them. Still that Firefox is my all-time favourite I was thinking about trying out the default Epiphany browser on Ubuntu 14.04, but I just can't figure it out how to open new tabs or get bookmarks.
Is there no such option or what? If I'm wrong can you give some instructions how to use it?
Answer: Epiphany uses a grid view interface since it is considered easier to use on a touchscreen.

From this source:

The tab bar might be gone, but we'll still offer a convenient, and we think improved, way of switching between pages. All the currently and recently opened pages are visible in the overview (the new start page), and we'll provide a way of switching between them with the mouse or keyboard shortcuts. You can see an early animated mockup of this in this video of the gnome design youtube channel

(the link has a video)
The manual has this to say about bookmarks:

add a bookmark: Select the menu at the top-right of the window, then Bookmarks ▸ Add Bookmark… or press Ctrl+D to add a bookmark.
Answer: To open a new tab in Epiphany, press Ctrl+T. When there's only a single tab, the tab bar is invisible.
To jump from tab to tab, use Ctrl+PgUp and Ctrl+PgDn, to close the current tab, press Ctrl+W


Converting Likert Scales

Question: We collected data on a 7-point survey and it should have been on a 9-point scale. How do you convert a 7-point scale to a 9-point scale?
Comment: I would say that the general answer is "you don't".

But why do you say it "should" have been collected on a 9 point scale? Are you are trying to compare it to other data that was collected using a 9 point scale? Or are you attempting to merge it with other data? Or something else?
Answer: You should not convert individual answers.

However, if you want to compare your work in the 7 point scale with a different work on a 9 point scale, you can make a linear transform of the type:
$$
y = \frac{x-m}{a}
$$
where $x$ is the mean or the median in the 7 point scale, $m$ is the minimum of that scale, $m=1$ in your case, and $a$ is the amplitude of the scale, in that case it will be $a = 7 - 1 = 6$.
For the 9 point scale, the transformation formula is the same, but $a = 9 - 1 = 8$.
Note that the standard deviation and the variance will each have their own transformations.
The transformed value will be in the interval $[0; 1]$ and you may find that, for instance, $4.2$ in the 7 point scale corresponds to a higher value than $4.8$ in the 9 point scale.
Comment: Sorry, I meant to comment on the original post. I will delete my comment on your answer
Comment: OK. No worries.

Converting Likert Scales


Statistical Mechanics Reaction problem

Question: I am trying to do a problem that I encountered on a test, that I couldn't do.
It reads as follows:
"Consider a system comprised of two types of molecules, A and B, trapped in a volume V. They can react to form a third type of molecule, C, which has an internal energy of $-\epsilon$, while A and B have $0$ internal energy. If initially $N_A=N_B$ and $N_C=0$, find the equilibrium amount of C molecules if the system is in contact with a reservoir with temperature T. Consider ideal gases."
I know that equilibrium means that the chemical potentials $\mu_i$ have to be equal, that is, $\mu_A+\mu_B=\mu_C$
Additionally,the partition function for the molecules are
$$Z_A=\frac{e^{-\beta HN_A}}{N_A!}=\frac{e^{0}}{N_A!}=\frac{1}{N_A!}$$
$$Z_B=\frac{e^{-\beta HN_B}}{N_B!}=\frac{1}{N_B!}$$
$$Z_C=\frac{e^{-\beta HN_C}}{N_C!}=\frac{e^{\beta \epsilon N_C}}{N_C!}$$
from here, I use that the Helmholtz Free energy $F=-k_BTln(Z)$ and the chemical potential $\mu =\frac{dF}{dN}$ to obtain
$\mu_A=k_BTln(N_A)$, $\mu_B=k_BTln(N_B)$ and $\mu_C=k_BTln(\frac{N_C}{e^{\beta \epsilon}})$
Now I plug this into the initial relationship between chemical potentials to obtain
$$k_BTln(N_A)+k_BTln(N_B)=k_BTln(\frac{N_C}{e^{\beta \epsilon}})$$
$$ln(\frac{N_AN_Be^{\beta \epsilon}}{N_C})=0$$
$$N_C=N_AN_Be^{\beta \epsilon}$$
And I think that I now have to plug in the relationship that $N_A=N_B$ $N_C=0$, but the expression blows up. What can I do from here?
Answer: It looks all good, just I guess that you are looking at the final concentration at equilibrium, so you don't care about initial conditions!   I will discard $N_c=0$  and set instead conservation of the number of molecules
$N_{c \, final} + N_{a \, final} + N_{b \, final} = N_{c \, initial} + N_{a \, initial} + N_{b \, initial} = N_A + N_B = 2 N_A $
plus as you wrote (but with "final!)
$ N_{a \, final} = N_{b \, final}$

Statistical Mechanics Reaction problem


Share network with neighbor

Question: My neighbor asked me if I wanted to share his network with me. Internet access is a little more expensive here than I am used to in my country. Before saying yes I wanted to know if I had risks in sharing my internet with him. He keeps the box and I will only have the wi-fi, which is enough for me, but about the security I don't want him to look at my bank passwords or something like that. I don't know if it's more risky than public wi-fi, but if someone can give me an idea or maybe advice.
Answer: You are certainly adding risk though whether that is enough to worry about may be difficult to calculate.

Is it against the terms and conditions of use of the ISP? You both could get cut off. Low to medium risk, relatively low impact.
Will someone in their household do something illegal that you might end up on the hook for - because you cannot prove you were not complicit. Illegal file sharing, child pornography or something else. Medium risk, terrible impact.
You will be relying on their router being secure - it may well be now but will it always be? Medium risk but potentially high impact.
You will be using a wireless connection between houses, will anyone else create a rogue Wi-Fi hotspot that will intercept your connection? An unlikely issue generally but quite high impact.

I would estimate that the risks of all of that are far lower than public Wi-Fi but they are certainly nowhere near zero.
UPDATE: You could help mitigate some of these risks fairly readily. You could have a written and signed agreement for example. You could make sure your neighbours router created a VLAN and you could give them your own Wi-Fi access point so that your traffic was segmented from theirs.
Comment: I'm sorry Steve but I disagree completely with your view. I have not offered any legal opinion and would not do so. I have outlined the possible RISKS and that is entirely appropriate. Indeed, I deliberately used the language of risk management.
Comment: I thought about a letter yes, but as you said it resolve some of these risks.
Comment: Remember this is an information security group, not legal advice.  1&2 are legal opinions and not appropriate advice to be offered here.
Answer: I think it comes down to how much you trust this person. Public Wifi can be dangerous because attackers can use things like packet sniffers to detect traffic and obtain passwords and other identifying information over the same network they're in. This guy could theoretically do the same without you knowing it. Depending on the network settings you have on your current system, he could have access to certain shares or drives you have created on your system that may be set to be accessible in a shared setup like that. That goes for anything you connect to the network too.
If you trust him, you have nothing to worry about. If you have any reservations, I'd probably hold off.
Comment: Trust is an odd thing. There are plenty of people I've trusted who have turned out to be involved with immoral or illegal activities, some of them pretty terrible. I don't think I have particularly dodgy contacts. It is only a tiny percentage of people but the impact on you from a neighbour being caught trading in child pornography for example might be catastrophic.
Comment: Truth. You never really know what's going on behind closed doors, and sharing a connection you're in the dark about doesn't seem to bode well, regardless of how much it might save.
Comment: But if he does it's not me that will have theses files on my computer it's him normally no? so I should no really have problem, I don't know.
Comment: To be honest I saw him one time... and he said that he have a good speed internet because he does bitcoin.., that we could test it etc. If I come on this forum it's for really know the risk I'm exposed if I do. If really it's better to have my own router, internet I will do.
Comment: Remember X-Files? Trust no-one. And secure your system accordingly.
Comment: I like to use a conversational analogy when it comes to internet connections. Sometimes it's better to have a conversation where it's only two people speaking, you and another party. Regardless of how secure that conversation may need to be, if you're okay with someone else potentially listening in on that conversation, and potentially adding on to it with whatever they choose to add, then you'll be okay sharing the connection. But again, it comes down to how much you trust that this person won't listen in and won't do something bad with the conversation.
Comment: @Nerm: It will not necessarily matter where the files are (or quite possibly are not) found. What may matter more is that someone tracked the downloading of files to the router. The router that you are sharing. The likelihood of this happening may be low but the potential impact is very high.
Answer: You could use a vpn to encrypt your connection. Please make sure to keep updating the vpn version. Set up your network as being a public and not a home network to minimize the file sharing risk with other devices on the network.

Share network with neighbor


If you have two bachelor's degree in related fields, can you mention in your CV only the latest of the two?

Question: I obtained my bachelor's degree from a third tier school before completing my second bachelor's degree and a master's degree at more reputable schools. I was wondering if it is acceptable to omit my first bachelor's degree from my CV.
Comment: Include all of your education.
Comment: Why would you want to leave it out?
Comment: CV for what? For graduate admissions, you will likely have to list (and supply transcripts from) _all_ schools you've attended anyway.
Answer: I think it would make for an awkward line of questioning at an interview when they inevitably ask what you did during those years and you reply that you completed a Bachelors degree but didn't feel it was good enough to include it.
Worst case scenario: your interviewer went to that institution and you've just shot yourself in the foot.
Always include your full educational and work experience as it makes for easy nitpicking at an interview that is easily avoided.
Answer: Withholding the information would be acceptable to most people, but it may expose a large gap in your education/employment track record. You may be asked about what you did during these years.


y=mx+c intersecting a circle

Question: I'm trying to write a 3d computer game.  When it comes to walls they're all straight lines between 2 points on the $xz$ plane. If the man is centered at $(i,k)$ the equation for their circle of influence is $(x-i)^2+(z-k)^2=r^2$.
If the case of a wall having equation $x=c$ or $z=c$ I can solve this, but when the wall is sloping and is of the form $z=mx+c$, my powers of math fail me.
Comment: Is there some person, who is assigned the job to down vote questions by first timers ?
Comment: Plug in your formula for $z$ and use the quadratic formula.
Comment: @rhubarbdog Welcome to MSE. Please look at http://math.stackexchange.com/help/notation to see how to format math for this site.
Comment: @rhurbardog, your equations are two dimensional, they don't three dimensions to work.
Comment: the y axis is stright up and down and will be accessed by jumping or catch an elevator, walking up hill or climbing a ladder
Answer: As suggested in comments, you can set $z=mx+c$ in the equation of circle, thus get $$(x-i)^2+(mx+c-k)^2=r^2\\ x^2-2ix+i^2+m^2x^2+2mx(c-k)+c^2-2ck+k^2=r^2$$
Now, we can write it as the quadratic equation $$(m^2+1)x^2+2(mc-mk-i)x+i^2+c^2+k^2-2kc-r^2=0$$and solve for $x$ (no, it is not pretty). Good luck!
Answer: If the question is "does the man's region of influence meet the wall?" rather than "WHERE does it meet the wall?", then things are easier: you merely need to compute the distance from the man $(i, k)$ to the nearest point on the wall. If this distance is less than $r$, then you've got your answer.
It's easier to compute the squared distance and check that it;'s less than $r^2$, however, avoiding a square root.
So how do you do this distance-checking?
First, writing wall-equations in the form $y = mx + b$ is a bad idea, even though it's what you're most familiar with from high-school, because it doesn't allow for $x = constant$ walls. Instead, it's best to write them in the form
$$
Ax + By + C = 0
$$
where at least one of $A$ or $B$ is nonzero. If you have the $y = mx + b$ form, you can shuffle it around:
$$
y = mx + b \\
y - mx - b = 0\\
(-m)x + 1y + (-b) = 0
$$
to get it in the $Ax + By + C = 0$ form, with $A = -m, B = 1, C = -b$. So this "general" form includes the one you're used to.
The second fact you need to know is that if you plug a point $(x, y) = (a, b)$ into the left side of the equation
$$
Ax + By + C = 0
$$
to get
$$
Aa + Bb + C,
$$
the resulting number is related to the distance from $(a, b)$ to the line. If the resulting number is zero, then the point's on the line, for instance!
Here's the rule: the distance from $(a, b)$ to the line defined by
$$
Ax + By + C = 0
$$
is exactly
$$
d = \frac{Aa + Bb + C}{\sqrt{A^2 + B^2}}
$$
so the squared distance is just
$$
d^2 = \frac{(Aa + Bb + C)^2}{A^2 + B^2}
$$
Conclusion: to test whether the point $(i, k)$ is "close" to a wall defined by $y = mx + b$, do the following:

Let $A = -m, B = 1, C = -b$
Compute $s = Ai + Bk + C$.
Compute $\frac{s^2}{A^2 + B^2}$.
If the value in step 3 is less than $r^2$, then the man is within distance $r$ of the wall; if the value's grater than $r^2$, the man is farther than $r$ from the wall. If it's exactly $r^2$, the man is at distance $r$ from the wall.

As a little throwaway, the value $s$ that you computed may be positive or negative. For all points on one side of the line, it'll be positive; for all points on the other side, it'll be negative. If you want to switch these sides, you can replace $A, B, C$ with $-A, -B, -C$, and the line will not change, but the sign of $s$ will.

y=mx+c intersecting a circle