Programs & Examples On #Visual studio dbpro

This tag refers to Microsoft's Visual Studio Team System Database Edition. In earlier versions of the product the database edition was known as "Database Professional" aka "DB Pro".

How to develop or migrate apps for iPhone 5 screen resolution?

Using xCode 5, select "Migrate to Asset Catalog" on Project>General.

Then use "Show in finder" to find your launch image, you can dummy-edit it to be 640x1136, then drag it into the asset catalog as shown in the image below.

Make sure that both iOS7 and iOS6 R4 section has an image that is 640x1136. Next time you launch the app, the black bars will disappear, and your app will use 4 inch screen

enter image description here

How do I determine scrollHeight?

Correct ways in jQuery are -

  • $('#test').prop('scrollHeight') OR
  • $('#test')[0].scrollHeight OR
  • $('#test').get(0).scrollHeight

Matplotlib legends in subplot

What you want cannot be done, because plt.legend() places a legend in the current axes, in your case in the last one.

If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this

f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()

enter image description here

Note that you pass to legend not the axes, as in your example code, but the lines as returned by the plot invocation.

PS

Of course you can invoke legend after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.

Equivalent of "continue" in Ruby

Inside for-loops and iterator methods like each and map the next keyword in ruby will have the effect of jumping to the next iteration of the loop (same as continue in C).

However what it actually does is just to return from the current block. So you can use it with any method that takes a block - even if it has nothing to do with iteration.

How can I upload fresh code at github?

You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)

Check Creating github repositories with command line | Do it yourself Android for example usage.

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

Sort and Lock Table is the only solution I have seen which does work on other browsers than IE. (although this "locked column css" might do the trick as well). Required code block below.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="/js/lib/dummy.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <style type="text/css">
    /* Scrollable Content Height */
.scrollContent {
 height:100px;
 overflow-x:hidden;
 overflow-y:auto;
}
.scrollContent tr {
 height: auto;
 white-space: nowrap;
}

/* Prevent Mozilla scrollbar from hiding right-most cell content */
.scrollContent tr td:last-child {
 padding-right: 20px;
}

/* Fixed Header Height */
.fixedHeader tr {
 position: relative;
 height: auto;
}

/* Put border around entire table */
div.TableContainer {
 border: 1px solid #7DA87D;
}

/* Table Header formatting */
.headerFormat {
 background-color: white;
 color: #FFFFFF;
 margin: 3px;
 padding: 1px;
 white-space: nowrap;
 font-family: Helvetica;
 font-size: 16px;
 text-decoration: none;
 font-weight: bold;
}
.headerFormat tr td {
 border: 1px solid #000000;
 background-color: #7DA87D;
}

/* Table Body (Scrollable Content) formatting */
.bodyFormat tr td {
    color: #000000;
    margin: 3px;
    padding: 1px;
    border: 0px none;
    font-family: Helvetica;
    font-size: 12px;
}

/* Use to set different color for alternating rows */
.alternateRow {
  background-color: #E0F1E0;
}

/* Styles used for SORTING */
.point {
 cursor:pointer;
}
td.sortedColumn {
  background-color: #E0F1E0;
}

tr.alternateRow td.sortedColumn {
  background-color: #c5e5c5;
}
.total {
    background-color: #FED362;
    color: #000000;
    white-space: nowrap;
    font-size: 12px;
    text-decoration: none;
}
  </style>

  <title></title>
<script type='text/javascript'>//<![CDATA[

/* This script and many more are available free online at
The JavaScript Source :: http://www.javascriptsource.com
Created by: Stan Slaughter :: http://www.stansight.com/ */

/* ======================================================
Generic Table Sort

Basic Concept: A table can be sorted by clicking on the title of any
column in the table, toggling between ascending and descending sorts.


Assumptions:

* The first row of the table contains column titles that are "clicked"
  to sort the table

* The images 'desc.gif','asc.gif','none.gif','sorting.gif' exist

* The img tag is in each column of the the title row to represent the
  sort graphic.

* The CSS classes 'alternateRow' and 'sortedColumn' exist so we can
  have alternating colors for each row and a highlight the sorted
  column.  Something like the <style> definition below, but with the
  background colors set to whatever you want.

   <style>
   tr.alternateRow {
     background-color: #E0F1E0;
   }

   td.sortedColumn {
     background-color: #E0F1E0;
   }

   tr.alternateRow td.sortedColumn {
     background-color: #c5e5c5;
   }
   </style>

====================================================== */

function sortTable(td_element,ignoreLastLines) {

  // If the optional ignoreLastLines parameter (number of lines *not* to sort at end of table)
  // was not passed then make it 0
  ignoreLastLines = (typeof(ignoreLastLines)=='undefined') ? 0 : ignoreLastLines;

  var sortImages =['data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUz4IVcZDleixQIQjA1pFFZx2FVRklZvOWUl8LsVgBeFLyE8TLgDZYESISwvAAA1QvjAQwBADs=','data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUw4CVeDzOeFwCgIhFBBDtY1sAmtIIWFV0VJweNRhkZeoeDpWIQNSYBgSAgWYgQLGwIADs=','data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7','http://web.archive.org/web/20150906203819im_/http://www.javascriptsource.com/miscellaneous/sorting.gif'];

  // Get the image used in the first row of the current column
  var sortColImage = td_element.getElementsByTagName('img')[0];

  // If current image is 'asc.gif' or 'none.gif' (elements 1 and 2 of sortImages array) then this will
  // be a descending sort else it will be ascending - get new sort image icon and set sort order flag
  var sortAscending = false;
  var newSortColImage = "";
  if (sortColImage.getAttribute('src').indexOf(sortImages[1])>-1 ||
    sortColImage.getAttribute('src').indexOf(sortImages[2])>-1) {
    newSortColImage = sortImages[0];
    sortAscending = false;
  } else {
    newSortColImage = sortImages[1];
    sortAscending = true;
  }

  // Assign "SORTING" image icon (element 3 of sortImages array)) to current column title
  // (will replace with newSortColImage when sort completes)
  sortColImage.setAttribute('src',sortImages[3]);

  // Find which column was clicked by getting it's column position
  var indexCol = td_element.cellIndex;

  // Get the table element from the td element that was passed as a parameter to this function
  var table_element = td_element.parentNode;
  while (table_element.nodeName != "TABLE") {
    table_element = table_element.parentNode;
  }

  // Get all "tr" elements from the table and assign then to the Array "tr_elements"
  var tr_elements = table_element.getElementsByTagName('tr');

  // Get all the images used in the first row then set them to 'none.gif'
  // (element 2 or sortImages array) except for the current column (all ready been changed)
  var allImg = tr_elements[0].getElementsByTagName('img');
    for(var i=0;i<allImg.length;i++){
    if(allImg[i]!=sortColImage){allImg[i].setAttribute('src',sortImages[2])}
  }

  // Some explantion of the basic concept of the following code before we
  // actually start.  Essentially we are going to copy the current columns information
  // into an array to be sorted. We'll sort the column array then go back and use the information
  // we saved about the original row positions to re-order the entire table.
  // We are never really sorting more than a columns worth of data, which should keep the sorting fast.

  // Create a new array for holding row information
  var clonedRows = new Array()

  // Create a new array to store just the selected column values, not the whole row
  var originalCol = new Array();

  // Now loop through all the data row elements
  // NOTE: Starting at row 1 because row 0 contains the column titles
  for (var i=1; i<tr_elements.length - ignoreLastLines; i++) {

   // "Clone" the tr element i.e. save a copy all of its attributes and values
   clonedRows[i]=tr_elements[i].cloneNode(true);

   // Text value of the selected column on this row
   var valueCol = getTextValue(tr_elements[i].cells[indexCol]);

   // Format text value for sorting depending on its type, ie Date, Currency, number, etc..
   valueCol = FormatForType(valueCol);

   // Assign the column value AND the row number it was originally on in the table
   originalCol[i]=[valueCol,tr_elements[i].rowIndex];
  }

  // Get rid of element "0" from this array.  A value was never assigned to it because the first row
  // in the table just contained the column titles, which we did not bother to assign.
  originalCol.shift();

  // Sort the column array returning the value of a sort into a new array
  sortCol = originalCol.sort(sortCompare);

  // If it was supposed to be an Ascending sort then reverse the order
  if (sortAscending) { sortCol.reverse(); }

  // Now take the values from the sorted column array and use that information to re-arrange
  // the order of the tr_elements in the table
  for (var i=1; i < tr_elements.length - ignoreLastLines; i++) {

    var old_row = sortCol[i-1][1];
    var new_row = i;
    tr_elements[i].parentNode.replaceChild(clonedRows[old_row],tr_elements[new_row]);
  }

   // Format the table, making the rows alternating colors and highlight the sorted column
   makePretty(table_element,indexCol,ignoreLastLines);

  // Assign correct sort image icon to current column title
  sortColImage.setAttribute('src',newSortColImage);
}

// Function used by the sort routine to compare the current value in the array with the next one
function sortCompare (currValue, nextValue) {
 // Since the elements of this array are actually arrays themselves, just sort
 // on the first element which contiains the value, not the second which contains
 // the original row position
  if ( currValue[0] == nextValue[0] ) return 0;
  if ( currValue[0] < nextValue[0] ) return -1;
  if ( currValue[0] > nextValue[0] ) return 1;
}

//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------

// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
   document.ELEMENT_NODE = 1;
   document.TEXT_NODE = 3;
}

function getTextValue(el) {
  var i;
  var s;
  // Find and concatenate the values of all text nodes contained within the
  // element.
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
      s += el.childNodes[i].nodeValue;
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
             el.childNodes[i].tagName == "BR")
      s += " ";
    else
      // Use recursion to get text within sub-elements.
      s += getTextValue(el.childNodes[i]);

  return normalizeString(s);
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

function normalizeString(s) {
  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.
  return s;
}

// Function used to modify values to make then sortable depending on the type of information
function FormatForType(itm) {
  var sortValue = itm.toLowerCase();

  // If the item matches a date pattern (MM/DD/YYYY or MM/DD/YY or M/DD/YYYY)
  if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/) ||
      itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/) ||
      itm.match(/^\d[\/-]\d\d[\/-]\d\d\d\d$/) ) {

    // Convert date to YYYYMMDD format for sort comparison purposes
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    var yr = -1;

    if (itm.length == 10) {
      sortValue = itm.substr(6,4)+itm.substr(0,2)+itm.substr(3,2);
     } else if (itm.length == 9) {
      sortValue = itm.substr(5,4)+"0" + itm.substr(0,1)+itm.substr(2,2);
    } else {
      yr = itm.substr(6,2);
      if (parseInt(yr) < 50) {
        yr = '20'+yr;
      } else {
        yr = '19'+yr;
      }
        sortValue = yr+itm.substr(3,2)+itm.substr(0,2);
    }

  }



  // If the item matches a Percent patten (contains a percent sign)
  if (itm.match(/%/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
   sortValue = parseFloat(sortValue);
  }

  // If item starts with a "(" and ends with a ")" then remove them and put a negative sign in front
  if (itm.substr(0,1) == "(" & itm.substr(itm.length - 1,1) == ")") {
   itm = "-" + itm.substr(1,itm.length - 2);
  }

// If the item matches a currency pattern (starts with a dollar or negative dollar sign)
  if (itm.match(/^[£$]|(^-)/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
   if (isNaN(sortValue)) {
     sortValue = 0;
   } else {
     sortValue = parseFloat(sortValue);
   }
}

  // If the item matches a numeric pattern
  if (itm.match(/(\d*,\d*$)|(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
 //  sortValue = sortValue.replace(/,/g,'');
   if (isNaN(sortValue)) {
     sortValue = 0;
   } else {
     sortValue = parseFloat(sortValue);
   }
  }

  return sortValue;
}

//-----------------------------------------------------------------------------
// Functions to update the table appearance after a sort.
//-----------------------------------------------------------------------------

// Style class names.
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";

// Regular expressions for setting class names.
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");

function makePretty(tblEl, col, ignoreLastLines) {

  var i, j;
  var rowEl, cellEl;

  // Set style classes on each row to alternate their appearance.
  for (i = 1; i < tblEl.rows.length - ignoreLastLines; i++) {
   rowEl = tblEl.rows[i];
   rowEl.className = rowEl.className.replace(rowTest, "");
    if (i % 2 != 0)
      rowEl.className += " " + rowClsNm;
    rowEl.className = normalizeString(rowEl.className);
    // Set style classes on each column (other than the name column) to
    // highlight the one that was sorted.
    for (j = 0; j < tblEl.rows[i].cells.length; j++) {
      cellEl = rowEl.cells[j];
      cellEl.className = cellEl.className.replace(colTest, "");
      if (j == col)
        cellEl.className += " " + colClsNm;
      cellEl.className = normalizeString(cellEl.className);
    }
  }


}

// END Generic Table sort.

// =================================================

// Function to scroll to top before sorting to fix an IE bug
// Which repositions the header off the top of the screen
// if you try to sort while scrolled to bottom.
function GoTop() {
 document.getElementById('TableContainer').scrollTop = 0;
}

//]]> 
</script>
</head>
<body>
  <table cellpadding="0" cellspacing="0" border="0">
<tr><td>
<div id="TableContainer" class="TableContainer" style="height:230px;">
<table class="scrollTable">
 <thead class="fixedHeader headerFormat">
  <tr>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort"><b>NAME</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Amt</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Lvl</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Rank</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Position</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Date</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
  </tr>
 </thead>
 <tbody class="scrollContent bodyFormat" style="height:200px;">
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">$19,923.19</td>
    <td align="right">100</td>
    <td align="right">100</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">100%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="alternateRow">
    <td>Marhanen</td>
    <td align="right">$223.04</td>
    <td align="right">83</td>
    <td align="right">99%</td>
    <td>Banker</td>
    <td align="right">06/27/2006</td>
   </tr>
   <tr>
    <td>Peter</td>
    <td align="right">$121</td>
    <td align="right">567</td>
    <td align="right">23423%</td>
    <td>FishHead</td>
    <td align="right">06/06/2006</td>
   </tr>
   <tr class="alternateRow">
    <td>Jones</td>
    <td align="right">$15</td>
    <td align="right">11</td>
    <td align="right">15%</td>
    <td>Bubba</td>
    <td align="right">10/27/2005</td>
   </tr>
   <tr>
    <td>Supa-De-Dupa</td>
    <td align="right">$145</td>
    <td align="right">91</td>
    <td align="right">32%</td>
    <td>momma</td>
    <td align="right">12/15/1996</td>
   </tr>
   <tr class="alternateRow">
    <td>ClickClock</td>
    <td align="right">$1,213</td>
    <td align="right">23</td>
    <td align="right">1%</td>
    <td>Dada</td>
    <td align="right">1/30/1998</td>
   </tr>
   <tr>
    <td>Mrs. Robinson</td>
    <td align="right">$99</td>
    <td align="right">99</td>
    <td align="right">99%</td>
    <td>Wife</td>
    <td align="right">07/04/1963</td>
   </tr>
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">$19,923.19</td>
    <td align="right">100</td>
    <td align="right">100%</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">100%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="alternateRow">
    <td>Marhanen</td>
    <td align="right">$223.04</td>
    <td align="right">83</td>
    <td align="right">59%</td>
    <td>Banker</td>
    <td align="right">06/27/2006</td>
   </tr>
   <tr>
    <td>Peter</td>
    <td align="right">$121</td>
    <td align="right">567</td>
    <td align="right">534.23%</td>
    <td>FishHead</td>
    <td align="right">06/06/2006</td>
   </tr>
   <tr class="alternateRow">
    <td>Jones</td>
    <td align="right">$15</td>
    <td align="right">11</td>
    <td align="right">15%</td>
    <td>Bubba</td>
    <td align="right">10/27/2005</td>
   </tr>
   <tr>
    <td>Supa-De-Dupa</td>
    <td align="right">$145</td>
    <td align="right">91</td>
    <td align="right">42%</td>
    <td>momma</td>
    <td align="right">12/15/1996</td>
   </tr>
   <tr class="alternateRow">
    <td>ClickClock</td>
    <td align="right">$1,213</td>
    <td align="right">23</td>
    <td align="right">2%</td>
    <td>Dada</td>
    <td align="right">1/30/1998</td>
   </tr>
   <tr>
    <td>Mrs. Robinson</td>
    <td align="right">$99</td>
    <td align="right">99</td>
    <td align="right">(-10.42%)</td>
    <td>Wife</td>
    <td align="right">07/04/1963</td>
   </tr>
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">-$19,923.19</td>
    <td align="right">100</td>
    <td align="right">(-10.01%)</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">-10.20%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="total">
    <td><strong>TOTAL</strong>:</td>
    <td align="right"><strong>999999</strong></td>
    <td align="right"><strong>9999999</strong></td>
    <td align="right"><strong>99</strong></td>
    <td > </td>
    <td align="right"> </td>
   </tr>
 </tbody>
</table>
</div>
</td></tr>
</table>
</body>
</html>

How can I display an RTSP video stream in a web page?

I have published project on Github that help you to stream ip/network camera on to web browser real time without plugin require, which I contributed to open source project under MIT License that might be matched to your need, here you go:

Streaming IP/Network Camera on web browser using NodeJS

There is no full package of framework yet, but it is a kickstart that might give you a way to proceed further.
As a student, I hope this helpful and please contribute to this project.

What are the sizes used for the iOS application splash screen?

For Adobe AIR iOS Developers, take note that if your iPad Splash images "shift" or display and scale a second later, it's because there are different dimensions depending on what version of AIR you're using.

Default-Portrait.png:
768 x 1004 (AIR 3.3 and earlier)
768 x 1024 (AIR 3.4 and higher)

[email protected]:
1536 x 2008 (AIR 3.3 and earlier)
1536 x 2048 (AIR 3.4 and higher)

Reference:
http://help.adobe.com/en_US/air/build/WS901d38e593cd1bac1e63e3d129907d2886-8000.html#WS901d38e593cd1bac58d08f9112e26606ea8-8000

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

Java/Groovy - simple date reformatting

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:

12-4-2012

How to check null objects in jQuery

if ( $('#whatever')[0] ) {...}

The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties; one of them being a "length" property. You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, i.e. $(elem)[0]

Sorting objects by property values

With ES6 arrow functions it will be like this:

//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
  { brand: 'Benz', top_speed: 110 },
  { brand: 'Fiat', top_speed: 90 },
  { brand: 'Aston Martin', top_speed: 70 } ]

Array.prototype.sort() can accept a comparator function (here I used arrow notation, but ordinary functions work the same):

let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)

// [ { brand: 'Aston Martin', top_speed: 70 },
//   { brand: 'Benz', top_speed: 110 },
//   { brand: 'Fiat', top_speed: 90 },
//   { brand: 'Porsche', top_speed: 260 } ]

The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:

let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)

//[ { brand: 'Aston Martin', top_speed: 70 },
//  { brand: 'Fiat', top_speed: 90 },
//  { brand: 'Benz', top_speed: 110 },
//  { brand: 'Porsche', top_speed: 260 } ]

If you don't mind mutating the orginal array cars.sort(comparatorFunction) will do the trick.

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

Regular expression for number with length of 4, 5 or 6

If the language you use accepts {}, you can use [0-9]{4,6}.

If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?.

Difference between static class and singleton pattern?

In many cases, these two have no practical difference, especially if the singleton instance never changes or changes very slowly e.g. holding configurations.

I'd say the biggest difference is a singleton is still a normal Java Bean as oppose to a specialized static-only Java class. And because of this, a singleton is accepted in many more situations; it is in fact the default Spring Framework's instantiation strategy. The consumer may or may not know it's a singleton being passed around, it just treat it like a normal Java bean. If requirement changes and a singleton needs to become a prototype instead, as we often see in Spring, it can be done totally seamlessly without a line of code change to the consumer.

Someone else has mentioned earlier that a static class should be purely procedural e.g. java.lang.Math. In my mind, such a class should never be passed around and they should never hold anything other than static final as attributes. For everything else, use a singleton since it's much more flexible and easier to maintain.

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

"No rule to make target 'install'"... But Makefile exists

I also came across the same error. Here is the fix: If you are using Cmake-GUI:

  1. Clean the cache of the loaded libraries in Cmake-GUI File menu.
  2. Configure the libraries.
  3. Generate the Unix file.

If you missed the 3rd step:

*** No rule to make target `install'. Stop.

error will occur.

How to say no to all "do you want to overwrite" prompts in a batch file copy?

I use XCOPY with the following parameters for copying .NET assemblies:

/D /Y /R /H 

/D:m-d-y - Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.

/Y - Suppresses prompting to confirm you want to overwrite an existing destination file.

/R - Overwrites read-only files.

/H - Copies hidden and system files also.

Convert array of strings to List<string>

Just use this constructor of List<T>. It accepts any IEnumerable<T> as an argument.

string[] arr = ...
List<string> list = new List<string>(arr);

Node.js - use of module.exports as a constructor

At the end, Node is about Javascript. JS has several way to accomplished something, is the same thing to get an "constructor", the important thing is to return a function.

This way actually you are creating a new function, as we created using JS on Web Browser environment for example.

Personally i prefer the prototype approach, as Sukima suggested on this post: Node.js - use of module.exports as a constructor

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Solution for HTTP Status 404 in NetBeans IDE: Right click on your project and go to your project properties, then click on run, then input your project relative URL like index.jsp.

  1. Project->Properties
  2. Click on Run
  3. Relative URL:/index.jsp (Select your project root URL)

enter image description here

How can I get Docker Linux container information from within the container itself?

I've found out that the container id can be found in /proc/self/cgroup

So you can get the id with :

cat /proc/self/cgroup | grep -o  -e "docker-.*.scope" | head -n 1 | sed "s/docker-\(.*\).scope/\\1/"

How can I create a two dimensional array in JavaScript?

I'm not sure if anyone has answered this but I found this worked for me pretty well -

var array = [[,],[,]]

eg:

var a = [[1,2],[3,4]]

For a 2 dimensional array, for instance.

What is the difference between res.end() and res.send()?

res.send is used to send the response to the client where res.end is used to end the response you are sending.

res.send automatically call res.end So you don't have to call or mention it after res.send

How to read large text file on windows?

The integrated Text-Viewer of Total Commander can open huge files (>10GB) for viewing without any problems. It also provides different views, e.g. a Hex-View.

Android Studio SDK location

create a new folder in your android studio parent directory folder. Name it sdk or whatever you want. Select that folder from the drop down list when asked. Thats what solves it for me.

How can I align text directly beneath an image?

Your HTML:

<div class="img-with-text">
    <img src="yourimage.jpg" alt="sometext" />
    <p>Some text</p>
</div>

If you know the width of your image, your CSS:

.img-with-text {
    text-align: justify;
    width: [width of img];
}

.img-with-text img {
    display: block;
    margin: 0 auto;
}

Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.

Meaning of 'const' last in a function declaration of a class?

The const keyword used with the function declaration specifies that it is a const member function and it will not be able to change the data members of the object.

IIS7 folder permissions for web application

Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.

How can I generate a 6 digit unique number?

If you want it to start at 000001 and go to 999999:

$num_str = sprintf("%06d", mt_rand(1, 999999));

Mind you, it's stored as a string.

Show/Hide Table Rows using Javascript classes

AngularJS directives ng-show, ng-hide allows to display and hide a row:

   <tr ng-show="rw.isExpanded">
   </tr>

A row will be visible when rw.isExpanded == true and hidden when rw.isExpanded == false. ng-hide performs the same task but requires inverse condition.

Programmatically open new pages on Tabs

You can, in Firefox it works, add the attribute target="_newtab" to the anchor to force the opening of a new tab.

<a href="some url" target="_newtab">content of the anchor</a>

In javascript you can use

window.open('page.html','_newtab');

Said that, I partially agree with Sam. You shouldn't force user to open new pages or new tab without showing them a hint on what is going to happen before they click on the link.

Let me know if it works on other browser too (I don't have a chance to try it on other browser than Firefox at the moment).

Edit: added reference for ie7 Maybe this link can be useful
http://social.msdn.microsoft.com/forums/en-US/ieextensiondevelopment/thread/951b04e4-db0d-4789-ac51-82599dc60405/

How do I create a transparent Activity on Android?

I achieved it on 2.3.3 by just adding android:theme="@android:style/Theme.Translucent" in the activity tag in the manifest.

I don't know about lower versions...

Checking Value of Radio Button Group via JavaScript?

To get the value you would do this:

document.getElementById("genderf").value;

But to check, whether the radio button is checked or selected:

document.getElementById("genderf").checked;

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

Cannot make file java.io.IOException: No such file or directory

i fixed my problem by this code on linux file system

if (!file.exists())
    Files.createFile(file.toPath());

How to append text to a text file in C++?

I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.

static void appendLineToFile(string filepath, string line)
{
    std::ofstream file;
    //can't enable exception now because of gcc bug that raises ios_base::failure with useless message
    //file.exceptions(file.exceptions() | std::ios::failbit);
    file.open(filepath, std::ios::out | std::ios::app);
    if (file.fail())
        throw std::ios_base::failure(std::strerror(errno));

    //make sure write fails with exception if something is wrong
    file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);

    file << line << std::endl;
}

m2e error in MavenArchiver.getManifest()

I also faced the similar issues, changing the version from 2.0.0.RELEASE to 1.5.10.RELEASE worked for me, please try it before downgrading the maven version

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>  
</dependencies>

Horizontal list items

Here you can find a working example, with some more suggestions about dynamic resizing of the list.

I've used display:inline-block and a percentage padding so that the parent list can dynamically change size:

display:inline-block;
padding:10px 1%;
width: 30%

plus two more rules to remove padding for the first and last items.

ul#menuItems li:first-child{padding-left:0;}
ul#menuItems li:last-child{padding-right:0;}

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

Setting the DB to single-user mode didn't work for me, but taking it offline, and then bringing it back online did work. It's in the right-click menu of the DB, under Tasks.

Be sure to check the 'Drop All Active Connections' option in the dialog.

Android getText from EditText field

Try out this will solve ur problem ....

EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();

how to list all sub directories in a directory

Easy as this:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

What is the correct JSON content type?

Not everything works for content type application/json.

If you are using Ext JS form submit to upload file, be aware that the server response is parsed by the browser to create the document for the <iframe>.

If the server is using JSON to send the return object, then the Content-Type header must be set to text/html in order to tell the browser to insert the text unchanged into the document body.

See the Ext JS 3.4.0 API documentation.

Appending a line to a file only if it does not already exist

This would be a clean, readable and reusable solution using grep and echo to add a line to a file only if it doesn't already exist:

LINE='include "/configs/projectname.conf"'
FILE='lighttpd.conf'
grep -qF -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"

If you need to match the whole line use grep -xqF

Add -s to ignore errors when the file does not exist, creating a new file with just that line.

Python iterating through object attributes

UPDATED

For python 3, you should use items() instead of iteritems()

PYTHON 2

for attr, value in k.__dict__.iteritems():
        print attr, value

PYTHON 3

for attr, value in k.__dict__.items():
        print(attr, value)

This will print

'names', [a list with names]
'tweet', [a list with tweet]

shell script to remove a file if it already exist

if [ $( ls <file> ) ]; then rm <file>; fi

Also, if you redirect your output with > instead of >> it will overwrite the previous file

Add two textbox values and display the sum in a third textbox automatically

i didn't find who made elegant answer , that's why let me say :

Array.from(
   document.querySelectorAll('#txt1,#txt2')
).map(e => parseInt(e.value) || 0) // to avoid NaN
.reduce((a, b) => a+b, 0)

_x000D_
_x000D_
window.sum= () => _x000D_
 document.getElementById('result').innerHTML=    _x000D_
   Array.from(_x000D_
     document.querySelectorAll('#txt1,#txt2')_x000D_
   ).map(e=>parseInt(e.value)||0)_x000D_
   .reduce((a,b)=>a+b,0)
_x000D_
<input type="text" id="txt1" onkeyup="sum()"/>_x000D_
<input type="text" id="txt2" onkeyup="sum()"  style="margin-right:10px;"/><span id="result"></span>
_x000D_
_x000D_
_x000D_

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.

OK, the answer is easy, but read on:

col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px

The pixel numbers are the breakpoints, so for example col-xs is targeting the element when the window is smaller than 768px(likely mobile devices)...

I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6 to show you how the grid system work in the page, look at how lg, md and xs are responsive to the window size:

Bootstrap grid system, col-*-6

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

WPF Check box: Check changed handling

What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.

Uncaught ReferenceError: function is not defined with onclick

If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.

How to convert current date into string in java?

Faster :

String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));

Select distinct values from a large DataTable column

This will retrun you distinct Ids

 var distinctIds = datatable.AsEnumerable()
                    .Select(s=> new {
                        id = s.Field<string>("id"),                           
                     })
                    .Distinct().ToList();

adb devices command not working

I fixed this issue on my debian GNU/Linux system by overiding system rules that way :

mv  /etc/udev/rules.d/51-android.rules /etc/udev/rules.d/99-android.rules

I used contents from files linked at : http://rootzwiki.com/topic/258-udev-rules-for-any-device-no-more-starting-adb-with-sudo/

Identifying country by IP address

Amazon's CloudFront content delivery network can now be configured to pass this information through as a header. Given Amazon's size (they're big and stable, not going anywhere) and this is configuration over code (no third-party API to learn or code to maintain), all around believe this to be the best option.

If you do not use AWS CloudFront, I'd look into seeing if your CDN has a similar header option that can be turned on. Usually the large providers are quick to push for feature parity. And if you are not using a CDN, you could put CloudFront in front of your infrastructure and simply set the origin to resolve to whatever you are currently using.

Additionally, it also makes sense to resolve this at the CDN level. Your CDN is already having to figure out geo location to route the user to the nearest content node, might as well pass this information along and not figure it out twice through a third party API (this becomes chokepoint for your app, waiting for a geo location lookup to resolve). No need to do this work twice (and the second time, arguably less resilient [e.g., 3rd party geo lookup]).

https://aws.amazon.com/blogs/aws/enhanced-cloudfront-customization/

Geo-Targeting – CloudFront will detect the user’s country of origin and pass along the county code to you in the CloudFront-Viewer-Country header. You can use this information to customize your responses without having to use URLs that are specific to each country.

How to detect simple geometric shapes using OpenCV

If you have only these regular shapes, there is a simple procedure as follows :

  1. Find Contours in the image ( image should be binary as given in your question)
  2. Approximate each contour using approxPolyDP function.
  3. First, check number of elements in the approximated contours of all the shapes. It is to recognize the shape. For eg, square will have 4, pentagon will have 5. Circles will have more, i don't know, so we find it. ( I got 16 for circle and 9 for half-circle.)
  4. Now assign the color, run the code for your test image, check its number, fill it with corresponding colors.

Below is my example in Python:

import numpy as np
import cv2

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Below is the output:

enter image description here

Remember, it works only for regular shapes.

Alternatively to find circles, you can use houghcircles. You can find a tutorial here.

Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.

You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf

Importing a Maven project into Eclipse from Git

You should note that putting generated metadata under version control (let it be git or any other scm), is not a very good idea if there are more than one developer working on the codebase. Two developers may have a totally different project or classpath setup. Just as a heads up in case you intends to share the code at some time...

Displaying a webcam feed using OpenCV and Python

change import cv to import cv2.cv as cv See also the post here.

How to utilize date add function in Google spreadsheet?

=TO_DATE(TO_PURE_NUMBER(Insert Date cell, i.e. AM4)+[how many days to add in numbers, e.g. 3 days])

Looks like in practice:

=TO_DATE(TO_PURE_NUMBER(AM4)+3)

Essentially you are converting the date into a pure number and back into a date again.

How do I remove blue "selected" outline on buttons?

That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!

Use this to remove this effect:

button {
  outline: none; // this one
}

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

I encountered the same error. JAVA_HOME pointing to the correct version of JDK. All support libraries and build tools updated. Was still facing the same issue.

I am using Android annotations in my project. I added a new View..and there was already an existing view with the same name in the Java file. When I run the project, instead of indicating the view already exists, I was receiving the above error.

Check your java files errors if other solutions does not work.

How to import Angular Material in project?

UPDATE for Angular 9.0.1

Since this version there is no barrel file for massive exports in the root index.d.ts. The assets imports should be:

import { NgModule } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule} from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

import {
  MatButtonModule,
  MatMenuModule,
  MatToolbarModule,
  MatIconModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ]
})
export class MaterialModule {}

source: @angular/material/index.d.ts' is not a module


MaterialModule was depreciated in version 2.0.0-beta.3 and it has been removed completely in version 2.0.0-beta.11. See this CHANGELOG for more details. Please go through the breaking changes.

Breaking changes

  • Angular Material now requires Angular 4.4.3 or greater
  • MaterialModule has been removed.
  • For beta.11, we've made the decision to deprecate the "md" prefix completely and use "mat" moving forward.

Please go through CHANGELOG we will get more answer!

Example shown below cmd

npm install --save @angular/material @angular/animations @angular/cdk
npm install --save angular/material2-builds angular/cdk-builds

Create file (material.module.ts) inside the 'app' folder

import { NgModule } from '@angular/core';

import {
  MatButtonModule,
  MatMenuModule,
  MatToolbarModule,
  MatIconModule,
  MatCardModule
} from '@angular/material';

@NgModule({
  imports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ],
  exports: [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule
  ]
})
export class MaterialModule {}

import on app.module.ts

import { MaterialModule } from './material.module';

Your component html file

<div>
  <mat-toolbar color="primary">
    <span><mat-icon>mood</mat-icon></span>

    <span>Yay, Material in Angular 2!</span>

    <button mat-icon-button [mat-menu-trigger-for]="menu">
      <mat-icon>more_vert</mat-icon>
    </button>
  </mat-toolbar>
  <mat-menu x-position="before" #menu="matMenu">
    <button mat-menu-item>Option 1</button>
    <button mat-menu-item>Option 2</button>
  </mat-menu>

  <mat-card>
    <button mat-button>All</button>
    <button mat-raised-button>Of</button>
    <button mat-raised-button color="primary">The</button>
    <button mat-raised-button color="accent">Buttons</button>
  </mat-card>

  <span class="done">
    <button mat-fab>
      <mat-icon>check circle</mat-icon>
    </button>
  </span>
</div>

Add global css 'style.css'

@import 'https://fonts.googleapis.com/icon?family=Material+Icons';
@import '~@angular/material/prebuilt-themes/indigo-pink.css'; 

Your component css

body {
  margin: 0;
  font-family: Roboto, sans-serif;
}

mat-card {
  max-width: 80%;
  margin: 2em auto;
  text-align: center;
}

mat-toolbar-row {
  justify-content: space-between;
}

.done {
  position: fixed;
  bottom: 20px;
  right: 20px;
  color: white;
}

If any one didn't get output use below instruction

instead of above interface (material.module.ts) u can directly use below code also in the app.module.ts.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MdButtonModule, MdCardModule, MdMenuModule, MdToolbarModule, MdIconModule, MatAutocompleteModule, MatInputModule,MatFormFieldModule } from '@angular/material';

So this case u don't want to import

import { MaterialModule } from './material.module';

in the app.module.ts

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Centering a div block without the width

Simple fix that works in old browsers (but does use tables, and requires a height to be set):

<div style="width:100%;height:40px;position:absolute;top:50%;margin-top:-20px;">
  <table style="width:100%"><tr><td align="center">
    In the middle
  </td></tr></table>
</div>

How do I use brew installed Python as the default Python?

Use pyenv instead to install and switch between versions of Python. I've been using rbenv for years which does the same thing, but for Ruby. Before that it was hell managing versions.

Consult pyenv's github page for installation instructions. Basically it goes like this: - Install pyenv using homebrew. brew install pyenv - Add a function to the end of your shell startup script so pyenv can do it's magic. echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

  • Use pyenv to install however many different versions of Python you need. pyenv install 3.7.7.
  • Set the default (global) version to a modern version you just installed. pyenv global 3.7.7.
  • If you work on a project that needs to use a different version of python, look into pyevn local. This creates a file in your project's folder that specifies the python version. Pyenv will look override the global python version with the version in that file.

Using jquery to get all checked checkboxes with a certain class name

$(document).ready(function(){
    $('input.checkD[type="checkbox"]').click(function(){
        if($(this).prop("checked") == true){
            $(this).val('true');
        }
        else if($(this).prop("checked") == false){
            $(this).val('false');
        }
    });
});

Split string into strings by length?

def split2len(s, n):
    def _f(s, n):
        while s:
            yield s[:n]
            s = s[n:]
    return list(_f(s, n))

Force GUI update from UI Thread

If you only need to update a couple controls, .update() is sufficient.

btnMyButton.BackColor=Color.Green; // it eventually turned green, after a delay
btnMyButton.Update(); // after I added this, it turned green quickly

PHP Include for HTML?

I figured out a simple solution to the PHP include stuff. Simply rename all your .html files to .php and your're good to go.

Restore a postgres backup file using the command line?

If you have a backup SQL file then you can easily Restore it. Just follow the instructions, given in the below

1. At first, create a database using pgAdmin or whatever you want (for example my_db is our created db name)
2. Now Open command line window
3. Go to Postgres bin folder. For example:  cd "C:\ProgramFiles\PostgreSQL\pg10\bin"
4. Enter the following command to restore your database: psql.exe -U postgres -d my_db -f D:\Backup\backup_file_name.sql 

Type password for your postgres user if needed and let Postgres to do its work. Then you can check the restore process.

Setting session variable using javascript

You could better use the localStorage of the web browser.

You can find a reference here

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

Those who updated their device to Android 4.2 Jelly Bean or higher or having a 4.2 JB or higher android powered device, will not found the Developers Options in Settings menu. The Developers Options hide by default on 4.2 jelly bean and later android versions. Follow the below steps to Unhide Developers Options.

  1. Go to Settings>>About (On most Android Smartphone and tablet) OR

Go to Settings>> More/General tab>> About (On Samsung Galaxy S3, Galaxy S4, Galaxy Note 8.0, Galaxy Tab 3 and other galaxy Smartphone and tablet having Android 4.2/4.3 Jelly Bean) OR

Go to Settings>> General>> About (On Samsung Galaxy Note 2, Galaxy Note 3 and some other Galaxy devices having Android 4.3 Jelly Bean or 4.4 KitKat) OR

Go to Settings> About> Software Information> More (On HTC One or other HTC devices having Android 4.2 Jelly Bean or higher) 2. Now Scroll onto Build Number and tap it 7 times repeatedly. A message will appear saying that u are now a developer.

  1. Just return to the previous menu to see developer option.

Credit to www.androidofficer.com

How do you dynamically allocate a matrix?

Here is the most clear & intuitive way i know to allocate a dynamic 2d array in C++. Templated in this example covers all cases.

template<typename T> T** matrixAllocate(int rows, int cols, T **M)
{
    M = new T*[rows];
    for (int i = 0; i < rows; i++){
        M[i] = new T[cols];
    }
    return M;
}

... 

int main()
{
    ...
    int** M1 = matrixAllocate<int>(rows, cols, M1);
    double** M2 = matrixAllocate(rows, cols, M2);
    ...
}

include external .js file in node.js app

you can put

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

at the top of your car.js file for it to work, or you can do what Raynos said to do.

Adding files to a GitHub repository

Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.

How to press back button in android programmatically?

onBackPressed() is supported since: API Level 5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        onBackPressed();
    }
}

@Override
public void onBackPressed() {
    //this is only needed if you have specific things
    //that you want to do when the user presses the back button.
    /* your specific things...*/
    super.onBackPressed();   
}

.NET String.Format() to add commas in thousands place for a number

String.Format("{0:#,###,###.##}", MyNumber)

That will give you commas at the relevant points.

Incrementing a variable inside a Bash loop

I had the same $count variable in a while loop getting lost issue.

@fedorqui's answer (and a few others) are accurate answers to the actual question: the sub-shell is indeed the problem.

But it lead me to another issue: I wasn't piping a file content... but the output of a series of pipes & greps...

my erroring sample code:

count=0
cat /etc/hosts | head | while read line; do
  ((count++))
  echo $count $line
done
echo $count

and my fix thanks to the help of this thread and the process substitution:

count=0
while IFS= read -r line; do
  ((count++))
  echo "$count $line"
done < <(cat /etc/hosts | head)
echo "$count"

PostgreSQL ERROR: canceling statement due to conflict with recovery

Likewise, here's a 2nd caveat to @Artif3x elaboration of @max-malysh's excellent answer, both above.

With any delayed application of transactions from the master the follower(s) will have an older, stale view of the data. Therefore while providing time for the query on the follower to finish by setting max_standby_archive_delay and max_standby_streaming_delay makes sense, keep both of these caveats in mind:

  • the value of the follower as a standby / backup diminishes
  • any other queries running on the follower may return stale data.

If the value of the follower for backup ends up being too much in conflict with hosting queries, one solution would be multiple followers, each optimized for one or the other.

Also, note that several queries in a row can cause the application of wal entries to keep being delayed. So when choosing the new values, it’s not just the time for a single query, but a moving window that starts whenever a conflicting query starts, and ends when the wal entry is finally applied.

Vue.js img src concatenate variable and text

If it helps, I am using the following to get a gravatar image:

<img
        :src="`https://www.gravatar.com/avatar/${this.gravatarHash(email)}?s=${size}&d=${this.defaultAvatar(email)}`"
        class="rounded-circle"
        :width="size"
    />

Powershell equivalent of bash ampersand (&) for forking/running background processes

I've used the solution described here http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.

De-obfuscate Javascript code to make it readable again

I have tried both of online jsbeautifier(jsbeautifier, jsnice), these tools gave me beautiful js code,

but couldn't copy for very large js (must be bug, when i copy, copied buffer contains only one character '-').

I found that only working solution was prettyjs:

http://www.thaoh.net/prettyjs/

Finding the id of a parent div using Jquery

JQUery has a .parents() method for moving up the DOM tree you can start there.

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />
</p>

and

$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);
    $("#messages").html(feedback);
});

Not quite sure how your validate and feedback are working, but you get the idea.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How to insert an item into an array at a specific index (JavaScript)?

Here are two ways :

_x000D_
_x000D_
const array = [ 'My', 'name', 'Hamza' ];_x000D_
_x000D_
array.splice(2, 0, 'is');_x000D_
_x000D_
console.log("Method 1 : ", array.join(" "));
_x000D_
_x000D_
_x000D_

OR

_x000D_
_x000D_
Array.prototype.insert = function ( index, item ) {_x000D_
    this.splice( index, 0, item );_x000D_
};_x000D_
_x000D_
const array = [ 'My', 'name', 'Hamza' ];_x000D_
array.insert(2, 'is');_x000D_
_x000D_
console.log("Method 2 : ", array.join(" "));
_x000D_
_x000D_
_x000D_

Use component from another module

One big and great approach is to load the module from a NgModuleFactory, you can load a module inside another module by calling this:

constructor(private loader: NgModuleFactoryLoader, private injector: Injector) {}

loadModule(path: string) {
    this.loader.load(path).then((moduleFactory: NgModuleFactory<any>) => {
        const entryComponent = (<any>moduleFactory.moduleType).entry;
        const moduleRef = moduleFactory.create(this.injector);
        const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
        this.lazyOutlet.createComponent(compFactory);
    });
}

I got this from here.

Meaning of *& and **& in C++

Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr; , it means that you have a Pointer * to an Integer variable int. Also when it's declared int **ptr2;, it is a Pointer variable * to a Pointer variable * pointing to an Integer variable int , which is the same as "(int *)* ptr2;"

Now, following the syntax by declaring int*& rPtr;, we say it's a Reference & to a Pointer * that points to a variable of type int. Finally, you can apply again this approach also for int**& rPtr2; concluding that it signifies a Reference & to a Pointer * to a Pointer * to an Integer int.

C++ - struct vs. class

The other difference is that

template<class T> ...

is allowed, but

template<struct T> ...

is not.

How to get first object out from List<Object> using Linq

There are a bunch of such methods:
.First .FirstOrDefault .Single .SingleOrDefault
Choose which suits you best.

Verify host key with pysftp

Do not set cnopts.hostkeys = None (as the second most upvoted answer shows), unless you do not care about security. You lose a protection against Man-in-the-middle attacks by doing so.


Use CnOpts.hostkeys (returns HostKeys) to manage trusted host keys.

cnopts = pysftp.CnOpts(knownhosts='known_hosts')

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

where the known_hosts contains a server public key(s)] in a format like:

example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

If you do not want to use an external file, you can also use

from base64 import decodebytes
# ...

keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add('example.com', 'ssh-rsa', key)

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

Though as of pysftp 0.2.9, this approach will issue a warning, what seems like a bug:
"Failed to load HostKeys" warning while connecting to SFTP server with pysftp


An easy way to retrieve the host key in the needed format is using OpenSSH ssh-keyscan:

$ ssh-keyscan example.com
# example.com SSH-2.0-OpenSSH_5.3
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

(due to a bug in pysftp, this does not work, if the server uses non-standard port – the entry starts with [example.com]:port + beware of redirecting ssh-keyscan to a file in PowerShell)

You can also make the application do the same automatically:
Use Paramiko AutoAddPolicy with pysftp
(It will automatically add host keys of new hosts to known_hosts, but for known host keys, it will not accept a changed key)


Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

See my article Where do I get SSH host key fingerprint to authorize the server?
It's for my WinSCP SFTP client, but most information there is valid in general.


If you need to verify the host key using its fingerprint only, see Python - pysftp / paramiko - Verify host key using its fingerprint.

Starting Docker as Daemon on Ubuntu

There are multiple popular repositories offering docker packages for Ubuntu. The package docker.io is (most likely) from the Ubuntu repository. Another popular one is http://get.docker.io/ubuntu which offers a package lxc-docker (I am running the latter because it ships updates faster). Make sure only one package is installed. Not quite sure if removal of the packages cleans up properly. If sudo service docker restart still does not work, you may have to clean up manually in /etc/.

Set ANDROID_HOME environment variable in mac

Here are the steps:

  1. Open Terminal
  2. Type touch .bash_profile and press Enter
  3. Now Type open .bash_profile and again press Enter
  4. A textEdit file will be opened
  5. Now type export ANDROID_HOME="Users/Your_User_Name/Library/Android/sdk"
  6. Then in next line type export PATH="${PATH}:/$ANDROID_HOME/platform-tools:/$ANDROID_HOME/tools:/$ANDROID_HOME/tools/bin"
  7. Now save this .bash_profile file
  8. Close the Terminal

To verify if Path is set successfully open terminal again and type adb if adb version and other details are displayed that means path is set properly.

How can one create an overlay in css?

I would suggest using css attributes to do this. You can use position:absolute to position an element on top of another.

For example:

<div id="container">
   <div id="on-top">Top!</div>
   <div id="on-bottom">Bottom!</div>
</div>

and css

#container {position:relative;}
#on-top {position:absolute; z-index:5;}
#on-bottom {position:absolute; z-index:4;}

I would take a look at this for advice: http://www.w3schools.com/cssref/pr_class_position.asp

And finally here is a jsfiddle to show you my example

http://jsfiddle.net/Wgfw6/

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

How to cast from List<Double> to double[] in Java?

High performance - every Double object wraps a single double value. If you want to store all these values into a double[] array, then you have to iterate over the collection of Double instances. A O(1) mapping is not possible, this should be the fastest you can get:

 double[] target = new double[doubles.size()];
 for (int i = 0; i < target.length; i++) {
    target[i] = doubles.get(i).doubleValue();  // java 1.4 style
    // or:
    target[i] = doubles.get(i);                // java 1.5+ style (outboxing)
 }

Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive method:

public static double[] toPrimitive(Double[] array) {
  if (array == null) {
    return null;
  } else if (array.length == 0) {
    return EMPTY_DOUBLE_ARRAY;
  }
  final double[] result = new double[array.length];
  for (int i = 0; i < array.length; i++) {
    result[i] = array[i].doubleValue();
  }
  return result;
}

(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )

By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[] from the list, then to unwrap the double values.

How to allow http content within an iframe on a https site

You could try scraping whatever you need with PHP or another server side language, then put the iframe to the scraped content. Here's an example with PHP:

scrapedcontent.php:

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

index.html:

<iframe src="scrapedcontent.php"></iframe>

How can I get enum possible values in a MySQL database?

You can use this syntax for get enum possible values in MySQL QUERY :

$syntax = "SELECT COLUMN_TYPY FROM information_schema.`COLUMNS` 
WHERE TABLE_NAME = '{$THE_TABLE_NAME}' 
AND COLUMN_NAME = '{$THE_COLUMN_OF_TABLE}'";

and you get value, example : enum('Male','Female')

this is example sytax php:

<?php
function ($table,$colm){

// mysql query.
$syntax = mysql_query("SELECT COLUMN_TYPY FROM information_schema.`COLUMNS` 
WHERE TABLE_NAME = '$table' AND COLUMN_NAME ='$colm'");

if (!mysql_error()){
 //Get a array possible values from table and colm.
 $array_string = mysql_fetch_array($syntax);

    //Remove part string
    $string = str_replace("'", "", $array_string['COLUMN_TYPE']);
    $string = str_replace(')', "", $string);
    $string = explode(",",substr(5,$string));
}else{
    $string = "error mysql :".mysql_error();
}
// Values is (Examples) Male,Female,Other
return $string;
}
?>

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

I solved this issue to update .htaccess file inside your workspace (like C:\xampp\htdocs\Nayan\.htaccess in my case).

Just update or add this php_value max_execution_time 300 line before # END WordPress. Then save the file and try to install again.

If the error occurs again, you can maximize the value from 300 to 600.

Portable way to get file size (in bytes) in shell?

Even though du usually prints disk usage and not actual data size, GNU coreutils du can print file's "apparent size" in bytes:

du -b FILE

But it won't work under BSD, Solaris, macOS, ...

How do I call a function twice or more times consecutively?

You could define a function that repeats the passed function N times.

def repeat_fun(times, f):
    for i in range(times): f()

If you want to make it even more flexible, you can even pass arguments to the function being repeated:

def repeat_fun(times, f, *args):
    for i in range(times): f(*args)

Usage:

>>> def do():
...   print 'Doing'
... 
>>> def say(s):
...   print s
... 
>>> repeat_fun(3, do)
Doing
Doing
Doing
>>> repeat_fun(4, say, 'Hello!')
Hello!
Hello!
Hello!
Hello!

How do you remove Subversion control for a folder?

I use rsync:

# copy folder src to srcStripped excluding subfolders named '.svn'. retain dates, verbose output
rsync -av --exclude .svn src srcStripped

Where can I find my Facebook application id and secret key?

Dashboard -> [your app] -> [View Details] -> Settings -> Basic

source

Command to get latest Git commit hash from a branch

Note that when using "git log -n 1 [branch_name]" option. -n returns only one line of log but order in which this is returned is not guaranteed. Following is extract from git-log man page

.....
.....
Commit Limiting

Besides specifying a range of commits that should be listed using the special notations explained in the     description, additional commit limiting may be applied.

Using more options generally further limits the output (e.g. --since=<date1> limits to commits newer than <date1>, and using it with --grep=<pattern> further limits to commits whose log message has a line that matches <pattern>), unless otherwise noted.

Note that these are applied before commit ordering and formatting options, such as --reverse.

-<number>
-n <number>
.....
.....

Open file by its full path in C++

Normally one uses the backslash character as the path separator in Windows. So:

ifstream file;
file.open("C:\\Demo.txt", ios::in);

Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.

Unclosed Character Literal error

String y = "hello";

would work (note the double quotes).

char y = 'h'; this will work for chars (note the single quotes)

but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.

Pdf.js: rendering a pdf file using a base64 file source instead of url

According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData}); Codetoffel answer does work just fine for me though.

Referring to the null object in Python

In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...

Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.

Anyway, you can have a look at:

How to change href attribute using JavaScript after opening the link in a new window?

Your onclick fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:

function changeLink() {
    var link = document.getElementById("mylink");

    window.open(
      link.href,
      '_blank'
    );

    link.innerHTML = "facebook";
    link.setAttribute('href', "http://facebook.com");

    return false;
}

How to find out the location of currently used MySQL configuration file in linux

login to mysql with proper credential and used mysql>SHOW VARIABLES LIKE 'datadir'; that will give you path of where mysql stored

use jQuery to get values of selected checkboxes

$("#locationthemes").prop("checked")

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

Ambiguous overload call to abs(double)

In my cases, I solved the problem when using the labs() instead of abs().

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

First few lines: man head.

Append lines: use the >> operator (?) in Bash:

echo 'This goes at the end of the file' >> file

C# Reflection: How to get class reference from string?

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

Git Bash doesn't see my PATH

Create a User variable named Path and add as value %Path%, from what I noticed Git Bash only sees User Variables and not System Variables. By doing the mentioned procedure you'll expose your System Variable in the User Variables.

How to detect the physical connected state of a network cable/connector?

I use this command to check a wire is connected:

cd /sys/class/net/
grep "" eth0/operstate

If the result will be up or down. Sometimes it shows unknown, then you need to check

eth0/carrier

It shows 0 or 1

TSQL - Cast string to integer or return default value

Joseph's answer pointed out ISNUMERIC also handles scientific notation like '1.3e+3' but his answer doesn't handle this format of number.

Casting to a money or float first handles both the currency and scientific issues:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TryConvertInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TryConvertInt]
GO

CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS bigint
AS
BEGIN
    DECLARE @IntValue bigint;

    IF (ISNUMERIC(@Value) = 1)
        IF (@Value like '%e%')
            SET @IntValue = CAST(Cast(@Value as float) as bigint);
        ELSE
            SET @IntValue = CAST(CAST(@Value as money) as bigint);
    ELSE
        SET @IntValue = NULL;

    RETURN @IntValue;
END

The function will fail if the number is bigger than a bigint.

If you want to return a different default value, leave this function so it is generic and replace the null afterwards:

SELECT IsNull(dbo.TryConvertInt('nan') , 1000);

Is there a performance difference between a for loop and a for-each loop?

The following code:

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

interface Function<T> {
    long perform(T parameter, long x);
}

class MyArray<T> {

    T[] array;
    long x;

    public MyArray(int size, Class<T> type, long x) {
        array = (T[]) Array.newInstance(type, size);
        this.x = x;
    }

    public void forEach(Function<T> function) {
        for (T element : array) {
            x = function.perform(element, x);
        }
    }
}

class Compute {
    int factor;
    final long constant;

    public Compute(int factor, long constant) {
        this.factor = factor;
        this.constant = constant;
    }

    public long compute(long parameter, long x) {
        return x * factor + parameter + constant;
    }
}

public class Main {

    public static void main(String[] args) {
        List<Long> numbers = new ArrayList<Long>(50000000);
        for (int i = 0; i < 50000000; i++) {
            numbers.add(i * i + 5L);
        }

        long x = 234553523525L;

        long time = System.currentTimeMillis();
        for (int i = 0; i < numbers.size(); i++) {
            x += x * 7 + numbers.get(i) + 3;
        }
        System.out.println(System.currentTimeMillis() - time);
        System.out.println(x);
        x = 0;
        time = System.currentTimeMillis();
        for (long i : numbers) {
            x += x * 7 + i + 3;
        }
        System.out.println(System.currentTimeMillis() - time);
        System.out.println(x);
        x = 0;
        numbers = null;
        MyArray<Long> myArray = new MyArray<Long>(50000000, Long.class, 234553523525L);
        for (int i = 0; i < 50000000; i++) {
            myArray.array[i] = i * i + 3L;
        }
        time = System.currentTimeMillis();
        myArray.forEach(new Function<Long>() {

            public long perform(Long parameter, long x) {
                return x * 8 + parameter + 5L;
            }
        });
        System.out.println(System.currentTimeMillis() - time);
        System.out.println(myArray.x);
        myArray = null;
        myArray = new MyArray<Long>(50000000, Long.class, 234553523525L);
        for (int i = 0; i < 50000000; i++) {
            myArray.array[i] = i * i + 3L;
        }
        time = System.currentTimeMillis();
        myArray.forEach(new Function<Long>() {

            public long perform(Long parameter, long x) {
                return new Compute(8, 5).compute(parameter, x);
            }
        });
        System.out.println(System.currentTimeMillis() - time);
        System.out.println(myArray.x);
    }
}

Gives following output on my system:

224
-699150247503735895
221
-699150247503735895
220
-699150247503735895
219
-699150247503735895

I'm running Ubuntu 12.10 alpha with OracleJDK 1.7 update 6.

In general HotSpot optimizes a lot of indirections and simple reduntant operations, so in general you shouldn't worry about them unless there are a lot of them in seqence or they are heavily nested.

On the other hand, indexed get on LinkedList is much slower than calling next on iterator for LinkedList so you can avoid that performance hit while retaining readability when you use iterators (explicitly or implicitly in for-each loop).

How to update attributes without validation

You can do something like:

object.attribute = value
object.save(:validate => false)

How to access the request body when POSTing using Node.js and Express?

What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.

The error you're getting doesn't appear to be related to any of the code you've shown us.

If you want to get the raw request, set handlers on request for the data and end events (and, of course, remove any invocations of express.bodyParser()). Note that the data events will occur in chunks, and that unless you set an encoding for the data event those chunks will be buffers, not strings.

Mock a constructor with parameter

Mockito has limitations testing final, static, and private methods.

with jMockit testing library, you can do few stuff very easy and straight-forward as below:

Mock constructor of a java.io.File class:

new MockUp<File>(){
    @Mock
    public void $init(String pathname){
        System.out.println(pathname);
        // or do whatever you want
    }
};
  • the public constructor name should be replaced with $init
  • arguments and exceptions thrown remains same
  • return type should be defined as void

Mock a static method:

  • remove static from the method mock signature
  • method signature remains same otherwise

Making macOS Installer Packages which are Developer ID ready

FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg

Zip folder in C#

From the DotNetZip help file, http://dotnetzip.codeplex.com/releases/

using (ZipFile zip = new ZipFile())
{
   zip.UseUnicodeAsNecessary= true;  // utf-8
   zip.AddDirectory(@"MyDocuments\ProjectX");
   zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 
   zip.Save(pathToSaveZipFile);
}

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

Can you change what a symlink points to after it is created?

Yes, you can!

$ ln -sfn source_file_or_directory_name softlink_name

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

android.content.res.Resources$NotFoundException: String resource ID #0x0

You can do it. this is a easy way.

txtTopicNo.setText(10+"");

Android getting value from selected radiobutton

Tested and working. Check this

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioGroup = (RadioGroup) findViewById(R.id.radio);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

xml

<RadioGroup
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />

    </RadioGroup>

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Extracting specific columns from a data frame

For some reason only

df[, (names(df) %in% c("A","B","E"))]

worked for me. All of the above syntaxes yielded "undefined columns selected".

Add the loading screen in starting of the android application

Please read this article

Chris Stewart wrote there:

Splash screens just waste your time, right? As an Android developer, when I see a splash screen, I know that some poor dev had to add a three-second delay to the code.

Then, I have to stare at some picture for three seconds until I can use the app. And I have to do this every time it’s launched. I know which app I opened. I know what it does. Just let me use it!

Splash Screens the Right Way

I believe that Google isn’t contradicting itself; the old advice and the new stand together. (That said, it’s still not a good idea to use a splash screen that wastes a user’s time. Please don’t do that.)

However, Android apps do take some amount of time to start up, especially on a cold start. There is a delay there that you may not be able to avoid. Instead of leaving a blank screen during this time, why not show the user something nice? This is the approach Google is advocating. Don’t waste the user’s time, but don’t show them a blank, unconfigured section of the app the first time they launch it, either.

If you look at recent updates to Google apps, you’ll see appropriate uses of the splash screen. Take a look at the YouTube app, for example.

enter image description here

How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

vim ~/.tmux.conf

In the configuration file add the following line:

set -g history-limit 5000

Log out and log in again, start a new tmux windows and your limit is 5000 now.

Visual Studio replace tab with 4 spaces?

If you don't see the formatting option, you can do Tools->Import and Export settings to import the missing one.

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

All that was necessary for me, a Ubuntu user, was to change the owner of the ~/.android directory. In a terminal type the following command:

sudo chown -R username:username ~/.android

Obviously, you must replace "username" (twice) with your username.

I wasn't sure if I should post this as an answer because the original poster's question was concerning Windows Vista, not Ubuntu. However I found this post whilst searching for the answer on Ubuntu so I believe it is pertinent. I don't have sufficient reputation to comment on +Maher Gamal's answer, though, which is what lead me to this answer. Hopefully someone else finds it useful!

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

As per Link: http://bavotasan.com/2011/style-select-box-using-only-css/ there are lot of extra rework that needs to be done(Put extra div and position the image there. Also the design will break as the option drilldown will be mis alligned to the the select.

Here is an easy and simple way which will allow you to put your own dropdown image and remove the browser default dropdown.(Without using any extra div). Its cross browser as well.

HTML

<select class="dropdown" name="drop-down">
  <option value="select-option">Please select...</option>
  <option value="Local-Community-Enquiry">Option 1</option>
  <option value="Bag-Packing-in-Store">Option 2</option>
</select>

CSS

select.dropdown {
  margin: 0px;
  margin-top: 12px;
  height: 48px;
  width: 100%;
  border-width: 1px;
  border-style: solid;
  border-color: #666666;
  padding: 9px;
  font-family: tescoregular;
  font-size: 16px;
  color: #666666;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
  -moz-appearance: none;
  appearance: none;
  background: url('yoururl/dropdown.png') no-repeat 97% 50% #ffffff;
  background-size: 11px 7px;
}

How to programmatically move, copy and delete files and directories on SD?

  1. Permissions:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
  2. Get SD card root folder:

    Environment.getExternalStorageDirectory()
    
  3. Delete file: this is an example on how to delete all empty folders in a root folder:

    public static void deleteEmptyFolder(File rootFolder){
        if (!rootFolder.isDirectory()) return;
    
        File[] childFiles = rootFolder.listFiles();
        if (childFiles==null) return;
        if (childFiles.length == 0){
            rootFolder.delete();
        } else {
            for (File childFile : childFiles){
                deleteEmptyFolder(childFile);
            }
        }
    }
    
  4. Copy file:

    public static void copyFile(File src, File dst) throws IOException {
        FileInputStream var2 = new FileInputStream(src);
        FileOutputStream var3 = new FileOutputStream(dst);
        byte[] var4 = new byte[1024];
    
        int var5;
        while((var5 = var2.read(var4)) > 0) {
            var3.write(var4, 0, var5);
        }
    
        var2.close();
        var3.close();
    }
    
  5. Move file = copy + delete source file

How can I group data with an Angular filter?

In addition to the accepted answer you can use this if you want to group by multiple columns:

<ul ng-repeat="(key, value) in players | groupBy: '[team,name]'">

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

Start your XAMPP server by using:

  • {XAMPP}\xampp-control.exe
  • {XAMPP}\apache_start.bat

Then you have to use the URI http://localhost/index.html because htdocs is the document root of the Apache server.

If you're getting redirected to http://localhost/xampp/*, then index.php located in the htdocs folder is the problem because index.php files have a higher priority than index.html files. You could temporarily rename index.php.

Using Jasmine to spy on a function without an object

A very simple way:

import * as myFunctionContainer from 'whatever-lib';

const fooSpy = spyOn(myFunctionContainer, 'myFunc');

Express-js can't GET my static files, why?

Try accessing it with http://localhost:3001/default.css.

   app.use(express.static(__dirname + '/styles'));

You are actually giving it the name of folder i.e. styles not your suburl.

Different ways of loading a file as an InputStream

All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String) and class.getClassLoader().getResourceAsStream(String). This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).

MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!  
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!

Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String) in the past and haven't had any problems.

PS: I also posted this over here

Converting SVG to PNG using C#

I'm using Batik for this. The complete Delphi code:

procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
  StartInfo : TStartupInfo;
  ProcInfo : TProcessInformation;
  CreateOK : Boolean;
begin
  FillChar(StartInfo, SizeOf(TStartupInfo), #0);
  FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
              CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);
  if CreateOK then begin
    //may or may not be needed. Usually wait for child processes
    if Wait then
      WaitForSingleObject(ProcInfo.hProcess, INFINITE);
  end else
    ShowMessage('Unable to run ' + ProgramName);

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
end;

procedure ConvertSVGtoPNG(aFilename: String);
const
  ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
  ExecNewProcess(ExecLine + aFilename, True);
end;

Best way to log POST data in Apache?

You can use [ModSecurity][1] to view POST data.

Install on Debian/Ubuntu:

$ sudo apt install libapache2-mod-security2

Use the recommended configuration file:

$ sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

Reload Apache:

$ sudo service apache2 reload

You will now find your data logged under /var/log/apache2/modsec_audit.log

$ tail -f /var/log/apache2/modsec_audit.log
--2222229-A--
[23/Nov/2017:11:36:35 +0000] 
--2222229-B--
POST / HTTP/1.1
Content-Type: application/json
User-Agent: curl
Host: example.com

--2222229-C--
{"test":"modsecurity"}

Adding maven nexus repo to my pom.xml

It seems the answers here do not support an enterprise use case where a Nexus server has multiple users and has project-based isolation (protection) based on user id ALONG with using an automated build (CI) system like Jenkins. You would not be able to create a settings.xml file to satisfy the different user ids needed for different projects. I am not sure how to solve this, except by opening Nexus up to anonymous access for reading repositories, unless the projects could store a project-specific generic user id in their pom.xml.

How to know function return type and argument types?

Yes, you should use docstrings to make your classes and functions more friendly to other programmers:

More: http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring

Some editors allow you to see docstrings while typing, so it really makes work easier.

How do I detect if Python is running as a 64-bit application?

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

Why doesn't Git ignore my specified file?

Make sure the .gitignore does not have a extension!! It can't be .gitignore.txt, in windows just name the file .gitignore. and it will work.

setTimeout in for-loop does not print consecutive values

You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.

function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 100);
}

for (var i = 1; i <= 2; ++i)
  doSetTimeout(i);

If you don't do something like this (and there are other variations on this same idea), then each of the timer handler functions will share the same variable "i". When the loop is finished, what's the value of "i"? It's 3! By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private "i" to use.

edit — there have been a couple of comments over time in which some confusion was evident over the fact that setting up a few timeouts causes the handlers to all fire at the same time. It's important to understand that the process of setting up the timer — the calls to setTimeout() — take almost no time at all. That is, telling the system, "Please call this function after 1000 milliseconds" will return almost immediately, as the process of installing the timeout request in the timer queue is very fast.

Thus, if a succession of timeout requests is made, as is the case in the code in the OP and in my answer, and the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid succession.

If what you need is for the handlers to be called at intervals, you can either use setInterval(), which is called exactly like setTimeout() but which will fire more than once after repeated delays of the requested amount, or instead you can establish the timeouts and multiply the time value by your iteration counter. That is, to modify my example code:

function doScaledTimeout(i) {
  setTimeout(function() {
    alert(i);
  }, i * 5000);
}

(With a 100 millisecond timeout, the effect won't be very obvious, so I bumped the number up to 5000.) The value of i is multiplied by the base delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.

Update

Here in 2018, there is a simpler alternative. With the new ability to declare variables in scopes more narrow than functions, the original code would work if so modified:

for (let i = 1; i <= 2; i++) {
    setTimeout(function() { alert(i) }, 100);
}

The let declaration, unlike var, will itself cause there to be a distinct i for each iteration of the loop.

IOException: The process cannot access the file 'file path' because it is being used by another process

The error indicates another process is trying to access the file. Maybe you or someone else has it open while you are attempting to write to it. "Read" or "Copy" usually doesn't cause this, but writing to it or calling delete on it would.

There are some basic things to avoid this, as other answers have mentioned:

  1. In FileStream operations, place it in a using block with a FileShare.ReadWrite mode of access.

    For example:

    using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
    {
    }
    

    Note that FileAccess.ReadWrite is not possible if you use FileMode.Append.

  2. I ran across this issue when I was using an input stream to do a File.SaveAs when the file was in use. In my case I found, I didn't actually need to save it back to the file system at all, so I ended up just removing that, but I probably could've tried creating a FileStream in a using statement with FileAccess.ReadWrite, much like the code above.

  3. Saving your data as a different file and going back to delete the old one when it is found to be no longer in use, then renaming the one that saved successfully to the name of the original one is an option. How you test for the file being in use is accomplished through the

    List<Process> lstProcs = ProcessHandler.WhoIsLocking(file);
    

    line in my code below, and could be done in a Windows service, on a loop, if you have a particular file you want to watch and delete regularly when you want to replace it. If you don't always have the same file, a text file or database table could be updated that the service always checks for file names, and then performs that check for processes & subsequently performs the process kills and deletion on it, as I describe in the next option. Note that you'll need an account user name and password that has Admin privileges on the given computer, of course, to perform the deletion and ending of processes.

  4. When you don't know if a file will be in use when you are trying to save it, you can close all processes that could be using it, like Word, if it's a Word document, ahead of the save.

    If it is local, you can do this:

    ProcessHandler.localProcessKill("winword.exe");
    

    If it is remote, you can do this:

    ProcessHandler.remoteProcessKill(computerName, txtUserName, txtPassword, "winword.exe");
    

    where txtUserName is in the form of DOMAIN\user.

  5. Let's say you don't know the process name that is locking the file. Then, you can do this:

    List<Process> lstProcs = new List<Process>();
    lstProcs = ProcessHandler.WhoIsLocking(file);
    
    foreach (Process p in lstProcs)
    {
        if (p.MachineName == ".")
            ProcessHandler.localProcessKill(p.ProcessName);
        else
            ProcessHandler.remoteProcessKill(p.MachineName, txtUserName, txtPassword, p.ProcessName);
    }
    

    Note that file must be the UNC path: \\computer\share\yourdoc.docx in order for the Process to figure out what computer it's on and p.MachineName to be valid.

    Below is the class these functions use, which requires adding a reference to System.Management. The code was originally written by Eric J.:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System.Management;
    
    namespace MyProject
    {
        public static class ProcessHandler
        {
            [StructLayout(LayoutKind.Sequential)]
            struct RM_UNIQUE_PROCESS
            {
                public int dwProcessId;
                public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
            }
    
            const int RmRebootReasonNone = 0;
            const int CCH_RM_MAX_APP_NAME = 255;
            const int CCH_RM_MAX_SVC_NAME = 63;
    
            enum RM_APP_TYPE
            {
                RmUnknownApp = 0,
                RmMainWindow = 1,
                RmOtherWindow = 2,
                RmService = 3,
                RmExplorer = 4,
                RmConsole = 5,
                RmCritical = 1000
            }
    
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            struct RM_PROCESS_INFO
            {
                public RM_UNIQUE_PROCESS Process;
    
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
                public string strAppName;
    
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
                public string strServiceShortName;
    
                public RM_APP_TYPE ApplicationType;
                public uint AppStatus;
                public uint TSSessionId;
                [MarshalAs(UnmanagedType.Bool)]
                public bool bRestartable;
            }
    
            [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
            static extern int RmRegisterResources(uint pSessionHandle,
                                                UInt32 nFiles,
                                                string[] rgsFilenames,
                                                UInt32 nApplications,
                                                [In] RM_UNIQUE_PROCESS[] rgApplications,
                                                UInt32 nServices,
                                                string[] rgsServiceNames);
    
            [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
            static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
    
            [DllImport("rstrtmgr.dll")]
            static extern int RmEndSession(uint pSessionHandle);
    
            [DllImport("rstrtmgr.dll")]
            static extern int RmGetList(uint dwSessionHandle,
                                        out uint pnProcInfoNeeded,
                                        ref uint pnProcInfo,
                                        [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                        ref uint lpdwRebootReasons);
    
            /// <summary>
            /// Find out what process(es) have a lock on the specified file.
            /// </summary>
            /// <param name="path">Path of the file.</param>
            /// <returns>Processes locking the file</returns>
            /// <remarks>See also:
            /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
            /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
            /// 
            /// </remarks>
            static public List<Process> WhoIsLocking(string path)
            {
                uint handle;
                string key = Guid.NewGuid().ToString();
                List<Process> processes = new List<Process>();
    
                int res = RmStartSession(out handle, 0, key);
                if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");
    
                try
                {
                    const int ERROR_MORE_DATA = 234;
                    uint pnProcInfoNeeded = 0,
                        pnProcInfo = 0,
                        lpdwRebootReasons = RmRebootReasonNone;
    
                    string[] resources = new string[] { path }; // Just checking on one resource.
    
                    res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
    
                    if (res != 0) throw new Exception("Could not register resource.");
    
                    //Note: there's a race condition here -- the first call to RmGetList() returns
                    //      the total number of process. However, when we call RmGetList() again to get
                    //      the actual processes this number may have increased.
                    res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
    
                    if (res == ERROR_MORE_DATA)
                    {
                        // Create an array to store the process results
                        RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                        pnProcInfo = pnProcInfoNeeded;
    
                        // Get the list
                        res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                        if (res == 0)
                        {
                            processes = new List<Process>((int)pnProcInfo);
    
                            // Enumerate all of the results and add them to the 
                            // list to be returned
                            for (int i = 0; i < pnProcInfo; i++)
                            {
                                try
                                {
                                    processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                                }
                                // catch the error -- in case the process is no longer running
                                catch (ArgumentException) { }
                            }
                        }
                        else throw new Exception("Could not list processes locking resource.");
                    }
                    else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
                }
                finally
                {
                    RmEndSession(handle);
                }
    
                return processes;
            }
    
            public static void remoteProcessKill(string computerName, string userName, string pword, string processName)
            {
                var connectoptions = new ConnectionOptions();
                connectoptions.Username = userName;
                connectoptions.Password = pword;
    
                ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2", connectoptions);
    
                // WMI query
                var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
    
                using (var searcher = new ManagementObjectSearcher(scope, query))
                {
                    foreach (ManagementObject process in searcher.Get()) 
                    {
                        process.InvokeMethod("Terminate", null);
                        process.Dispose();
                    }
                }            
            }
    
            public static void localProcessKill(string processName)
            {
                foreach (Process p in Process.GetProcessesByName(processName))
                {
                    p.Kill();
                }
            }
    
            [DllImport("kernel32.dll")]
            public static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, int dwFlags);
    
            public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
    
        }
    }
    

Using ORDER BY and GROUP BY together

Why make it so complicated? This worked.

SELECT m_id,v_id,MAX(TIMESTAMP) AS TIME
 FROM table_name 
 GROUP BY m_id

Xcode 4: create IPA file instead of .xcarchive

I had the same problem... Had to recreate the project from scratch.

Note: my project was created in XCode 3.1 and was linking against a static library that was being built as a subproject (to a common destination). I changed this to build the source instead when I recreated the XCode project in XCode 4.

Now doing a Product/Archive/Share... gets the option of "iOS App Store Package (.ipa)" directly above "Application" (which is now greyed out) and "Archive" (which exports the .xcarchive).

CSS table td width - fixed, not flexible

It is not only the table cell which is growing, the table itself can grow, too. To avoid this you can assign a fixed width to the table which in return forces the cell width to be respected:

table {
  table-layout: fixed;
  width: 120px; /* Important */
}
td {
  width: 30px;
}

(Using overflow: hidden and/or text-overflow: ellipsis is optional but highly recommended for a better visual experience)

So if your situation allows you to assign a fixed width to your table, this solution might be a better alternative to the other given answers (which do work with or without a fixed width)

new Date() is working in Chrome but not Firefox

This should work for you:

var date1 = new Date(year, month, day, hour, minute, seconds);

I had to create date form a string so I have done it like this:

var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

Remember that the months in javascript are from 0 to 11, so you should reduce the month value by 1, like this:

var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

Download files from SFTP with SSH.NET library

While the example works, its not the correct way to handle the streams...

You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...

       public void DownloadAll()
    {
        string host = @"sftp.domain.com";
        string username = "myusername";
        string password = "mypassword";

        string remoteDirectory = "/RemotePath/";
        string localDirectory = @"C:\LocalDriveFolder\Downloaded\";

        using (var sftp = new SftpClient(host, username, password))
        {
            sftp.Connect();
            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {
                string remoteFileName = file.Name;
                if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))

                    using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
                    { 
                        sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                    }
            }

        }
    }

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

How do I generate a SALT in Java for Salted-Hash?

Here's my solution, i would love anyone's opinion on this, it's simple for beginners

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Scanner;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Cryptography {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Encoder encoder = Base64.getUrlEncoder().withoutPadding();
        System.out.print("Password: ");
        String strPassword = new Scanner(System.in).nextLine();
        byte[] bSalt = Salt();
        String strSalt = encoder.encodeToString(bSalt); // Byte to String
        System.out.println("Salt: " + strSalt);
        System.out.println("String to be hashed: " + strPassword + strSalt);
        String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
        System.out.println("Hashed value (Password + Salt value): " + strHash);
    }

    private static byte[] Salt() {
        SecureRandom random = new SecureRandom();
        byte salt[] = new byte[6];
        random.nextBytes(salt);
        return salt;
    }

    private static byte[] Hash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = factory.generateSecret(spec).getEncoded();
        return hash;
    }

}

You can validate by just decoding the strSalt and using the same hash method:

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Encoder encoder = Base64.getUrlEncoder().withoutPadding();
        Decoder decoder = Base64.getUrlDecoder();
        System.out.print("Password: ");
        String strPassword = new Scanner(System.in).nextLine();
        String strSalt = "Your Salt String Here";
        byte[] bSalt = decoder.decode(strSalt); // String to Byte
        System.out.println("Salt: " + strSalt);
        System.out.println("String to be hashed: " + strPassword + strSalt);
        String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
        System.out.println("Hashed value (Password + Salt value): " + strHash);
    }

SQL: ... WHERE X IN (SELECT Y FROM ...)

Maybe try this

Select cust.*

From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null

android.os.NetworkOnMainThreadException with android 4.2

android.os.NetworkOnMainThreadException occurs when you try to access network on your main thread (You main activity execution). To avoid this, you must create a separate thread or AsyncTask or Runnable implementation to execute your JSON data loading. Since HoneyComb you can not further execute the network task on main thread. Here is the implementation using AsyncTask for a network task execution

Moment JS start and end of given month

Try the following code:

moment(startDate).startOf('months')
moment(startDate).endOf('months')

Versioning SQL Server database

In my experience the solution is twofold:

  1. You need to handle changes to the development database that are done by multiple developers during development.

  2. You need to handle database upgrades in customers sites.

In order to handle #1 you'll need a strong database diff/merge tool. The best tool should be able to perform automatic merge as much as possible while allowing you to resolve unhandled conflicts manually.

The perfect tool should handle merge operations by using a 3-way merge algorithm that brings into account the changes that were made in the THEIRS database and the MINE database, relative to the BASE database.

I wrote a commercial tool that provides manual merge support for SQLite databases and I'm currently adding support for 3-way merge algorithm for SQLite. Check it out at http://www.sqlitecompare.com

In order to handle #2 you will need an upgrade framework in place.

The basic idea is to develop an automatic upgrade framework that knows how to upgrade from an existing SQL schema to the newer SQL schema and can build an upgrade path for every existing DB installation.

Check out my article on the subject in http://www.codeproject.com/KB/database/sqlite_upgrade.aspx to get a general idea of what I'm talking about.

Good Luck

Liron Levi

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

How to change current Theme at runtime in Android

This way work for me:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(GApplication.getInstance().getTheme());
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
}

Then you want to change a new theme:

GApplication.getInstance().setTheme(R.style.LightTheme);
recreate();

javax.servlet.ServletException cannot be resolved to a type in spring web app

As almost anyone said, adding a runtime service will solve the problem. But if there is no runtime services or there is something like Google App Engine which is not your favorite any how, click New button right down the Targeted Runtimes list and add a new runtime server environment. Then check it and click OK and let the compiler to compile your project again.

Hope it helps ;)

Why doesn't wireshark detect my interface?

On Fedora 29 with Wireshark 3.0.0 only adding a user to the wireshark group is required:

sudo usermod -a -G wireshark $USER

Then log out and log back in (or reboot), and Wireshark should work correctly.

ORDER BY using Criteria API

It's hard to know for sure without seeing the mappings (see @Juha's comment), but I think you want something like the following:

Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();

How do I compare two strings in Perl?

The obvious subtext of this question is:

why can't you just use == to check if two strings are the same?

Perl doesn't have distinct data types for text vs. numbers. They are both represented by the type "scalar". Put another way, strings are numbers if you use them as such.

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7

Since text and numbers aren't differentiated by the language, we can't simply overload the == operator to do the right thing for both cases. Therefore, Perl provides eq to compare values as text:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true

In short:

  • Perl doesn't have a data-type exclusively for text strings
  • use == or !=, to compare two operands as numbers
  • use eq or ne, to compare two operands as text

There are many other functions and operators that can be used to compare scalar values, but knowing the distinction between these two forms is an important first step.

Vuejs: v-model array in multiple input

Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
  },_x000D_
  methods: {_x000D_
    addUser: function () {_x000D_
      this.users.push({ name: '',email:'' });_x000D_
    },_x000D_
    deleteUser: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.users.splice(index, 1);_x000D_
      if(index===0)_x000D_
      this.addUser()_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Add user</h1>_x000D_
  <div v-for="(user, index) in users">_x000D_
    <input v-model="user.name">_x000D_
    <input v-model="user.email">_x000D_
    <button @click="deleteUser(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addUser">_x000D_
    New User_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the iBeacon Bluetooth Profile

It seems to based on advertisement data, particularly the manufacturer data:

4C00 02 15 585CDE931B0142CC9A1325009BEDC65E 0000 0000 C5

<company identifier (2 bytes)> <type (1 byte)> <data length (1 byte)>
    <uuid (16 bytes)> <major (2 bytes)> <minor (2 bytes)> <RSSI @ 1m>
  • Apple Company Identifier (Little Endian), 0x004c
  • data type, 0x02 => iBeacon
  • data length, 0x15 = 21
  • uuid: 585CDE931B0142CC9A1325009BEDC65E
  • major: 0000
  • minor: 0000
  • meaured power at 1 meter: 0xc5 = -59

I have this node.js script working on Linux with the sample AirLocate app example.

Check if PHP session has already started

i ended up with double check of status. php 5.4+

if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};

How to obtain Telegram chat_id for a specific user?

Straight out from the documentation:

Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.

  1. Create a bot with a suitable username, e.g. @ExampleComBot
  2. Set up a webhook for incoming messages
  3. Generate a random string of a sufficient length, e.g. $memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
  4. Put the value 123 with the key $memcache_key into Memcache for 3600 seconds (one hour)
  5. Show our user the button https://telegram.me/ExampleComBot?start=vCH1vGWJxfSeofSAs0K5PA
  6. Configure the webhook processor to query Memcached with the parameter that is passed in incoming messages beginning with /start. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.
  7. Now when we want to send a notification to the user 123, check if they have the field telegram_chat_id. If yes, use the sendMessage method in the Bot API to send them a message in Telegram.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

If you are using java 7 then make sure you have Tomcat 7

brew install tomcat@7

and update run configuration to Tomcat 7

Tomcat 9 is working with java 8

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

What does the Ellipsis object do?

This is equivalent.

l=[..., 1,2,3]
l=[Ellipsis, 1,2,3]

... is a constant defined inside built-in constants.

Ellipsis

The same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.

Reading specific XML elements from XML file

Alternatively, you can use XPath query via XPathSelectElements method:

var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");

Why is 2 * (i * i) faster than 2 * i * i in Java?

There is a slight difference in the ordering of the bytecode.

2 * (i * i):

     iconst_2
     iload0
     iload0
     imul
     imul
     iadd

vs 2 * i * i:

     iconst_2
     iload0
     imul
     iload0
     imul
     iadd

At first sight this should not make a difference; if anything the second version is more optimal since it uses one slot less.

So we need to dig deeper into the lower level (JIT)1.

Remember that JIT tends to unroll small loops very aggressively. Indeed we observe a 16x unrolling for the 2 * (i * i) case:

030   B2: # B2 B3 <- B1 B2  Loop: B2-B2 inner main of N18 Freq: 1e+006
030     addl    R11, RBP    # int
033     movl    RBP, R13    # spill
036     addl    RBP, #14    # int
039     imull   RBP, RBP    # int
03c     movl    R9, R13 # spill
03f     addl    R9, #13 # int
043     imull   R9, R9  # int
047     sall    RBP, #1
049     sall    R9, #1
04c     movl    R8, R13 # spill
04f     addl    R8, #15 # int
053     movl    R10, R8 # spill
056     movdl   XMM1, R8    # spill
05b     imull   R10, R8 # int
05f     movl    R8, R13 # spill
062     addl    R8, #12 # int
066     imull   R8, R8  # int
06a     sall    R10, #1
06d     movl    [rsp + #32], R10    # spill
072     sall    R8, #1
075     movl    RBX, R13    # spill
078     addl    RBX, #11    # int
07b     imull   RBX, RBX    # int
07e     movl    RCX, R13    # spill
081     addl    RCX, #10    # int
084     imull   RCX, RCX    # int
087     sall    RBX, #1
089     sall    RCX, #1
08b     movl    RDX, R13    # spill
08e     addl    RDX, #8 # int
091     imull   RDX, RDX    # int
094     movl    RDI, R13    # spill
097     addl    RDI, #7 # int
09a     imull   RDI, RDI    # int
09d     sall    RDX, #1
09f     sall    RDI, #1
0a1     movl    RAX, R13    # spill
0a4     addl    RAX, #6 # int
0a7     imull   RAX, RAX    # int
0aa     movl    RSI, R13    # spill
0ad     addl    RSI, #4 # int
0b0     imull   RSI, RSI    # int
0b3     sall    RAX, #1
0b5     sall    RSI, #1
0b7     movl    R10, R13    # spill
0ba     addl    R10, #2 # int
0be     imull   R10, R10    # int
0c2     movl    R14, R13    # spill
0c5     incl    R14 # int
0c8     imull   R14, R14    # int
0cc     sall    R10, #1
0cf     sall    R14, #1
0d2     addl    R14, R11    # int
0d5     addl    R14, R10    # int
0d8     movl    R10, R13    # spill
0db     addl    R10, #3 # int
0df     imull   R10, R10    # int
0e3     movl    R11, R13    # spill
0e6     addl    R11, #5 # int
0ea     imull   R11, R11    # int
0ee     sall    R10, #1
0f1     addl    R10, R14    # int
0f4     addl    R10, RSI    # int
0f7     sall    R11, #1
0fa     addl    R11, R10    # int
0fd     addl    R11, RAX    # int
100     addl    R11, RDI    # int
103     addl    R11, RDX    # int
106     movl    R10, R13    # spill
109     addl    R10, #9 # int
10d     imull   R10, R10    # int
111     sall    R10, #1
114     addl    R10, R11    # int
117     addl    R10, RCX    # int
11a     addl    R10, RBX    # int
11d     addl    R10, R8 # int
120     addl    R9, R10 # int
123     addl    RBP, R9 # int
126     addl    RBP, [RSP + #32 (32-bit)]   # int
12a     addl    R13, #16    # int
12e     movl    R11, R13    # spill
131     imull   R11, R13    # int
135     sall    R11, #1
138     cmpl    R13, #999999985
13f     jl     B2   # loop end  P=1.000000 C=6554623.000000

We see that there is 1 register that is "spilled" onto the stack.

And for the 2 * i * i version:

05a   B3: # B2 B4 <- B1 B2  Loop: B3-B2 inner main of N18 Freq: 1e+006
05a     addl    RBX, R11    # int
05d     movl    [rsp + #32], RBX    # spill
061     movl    R11, R8 # spill
064     addl    R11, #15    # int
068     movl    [rsp + #36], R11    # spill
06d     movl    R11, R8 # spill
070     addl    R11, #14    # int
074     movl    R10, R9 # spill
077     addl    R10, #16    # int
07b     movdl   XMM2, R10   # spill
080     movl    RCX, R9 # spill
083     addl    RCX, #14    # int
086     movdl   XMM1, RCX   # spill
08a     movl    R10, R9 # spill
08d     addl    R10, #12    # int
091     movdl   XMM4, R10   # spill
096     movl    RCX, R9 # spill
099     addl    RCX, #10    # int
09c     movdl   XMM6, RCX   # spill
0a0     movl    RBX, R9 # spill
0a3     addl    RBX, #8 # int
0a6     movl    RCX, R9 # spill
0a9     addl    RCX, #6 # int
0ac     movl    RDX, R9 # spill
0af     addl    RDX, #4 # int
0b2     addl    R9, #2  # int
0b6     movl    R10, R14    # spill
0b9     addl    R10, #22    # int
0bd     movdl   XMM3, R10   # spill
0c2     movl    RDI, R14    # spill
0c5     addl    RDI, #20    # int
0c8     movl    RAX, R14    # spill
0cb     addl    RAX, #32    # int
0ce     movl    RSI, R14    # spill
0d1     addl    RSI, #18    # int
0d4     movl    R13, R14    # spill
0d7     addl    R13, #24    # int
0db     movl    R10, R14    # spill
0de     addl    R10, #26    # int
0e2     movl    [rsp + #40], R10    # spill
0e7     movl    RBP, R14    # spill
0ea     addl    RBP, #28    # int
0ed     imull   RBP, R11    # int
0f1     addl    R14, #30    # int
0f5     imull   R14, [RSP + #36 (32-bit)]   # int
0fb     movl    R10, R8 # spill
0fe     addl    R10, #11    # int
102     movdl   R11, XMM3   # spill
107     imull   R11, R10    # int
10b     movl    [rsp + #44], R11    # spill
110     movl    R10, R8 # spill
113     addl    R10, #10    # int
117     imull   RDI, R10    # int
11b     movl    R11, R8 # spill
11e     addl    R11, #8 # int
122     movdl   R10, XMM2   # spill
127     imull   R10, R11    # int
12b     movl    [rsp + #48], R10    # spill
130     movl    R10, R8 # spill
133     addl    R10, #7 # int
137     movdl   R11, XMM1   # spill
13c     imull   R11, R10    # int
140     movl    [rsp + #52], R11    # spill
145     movl    R11, R8 # spill
148     addl    R11, #6 # int
14c     movdl   R10, XMM4   # spill
151     imull   R10, R11    # int
155     movl    [rsp + #56], R10    # spill
15a     movl    R10, R8 # spill
15d     addl    R10, #5 # int
161     movdl   R11, XMM6   # spill
166     imull   R11, R10    # int
16a     movl    [rsp + #60], R11    # spill
16f     movl    R11, R8 # spill
172     addl    R11, #4 # int
176     imull   RBX, R11    # int
17a     movl    R11, R8 # spill
17d     addl    R11, #3 # int
181     imull   RCX, R11    # int
185     movl    R10, R8 # spill
188     addl    R10, #2 # int
18c     imull   RDX, R10    # int
190     movl    R11, R8 # spill
193     incl    R11 # int
196     imull   R9, R11 # int
19a     addl    R9, [RSP + #32 (32-bit)]    # int
19f     addl    R9, RDX # int
1a2     addl    R9, RCX # int
1a5     addl    R9, RBX # int
1a8     addl    R9, [RSP + #60 (32-bit)]    # int
1ad     addl    R9, [RSP + #56 (32-bit)]    # int
1b2     addl    R9, [RSP + #52 (32-bit)]    # int
1b7     addl    R9, [RSP + #48 (32-bit)]    # int
1bc     movl    R10, R8 # spill
1bf     addl    R10, #9 # int
1c3     imull   R10, RSI    # int
1c7     addl    R10, R9 # int
1ca     addl    R10, RDI    # int
1cd     addl    R10, [RSP + #44 (32-bit)]   # int
1d2     movl    R11, R8 # spill
1d5     addl    R11, #12    # int
1d9     imull   R13, R11    # int
1dd     addl    R13, R10    # int
1e0     movl    R10, R8 # spill
1e3     addl    R10, #13    # int
1e7     imull   R10, [RSP + #40 (32-bit)]   # int
1ed     addl    R10, R13    # int
1f0     addl    RBP, R10    # int
1f3     addl    R14, RBP    # int
1f6     movl    R10, R8 # spill
1f9     addl    R10, #16    # int
1fd     cmpl    R10, #999999985
204     jl     B2   # loop end  P=1.000000 C=7419903.000000

Here we observe much more "spilling" and more accesses to the stack [RSP + ...], due to more intermediate results that need to be preserved.

Thus the answer to the question is simple: 2 * (i * i) is faster than 2 * i * i because the JIT generates more optimal assembly code for the first case.


But of course it is obvious that neither the first nor the second version is any good; the loop could really benefit from vectorization, since any x86-64 CPU has at least SSE2 support.

So it's an issue of the optimizer; as is often the case, it unrolls too aggressively and shoots itself in the foot, all the while missing out on various other opportunities.

In fact, modern x86-64 CPUs break down the instructions further into micro-ops (µops) and with features like register renaming, µop caches and loop buffers, loop optimization takes a lot more finesse than a simple unrolling for optimal performance. According to Agner Fog's optimization guide:

The gain in performance due to the µop cache can be quite considerable if the average instruction length is more than 4 bytes. The following methods of optimizing the use of the µop cache may be considered:

  • Make sure that critical loops are small enough to fit into the µop cache.
  • Align the most critical loop entries and function entries by 32.
  • Avoid unnecessary loop unrolling.
  • Avoid instructions that have extra load time
    . . .

Regarding those load times - even the fastest L1D hit costs 4 cycles, an extra register and µop, so yes, even a few accesses to memory will hurt performance in tight loops.

But back to the vectorization opportunity - to see how fast it can be, we can compile a similar C application with GCC, which outright vectorizes it (AVX2 is shown, SSE2 is similar)2:

  vmovdqa ymm0, YMMWORD PTR .LC0[rip]
  vmovdqa ymm3, YMMWORD PTR .LC1[rip]
  xor eax, eax
  vpxor xmm2, xmm2, xmm2
.L2:
  vpmulld ymm1, ymm0, ymm0
  inc eax
  vpaddd ymm0, ymm0, ymm3
  vpslld ymm1, ymm1, 1
  vpaddd ymm2, ymm2, ymm1
  cmp eax, 125000000      ; 8 calculations per iteration
  jne .L2
  vmovdqa xmm0, xmm2
  vextracti128 xmm2, ymm2, 1
  vpaddd xmm2, xmm0, xmm2
  vpsrldq xmm0, xmm2, 8
  vpaddd xmm0, xmm2, xmm0
  vpsrldq xmm1, xmm0, 4
  vpaddd xmm0, xmm0, xmm1
  vmovd eax, xmm0
  vzeroupper

With run times:

  • SSE: 0.24 s, or 2 times as fast.
  • AVX: 0.15 s, or 3 times as fast.
  • AVX2: 0.08 s, or 5 times as fast.

1 To get JIT generated assembly output, get a debug JVM and run with -XX:+PrintOptoAssembly

2 The C version is compiled with the -fwrapv flag, which enables GCC to treat signed integer overflow as a two's-complement wrap-around.

getApplication() vs. getApplicationContext()

Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.

Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).

So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

Why does getApplicationContext() exist in the first place ?

getApplication() is only available in the Activity class and the Service class, whereas getApplicationContext() is declared in the Context class.

That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext(). Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.

When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext() delegates it's call to baseContext.getApplicationContext().

One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

I know this is not an exact and precise answer, but still, does that answer your question?

SQL Update to the SUM of its joined values

Use a sub query similar to the below.

UPDATE P
SET extrasPrice = sub.TotalPrice from
BookingPitches p
inner join 
(Select PitchID, Sum(Price) TotalPrice
    from  dbo.BookingPitchExtras
    Where [Required] = 1
    Group by Pitchid
) as Sub
on p.Id = e.PitchId 
where p.BookingId = 1

write() versus writelines() and concatenated strings

Why am I unable to use a string for a newline in write() but I can use it in writelines()?

The idea is the following: if you want to write a single string you can do this with write(). If you have a sequence of strings you can write them all using writelines().

write(arg) expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception (by the way, show errors to us!).

writelines(arg) expects an iterable as argument (an iterable object can be a tuple, a list, a string, or an iterator in the most general sense). Each item contained in the iterator is expected to be a string. A tuple of strings is what you provided, so things worked.

The nature of the string(s) does not matter to both of the functions, i.e. they just write to the file whatever you provide them. The interesting part is that writelines() does not add newline characters on its own, so the method name can actually be quite confusing. It actually behaves like an imaginary method called write_all_of_these_strings(sequence).

What follows is an idiomatic way in Python to write a list of strings to a file while keeping each string in its own line:

lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.write('\n'.join(lines))

This takes care of closing the file for you. The construct '\n'.join(lines) concatenates (connects) the strings in the list lines and uses the character '\n' as glue. It is more efficient than using the + operator.

Starting from the same lines sequence, ending up with the same output, but using writelines():

lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.writelines("%s\n" % l for l in lines)

This makes use of a generator expression and dynamically creates newline-terminated strings. writelines() iterates over this sequence of strings and writes every item.

Edit: Another point you should be aware of:

write() and readlines() existed before writelines() was introduced. writelines() was introduced later as a counterpart of readlines(), so that one could easily write the file content that was just read via readlines():

outfile.writelines(infile.readlines())

Really, this is the main reason why writelines has such a confusing name. Also, today, we do not really want to use this method anymore. readlines() reads the entire file to the memory of your machine before writelines() starts to write the data. First of all, this may waste time. Why not start writing parts of data while reading other parts? But, most importantly, this approach can be very memory consuming. In an extreme scenario, where the input file is larger than the memory of your machine, this approach won't even work. The solution to this problem is to use iterators only. A working example:

with open('inputfile') as infile:
    with open('outputfile') as outfile:
        for line in infile:
            outfile.write(line)

This reads the input file line by line. As soon as one line is read, this line is written to the output file. Schematically spoken, there always is only one single line in memory (compared to the entire file content being in memory in case of the readlines/writelines approach).

Search for string and get count in vi editor

:%s/string/string/g will give the answer.

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

Set up a scheduled job?

I personally use cron, but the Jobs Scheduling parts of django-extensions looks interesting.

Performing a query on a result from another query?

Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
  SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
  FROM availables
  INNER JOIN rooms
  ON availables.room_id=rooms.id
  WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
  GROUP BY availables.bookdate
) AS SUBQUERY

SQL Server Creating a temp table for this query

Like this. Make sure you drop the temp table (at the end of the code block, after you're done with it) or it will error on subsequent runs.

SELECT  
    tblMEP_Sites.Name AS SiteName, 
    convert(varchar(10),BillingMonth ,101) AS BillingMonth, 
    SUM(Consumption) AS Consumption
INTO 
    #MyTempTable
FROM 
    tblMEP_Projects
    JOIN tblMEP_Sites
        ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
    JOIN tblMEP_Meters
        ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
    JOIN tblMEP_MonthlyData
        ON tblMEP_MonthlyData.MeterID = tblMEP_Meters.ID
    JOIN tblMEP_CustomerAccounts
        ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
    JOIN tblMEP_UtilityCompanies
        ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID
    JOIN tblMEP_MeterTypes
        ON tblMEP_UtilityCompanies.UtilityTypeID = tblMEP_MeterTypes.ID
WHERE 
    tblMEP_Projects.ID = @ProjectID
    AND tblMEP_MonthlyData.BillingMonth Between @StartDate AND @EndDate
    AND tbLMEP_MeterTypes.ID = @MeterTypeID
GROUP BY 
    BillingMonth, tblMEP_Sites.Name

DROP TABLE #MyTempTable

How to select rows in a DataFrame between two values, in Python Pandas?

If you're dealing with multiple values and multiple inputs you could also set up an apply function like this. In this case filtering a dataframe for GPS locations that fall withing certain ranges.

def filter_values(lat,lon):
    if abs(lat - 33.77) < .01 and abs(lon - -118.16) < .01:
        return True
    elif abs(lat - 37.79) < .01 and abs(lon - -122.39) < .01:
        return True
    else:
        return False


df = df[df.apply(lambda x: filter_values(x['lat'],x['lon']),axis=1)]

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to compare two tags with git?

$ git diff tag1 tag2

or show log between them:

$ git log tag1..tag2

sometimes it may be convenient to see only the list of files that were changed:

$ git diff tag1 tag2 --stat

and then look at the differences for some particular file:

$ git diff tag1 tag2 -- some/file/name

A tag is only a reference to the latest commit 'on that tag', so that you are doing a diff on the commits between them.

(Make sure to do git pull --tags first)

Also, a good reference: http://learn.github.com/p/diff.html

Laravel 5 - How to access image uploaded in storage within View?

without site name

{{Storage::url($photoLink)}}

if you want to add site name to it example to append on api JSON felids

 public function getPhotoFullLinkAttribute()
{
    return env('APP_URL', false).Storage::url($this->attributes['avatar']) ;
}

How to convert data.frame column from Factor to numeric

As an alternative to $dollarsign notation, use a within block:

breast <- within(breast, {
  class <- as.numeric(as.character(class))
})

Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class) will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.

How to make sure you don't get WCF Faulted state exception?

Similar to Ryan Rodemoyer's answer, I found that when the UriTemplate on the Contract is not valid you can get this error. In my case, I was using the same parameter twice. For example:

/Root/{Name}/{Name}

Angular ui-grid dynamically calculate height of the grid

.ui-grid, .ui-grid-viewport,.ui-grid-contents-wrapper, .ui-grid-canvas { height: auto !important; }

Proper way to return JSON using node or Express

That response is a string too, if you want to send the response prettified, for some awkward reason, you could use something like JSON.stringify(anObject, null, 3)

It's important that you set the Content-Type header to application/json, too.

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

// > {"a":1}

Prettified:

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }, null, 3));
});
app.listen(3000);

// >  {
// >     "a": 1
// >  }

I'm not exactly sure why you want to terminate it with a newline, but you could just do JSON.stringify(...) + '\n' to achieve that.

Express

In express you can do this by changing the options instead.

'json replacer' JSON replacer callback, null by default

'json spaces' JSON response spaces for formatting, defaults to 2 in development, 0 in production

Not actually recommended to set to 40

app.set('json spaces', 40);

Then you could just respond with some json.

res.json({ a: 1 });

It'll use the 'json spaces' configuration to prettify it.

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

Best way to check if object exists in Entity Framework?

I had to manage a scenario where the percentage of duplicates being provided in the new data records was very high, and so many thousands of database calls were being made to check for duplicates (so the CPU sent a lot of time at 100%). In the end I decided to keep the last 100,000 records cached in memory. This way I could check for duplicates against the cached records which was extremely fast when compared to a LINQ query against the SQL database, and then write any genuinely new records to the database (as well as add them to the data cache, which I also sorted and trimmed to keep its length manageable).

Note that the raw data was a CSV file that contained many individual records that had to be parsed. The records in each consecutive file (which came at a rate of about 1 every 5 minutes) overlapped considerably, hence the high percentage of duplicates.

In short, if you have timestamped raw data coming in, pretty much in order, then using a memory cache might help with the record duplication check.

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.