Since I wanted to compare two arrays for a unit Test and I arrived on this answer I thought I could share.
You can also do it with:
@Test
public void testTwoArrays() {
byte[] array = new BigInteger("1111000011110001", 2).toByteArray();
byte[] secondArray = new BigInteger("1111000011110001", 2).toByteArray();
Assert.assertArrayEquals(array, secondArray);
}
And you could check on Comparing arrays in JUnit assertions for more infos.
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
When you have a function that can receive pointers to more than one type, calling it with NULL
is ambiguous. The way this is worked around now is very hacky by accepting an int and assuming it's NULL
.
template <class T>
class ptr {
T* p_;
public:
ptr(T* p) : p_(p) {}
template <class U>
ptr(U* u) : p_(dynamic_cast<T*>(u)) { }
// Without this ptr<T> p(NULL) would be ambiguous
ptr(int null) : p_(NULL) { assert(null == NULL); }
};
In C++11
you would be able to overload on nullptr_t
so that ptr<T> p(42);
would be a compile-time error rather than a run-time assert
.
ptr(std::nullptr_t) : p_(nullptr) { }
Graphviz - from the web page:
The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)
It's the simplest and most productive tool I've found to create a variety of boxes-and-lines diagrams. I have and use Visio and OmniGraffle, but there's always the temptation to make "just one more adjustment".
It's also quite easy to write code to produce the "dot file" format that Graphiz consumes, so automated diagram production is also nicely within reach.
If you don't exactly need this format:
2009_07_28__08_36_01
Then you could use the following 3 lines of code which uses %date% and %time%:
set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%
Note: The characters /
and :
are removed and the character .
and space is replaced with an underscore.
Example output (taken Wednesday 8/5/15 at 12:49 PM with 50 seconds and 93 milliseconds):
echo %mytimestamp%
Wed_08052015_124950_93
You can use this
char name[20];
scanf("%20[^\n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("\n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^\n]", variable);
}
char name[20];
getText("Your name", name, 20);
Building on top of @dargue3's answer, if you want the thumb to be larger than the track, you want to fully take advantage of the <input type="range" />
element and go cross browser, you need a little extra lines of JS & CSS.
On Chrome/Mozilla you can use the linear-gradient
technique, but you need to adjust the ratio based on the min
, max
, value
attributes as mentioned here by @Attila O.. You need to make sure you are not applying this on Edge, otherwise the thumb is not displayed. @Geoffrey Lalloué explains this in more detail here.
Another thing worth mentioning, is that you need to adjust the rangeEl.style.height = "20px";
on IE/Older. Simply put this is because in this case "the height is not applied to the track but rather the whole input including the thumb". fiddle
/**_x000D_
* Sniffs for Older Edge or IE,_x000D_
* more info here:_x000D_
* https://stackoverflow.com/q/31721250/3528132_x000D_
*/_x000D_
function isOlderEdgeOrIE() {_x000D_
return (_x000D_
window.navigator.userAgent.indexOf("MSIE ") > -1 ||_x000D_
!!navigator.userAgent.match(/Trident.*rv\:11\./) ||_x000D_
window.navigator.userAgent.indexOf("Edge") > -1_x000D_
);_x000D_
}_x000D_
_x000D_
function valueTotalRatio(value, min, max) {_x000D_
return ((value - min) / (max - min)).toFixed(2);_x000D_
}_x000D_
_x000D_
function getLinearGradientCSS(ratio, leftColor, rightColor) {_x000D_
return [_x000D_
'-webkit-gradient(',_x000D_
'linear, ',_x000D_
'left top, ',_x000D_
'right top, ',_x000D_
'color-stop(' + ratio + ', ' + leftColor + '), ',_x000D_
'color-stop(' + ratio + ', ' + rightColor + ')',_x000D_
')'_x000D_
].join('');_x000D_
}_x000D_
_x000D_
function updateRangeEl(rangeEl) {_x000D_
var ratio = valueTotalRatio(rangeEl.value, rangeEl.min, rangeEl.max);_x000D_
_x000D_
rangeEl.style.backgroundImage = getLinearGradientCSS(ratio, '#919e4b', '#c5c5c5');_x000D_
}_x000D_
_x000D_
function initRangeEl() {_x000D_
var rangeEl = document.querySelector('input[type=range]');_x000D_
var textEl = document.querySelector('input[type=text]');_x000D_
_x000D_
/**_x000D_
* IE/Older Edge FIX_x000D_
* On IE/Older Edge the height of the <input type="range" />_x000D_
* is the whole element as oposed to Chrome/Moz_x000D_
* where the height is applied to the track._x000D_
*_x000D_
*/_x000D_
if (isOlderEdgeOrIE()) {_x000D_
rangeEl.style.height = "20px";_x000D_
// IE 11/10 fires change instead of input_x000D_
// https://stackoverflow.com/a/50887531/3528132_x000D_
rangeEl.addEventListener("change", function(e) {_x000D_
textEl.value = e.target.value;_x000D_
});_x000D_
rangeEl.addEventListener("input", function(e) {_x000D_
textEl.value = e.target.value;_x000D_
});_x000D_
} else {_x000D_
updateRangeEl(rangeEl);_x000D_
rangeEl.addEventListener("input", function(e) {_x000D_
updateRangeEl(e.target);_x000D_
textEl.value = e.target.value;_x000D_
});_x000D_
}_x000D_
}_x000D_
_x000D_
initRangeEl();
_x000D_
input[type="range"] {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
width: 300px;_x000D_
height: 5px;_x000D_
padding: 0;_x000D_
border-radius: 2px;_x000D_
outline: none;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
_x000D_
/*Chrome thumb*/_x000D_
_x000D_
input[type="range"]::-webkit-slider-thumb {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
-webkit-border-radius: 5px;_x000D_
/*16x16px adjusted to be same as 14x14px on moz*/_x000D_
height: 16px;_x000D_
width: 16px;_x000D_
border-radius: 5px;_x000D_
background: #e7e7e7;_x000D_
border: 1px solid #c5c5c5;_x000D_
}_x000D_
_x000D_
_x000D_
/*Mozilla thumb*/_x000D_
_x000D_
input[type="range"]::-moz-range-thumb {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
-moz-border-radius: 5px;_x000D_
height: 14px;_x000D_
width: 14px;_x000D_
border-radius: 5px;_x000D_
background: #e7e7e7;_x000D_
border: 1px solid #c5c5c5;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge input*/_x000D_
_x000D_
input[type=range]::-ms-track {_x000D_
width: 300px;_x000D_
height: 6px;_x000D_
/*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */_x000D_
background: transparent;_x000D_
/*leave room for the larger thumb to overflow with a transparent border */_x000D_
border-color: transparent;_x000D_
border-width: 2px 0;_x000D_
/*remove default tick marks*/_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge thumb*/_x000D_
_x000D_
input[type=range]::-ms-thumb {_x000D_
height: 14px;_x000D_
width: 14px;_x000D_
border-radius: 5px;_x000D_
background: #e7e7e7;_x000D_
border: 1px solid #c5c5c5;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge left side*/_x000D_
_x000D_
input[type=range]::-ms-fill-lower {_x000D_
background: #919e4b;_x000D_
border-radius: 2px;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE & Edge right side*/_x000D_
_x000D_
input[type=range]::-ms-fill-upper {_x000D_
background: #c5c5c5;_x000D_
border-radius: 2px;_x000D_
}_x000D_
_x000D_
_x000D_
/*IE disable tooltip*/_x000D_
_x000D_
input[type=range]::-ms-tooltip {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
input[type="text"] {_x000D_
border: none;_x000D_
}
_x000D_
<input type="range" value="80" min="10" max="100" step="1" />_x000D_
<input type="text" value="80" size="3" />
_x000D_
I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa
I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.
I think this is easier:
double time = 200.3456;
DecimalFormat df = new DecimalFormat("#.##");
time = Double.valueOf(df.format(time));
System.out.println(time); // 200.35
Note that this will actually do the rounding for you, not just formatting.
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>
Here is a complete test case that simulates the click
event, calls all handlers attached (however they have been attached), maintains the "target"
attribute ("srcElement"
in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
if (anchorObj.click) {
anchorObj.click()
} else if(document.createEvent) {
if(event.target !== anchorObj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var allowDefault = anchorObj.dispatchEvent(evt);
// you can check allowDefault for false to see if
// any handler called evt.preventDefault().
// Firefox will *not* redirect to anchorObj.href
// for you. However every other browser will.
}
}
}
</script>
</head>
<body>
<div onclick="alert('Container clicked')">
<a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
Fake Click on Normal Link
</button>
<br /><br />
<div onclick="alert('Container clicked')">
<div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>
</body>
</html>
It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target
attribute of the event (which remains unchanged during propagation).
Obviously IE does this internally holding a reference to its global event
object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event
.
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
thank-you Ignacio Vazquez-Abrams
i adapted slightly for better ease of use :)
placed at top of script
NEW_LINE=$'\n'
then to use easily with other variables
variable1="test1"
variable2="test2"
DESCRIPTION="$variable1$NEW_LINE$variable2$NEW_LINE"
OR to append thank-you William Pursell
DESCRIPTION="$variable1$NEW_LINE"
DESCRIPTION+="$variable2$NEW_LINE"
echo "$DESCRIPTION"
Gensim implements a model called Doc2Vec for paragraph embedding.
There are different tutorials presented as IPython notebooks:
Another method would rely on Word2Vec and Word Mover's Distance (WMD), as shown in this tutorial:
An alternative solution would be to rely on average vectors:
from gensim.models import KeyedVectors
from gensim.utils import simple_preprocess
def tidy_sentence(sentence, vocabulary):
return [word for word in simple_preprocess(sentence) if word in vocabulary]
def compute_sentence_similarity(sentence_1, sentence_2, model_wv):
vocabulary = set(model_wv.index2word)
tokens_1 = tidy_sentence(sentence_1, vocabulary)
tokens_2 = tidy_sentence(sentence_2, vocabulary)
return model_wv.n_similarity(tokens_1, tokens_2)
wv = KeyedVectors.load('model.wv', mmap='r')
sim = compute_sentence_similarity('this is a sentence', 'this is also a sentence', wv)
print(sim)
Finally, if you can run Tensorflow, you may try: https://tfhub.dev/google/universal-sentence-encoder/2
You should be able to access your windows system under the /mnt
directory. For example inside of bash, use this to get to your pictures directory:
cd /mnt/c/Users/<ubuntu.username>/Pictures
Hope this helps!
By 'return non-false', they mean to return any value which would not work out to boolean false. So you could return true
, 1
, 'non-false'
, or whatever else you can think up.
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
I got it via the Prism.WPF NuGet-Package. (it includes Windows.System.Interactivity)
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
@fthiella 's solution is very elegant.
If in future you want show more than user_id
you could use joins, and there in one line could be all data you need.
If you want to use AND
conditions, and the conditions are in multiple lines in your table, you can use JOINS
example:
SELECT `w_name`.`user_id`
FROM `wp_usermeta` as `w_name`
JOIN `wp_usermeta` as `w_year` ON `w_name`.`user_id`=`w_year`.`user_id`
AND `w_name`.`meta_key` = 'first_name'
AND `w_year`.`meta_key` = 'yearofpassing'
JOIN `wp_usermeta` as `w_city` ON `w_name`.`user_id`=`w_city`.user_id
AND `w_city`.`meta_key` = 'u_city'
JOIN `wp_usermeta` as `w_course` ON `w_name`.`user_id`=`w_course`.`user_id`
AND `w_course`.`meta_key` = 'us_course'
WHERE
`w_name`.`meta_value` = '$us_name' AND
`w_year`.meta_value = '$us_yearselect' AND
`w_city`.`meta_value` = '$us_reg' AND
`w_course`.`meta_value` = '$us_course'
Other thing: Recommend to use prepared statements, because mysql_*
functions is not SQL injection save, and will be deprecated.
If you want to change your code the less as possible, you can use mysqli_
functions:
http://php.net/manual/en/book.mysqli.php
Recommendation:
Use indexes in this table. user_id
highly recommend to be and index, and recommend to be the meta_key
AND meta_value
too, for faster run of query.
The explain:
If you use AND
you 'connect' the conditions for one line. So if you want AND condition for multiple lines, first you must create one line from multiple lines, like this.
Tests: Table Data:
PRIMARY INDEX
int varchar(255) varchar(255)
/ \ |
+---------+---------------+-----------+
| user_id | meta_key | meta_value|
+---------+---------------+-----------+
| 1 | first_name | Kovge |
+---------+---------------+-----------+
| 1 | yearofpassing | 2012 |
+---------+---------------+-----------+
| 1 | u_city | GaPa |
+---------+---------------+-----------+
| 1 | us_course | PHP |
+---------+---------------+-----------+
The result of Query with $us_name='Kovge'
$us_yearselect='2012'
$us_reg='GaPa'
, $us_course='PHP'
:
+---------+
| user_id |
+---------+
| 1 |
+---------+
So it should works.
I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.
$.validator.addClassRules("price", {
required: true,
minlength: 2
});
This method does not require you to have validate method above this call.
Hope this will help someone in the future too. Source here.
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
Ok, i find solution changing the path of mysql-conector-java.jar to the follow path:
ProjectName/WebContent/Web-inf/lib/mysql-conector-java.jar
So you need to add the conector to project again and delete the previous one.
you can also add host as well with same command like :
php artisan serve --host=172.10.29.100 --port=8080
You can try this:
//custom date for example
$d1 = new DateTime("2012-07-08");
$d2 = new DateTime("2012-07-11");
$d3 = new DateTime("2012-07-08");
$d4 = new DateTime("2012-07-15");
//create a date period object
$interval = new DateInterval('P1D');
$daterange = iterator_to_array(new DatePeriod($d1, $interval, $d2));
$daterange1 = iterator_to_array(new DatePeriod($d3, $interval, $d4));
array_map(function($v) use ($daterange1) { if(in_array($v, $daterange1)) print "Bingo!";}, $daterange);
I like the answer of Anacrust, though, by the fact "console.log" is executed twice, I would like to do a small update for src/mylib.js
:
let test = {
foo () { return 'foo' },
bar () { return 'bar' },
baz () { return 'baz' }
}
export default test
All other code remains the same...
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
No need to do the loop, and using just standard Java library classes:
protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
if (length > 0) {
char[] array = new char[length];
Arrays.fill(array, charToFill);
return new String(array);
}
return "";
}
As you can see, I also added suitable code for the length == 0
case.
I started django server with the following command.
nohup manage.py runserver <localhost:port>
This works on CentOS:
:~ ns$netstat -ntlp
:~ ns$kill -9 PID
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
Turn the String into a char[], replace the letter by index, then convert the array back into a String.
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
There's the %
sign. It's not just for the remainder, it is the modulo operation.
# file? will only return true for files
File.file?(filename)
and
# Will also return true for directories - watch out!
File.exist?(filename)
Or you could replace '\' with '/' in the path.
Simulated Multiple Inheritance Pattern
http://www.codeproject.com/KB/architecture/smip.aspx
This may not be as slick as a one-liner, but I use it to perform date manipulation mainly for reports:
DECLARE @Date datetime
SET @Date = GETDATE()
-- Set all time components to zero
SET @Date = DATEADD(ms, -DATEPART(ms, @Date), @Date) -- milliseconds = 0
SET @Date = DATEADD(ss, -DATEPART(ss, @Date), @Date) -- seconds = 0
SET @Date = DATEADD(mi, -DATEPART(mi, @Date), @Date) -- minutes = 0
SET @Date = DATEADD(hh, -DATEPART(hh, @Date), @Date) -- hours = 0
-- Extra manipulation for month and year
SET @Date = DATEADD(dd, -DATEPART(dd, @Date) + 1, @Date) -- day = 1
SET @Date = DATEADD(mm, -DATEPART(mm, @Date) + 1, @Date) -- month = 1
I use this to get hourly, daily, monthly, and yearly dates used for reporting and performance indicators, etc.
A great alternative that hasn't been mentioned is to use the entity framework, which uses an object that is the table - to get data into an array you can do things like:
var rows = db.someTable.SqlQuery("SELECT col1,col2 FROM someTable").ToList().ToArray();
for info on getting started with Entity Framework see https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx
warning: LF will be replaced by CRLF.
Depending on the editor you are using, a text file with LF wouldn't necessary be saved with CRLF: recent editors can preserve eol style. But that git config setting insists on changing those...
Simply make sure that (as I recommend here):
git config --global core.autocrlf false
That way, you avoid any automatic transformation, and can still specify them through a .gitattributes
file and core.eol
directives.
windows git "LF will be replaced by CRLF"
Is this warning tail backward?
No: you are on Windows, and the git config
help page does mention
Use this setting if you want to have
CRLF
line endings in your working directory even though the repository does not have normalized line endings.
As described in "git replacing LF with CRLF", it should only occur on checkout (not commit), with core.autocrlf=true
.
repo
/ \
crlf->lf lf->crlf
/ \
As mentioned in XiaoPeng's answer, that warning is the same as:
warning: (If you check it out/or clone to another folder with your current
core.autocrlf
configuration,) LF will be replaced by CRLF
The file will have its original line endings in your (current) working directory.
As mentioned in git-for-windows/git
issue 1242:
I still feel this message is confusing, the message could be extended to include a better explanation of the issue, for example: "LF will be replaced by CRLF in
file.json
after removing the file and checking it out again".
Note: Git 2.19 (Sept 2018), when using core.autocrlf
, the bogus "LF
will be replaced by CRLF" warning is now suppressed.
As quaylar rightly comments, if there is a conversion on commit, it is to LF
only.
That specific warning "LF will be replaced by CRLF
" comes from convert.c#check_safe_crlf():
if (checksafe == SAFE_CRLF_WARN)
warning("LF will be replaced by CRLF in %s.
The file will have its original line endings
in your working directory.", path);
else /* i.e. SAFE_CRLF_FAIL */
die("LF would be replaced by CRLF in %s", path);
It is called by convert.c#crlf_to_git()
, itself called by convert.c#convert_to_git()
, itself called by convert.c#renormalize_buffer()
.
And that last renormalize_buffer()
is only called by merge-recursive.c#blob_unchanged()
.
So I suspect this conversion happens on a git commit
only if said commit is part of a merge process.
Note: with Git 2.17 (Q2 2018), a code cleanup adds some explanation.
See commit 8462ff4 (13 Jan 2018) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit 9bc89b1, 13 Feb 2018)
convert_to_git(): safe_crlf/checksafe becomes int conv_flags
When calling
convert_to_git()
, thechecksafe
parameter defined what should happen if the EOL conversion (CRLF --> LF --> CRLF
) does not roundtrip cleanly.
In addition, it also defined if line endings should be renormalized (CRLF --> LF
) or kept as they are.checksafe was an
safe_crlf
enum with these values:
SAFE_CRLF_FALSE: do nothing in case of EOL roundtrip errors
SAFE_CRLF_FAIL: die in case of EOL roundtrip errors
SAFE_CRLF_WARN: print a warning in case of EOL roundtrip errors
SAFE_CRLF_RENORMALIZE: change CRLF to LF
SAFE_CRLF_KEEP_CRLF: keep all line endings as they are
Note that a regression introduced in 8462ff4 ("convert_to_git()
:
safe_crlf/checksafe
becomes int conv_flags
", 2018-01-13, Git 2.17.0) back in Git 2.17 cycle caused autocrlf
rewrites to produce a warning message
despite setting safecrlf=false
.
See commit 6cb0912 (04 Jun 2018) by Anthony Sottile (asottile
).
(Merged by Junio C Hamano -- gitster
-- in commit 8063ff9, 28 Jun 2018)
Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:
If a call to a method matches more than one mock's when
trained calls, the order of the when
calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:
when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);
is the order that ensures the (probably) desired result:
foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false
If you inverse the when calls then the result would always be true
.
Still not cool enough to comment, but regarding @vladislav's comment the original article was fairly old. Here is an update document regarding DTU's, which would help answer the OP's question.
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-what-is-a-dtu
Way 1: only works for dataURL, not for other types of url.
function dataURLtoFile(dataurl, filename) {_x000D_
_x000D_
var arr = dataurl.split(','),_x000D_
mime = arr[0].match(/:(.*?);/)[1],_x000D_
bstr = atob(arr[1]), _x000D_
n = bstr.length, _x000D_
u8arr = new Uint8Array(n);_x000D_
_x000D_
while(n--){_x000D_
u8arr[n] = bstr.charCodeAt(n);_x000D_
}_x000D_
_x000D_
return new File([u8arr], filename, {type:mime});_x000D_
}_x000D_
_x000D_
//Usage example:_x000D_
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');_x000D_
console.log(file);
_x000D_
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance_x000D_
function urltoFile(url, filename, mimeType){_x000D_
return (fetch(url)_x000D_
.then(function(res){return res.arrayBuffer();})_x000D_
.then(function(buf){return new File([buf], filename,{type:mimeType});})_x000D_
);_x000D_
}_x000D_
_x000D_
//Usage example:_x000D_
urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')_x000D_
.then(function(file){ console.log(file);});
_x000D_
I was facing a similar issue while migrating some code from VS 2008 to VS 2010 Making changes to the App.config file resolved the issue for me.
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0.30319"
sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
</configuration>
For your need:
UPDATE classes
SET `date` = DATE_ADD(`date`, INTERVAL 2 DAY)
WHERE id = 161
Had the same problem with base64. For anyone in the future with the same problem:
url = "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";
This would work executed from console, but not from within a script:
$img.css("background-image", "url('" + url + "')");
But after playing with it a bit, I came up with this:
var img = new Image();
img.src = url;
$img.css("background-image", "url('" + img.src + "')");
No idea why it works with a proxy image, but it does. Tested on Firefox Dev 37 and Chrome 40.
Hope it helps someone.
EDIT
Investigated a little bit further. It appears that sometimes base64 encoding (at least in my case) breaks with CSS because of line breaks present in the encoded value (in my case value was generated dynamically by ActionScript).
Simply using e.g.:
$img.css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");
works too, and even seems to be faster by a few ms than using a proxy image.
you can use below methods
public static String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
or
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
the second one is better than first.
df['y']
will set a column
since you want to set a row, use .loc
Note that .ix
is equivalent here, yours failed because you tried to assign a dictionary
to each element of the row y
probably not what you want; converting to a Series tells pandas
that you want to align the input (for example you then don't have to to specify all of the elements)
In [7]: df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])
In [8]: df.loc['y'] = pandas.Series({'a':1, 'b':5, 'c':2, 'd':3})
In [9]: df
Out[9]:
a b c d
x NaN NaN NaN NaN
y 1 5 2 3
z NaN NaN NaN NaN
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
use the ternary operator ?:
change this
<?php if ($requestVars->_name == '') echo $redText; ?>
with
<?php echo ($requestVars->_name == '') ? $redText : ''; ?>
In short
// (Condition)?(thing's to do if condition true):(thing's to do if condition false);
mysql -u user -h 192.168.1.2 -p
This should be enough for connection to MySQL server.
Please, check the firewall of 192.168.1.2
if remote connection to MySQL server is enabled.
Regards
Thread.Sleep(50);
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread.Join
This work for me!
public void showLoader(){
URL url = this.getClass().getResource("images/ajax-loader.gif");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
frameLoader.setUndecorated(true);
frameLoader.getContentPane().add(label);
frameLoader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameLoader.pack();
frameLoader.setLocationRelativeTo(null);
frameLoader.setVisible(true);
}
You can do This :
$("#td_id").removeClass('Old_class');
$("#td_id").addClass('New_class');
Or You can do This
$("#td_id").removeClass('Old_class').addClass('New_class');
To convert character to numeric you have to convert it into factor by applying
BankFinal1 <- transform(BankLoan, LoanApproval=as.factor(LoanApproval))
BankFinal1 <- transform(BankFinal1, LoanApp=as.factor(LoanApproval))
You have to make two columns with the same data, because one column cannot convert into numeric. If you do one conversion it gives the below error
transform(BankData, LoanApp=as.numeric(LoanApproval))
Warning message: In eval(substitute(list(...)), `_data`, parent.frame()) : NAs introduced by coercion
so, after doing two column of the same data apply
BankFinal1 <- transform(BankFinal1, LoanApp = as.numeric(LoanApp),
LoanApproval = as.numeric(LoanApproval))
it will transform the character to numeric successfully
If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.
e.g.
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);
Delete the supplier, and it will delate all products for that supplier
(1:nrow(mydata_2))[mydata_2[,4] == 1578]
Of course there may be more than one row with a value of 1578.
For those who migrated to androidx, here is a list of mappings to new packages: https://developer.android.com/jetpack/androidx/migrate#class_mappings
Use implementation 'androidx.appcompat:appcompat:1.0.0'
Instead support library implementation 'com.android.support:appcompat-v7:28.0.0'
This is working nicely.
UPDATE state SET name = CONCAT(UCASE(LEFT(name, 1)), LCASE(SUBSTRING(name, 2)));
IF the table is existed. you can try insert into table_name select * from old_tale;
IF the table is not existed. you should try create table table_name like old_table; insert into table_name select * from old_tale;
for root, dirs, files in os.walk(directory):
for file in files:
floc = file
im = Image.open(str(directory) + '\\' + floc)
pix = np.array(im.getdata())
pixels.append(pix)
labels.append(1) # append(i)???
So far ok. But you want to leave pixels
as a list until you are done with the iteration.
pixels = np.array(pixels)
labels = np.array(labels)
You had this indention right in your other question. What happened? previous
Iterating, collecting values in a list, and then at the end joining things into a bigger array is the right way. To make things clear I often prefer to use notation like:
alist = []
for ..
alist.append(...)
arr = np.array(alist)
If names indicate something about the nature of the object I'm less likely to get errors like yours.
I don't understand what you are trying to do with traindata
. I doubt if you need to build it during the loop. pixels
and labels
have the basic information.
That
traindata = np.array([traindata[i][i],traindata[1]], dtype=object)
comes from the previous question. I'm not sure you understand that answer.
traindata = []
traindata.append(pixels)
traindata.append(labels)
if done outside the loop is just
traindata = [pixels, labels]
labels
is a 1d array, a bunch of 1s (or [0,1,2,3...] if my guess is right). pixels
is a higher dimension array. What is its shape?
Stop right there. There's no point in turning that list into an array. You can save the list with pickle
.
You are copying code from an earlier question, and getting the formatting wrong. cPickle very large amount of data
Sometimes, it may help switching off AllowAutoRedirect
and setting both login POST
and page GET
requests the same user agent.
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;
I'm not sure why there are no answers to what the question is asking for. i.e. All tags (non-annotated included) and without the suffix:
git describe --tags --abbrev=0
In Windows 7:
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip%
pause
Another problem solved by the rubber duck:
The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/
Change your HTML code to have the div before the header:
<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>
And keep your CSS to the simple div { float: right; }
.
It's a linker problem. Include the static library path into your project.
For Qt Creator open the project file .pro
and add the following line:
LIBS += -L<path for boost libraries in the system> -lboost_system
In my case Ubuntu x86_64:
LIBS += -L/usr/lib/x86_64-linux-gnu -lboost_system
For Codeblocks, open up Settings->Compiler...->Linker
settings tab and add:
boost_system
to the Link libraries text widget and press OK button.
For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.
First, create a string property on your Model.
public class MyModel
{
public string JavascriptToRun { get; set;}
}
Now, bind to your new model property in the Javascript of your view:
<script type="text/javascript">
@Model.JavascriptToRun
</script>
Now, also in your view, create a Javascript function that does whatever you need to do:
<script type="text/javascript">
@Model.JavascriptToRun
function ShowErrorPopup() {
alert('Sorry, we could not process your order.');
}
</script>
Finally, in your controller action, you need to call this new Javascript function:
[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
// Do something useful
...
if (success == false)
{
model.JavascriptToRun= "ShowErrorPopup()";
return View(model);
}
else
return RedirectToAction("Success");
}
Just add a new table
in the td
you want. Example: http://jsfiddle.net/AbE3Q/
<table border="1">
<tr>
<td>ABC</td>
<td>ABC</td>
<td>ABC</td>
<td>ABC</td>
</tr>
<tr>
<td>Item1</td>
<td>Item2</td>
<td>
<table border="1">
<tr>
<td>qweqwewe</td>
<td>qweqwewe</td>
</tr>
<tr>
<td>qweqwewe</td>
<td>qweqwewe</td>
</tr>
<tr>
<td>qweqwewe</td>
<td>qweqwewe</td>
</tr>
</table>
</td>
<td>Item3</td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
_x000D_
Another easy way is to use 2 premade sizes and pass them as parameter when calling the function in your html. use: 'lg' for large modals with width 900px 'sm' for small modals with width 300px or passing no parameter you use the default size which is 600px.
example code:
$scope.openModal = function (size) {
var modal = $modal.open({
templateUrl: "/partials/welcome",
controller: "welcomeCtrl",
backdrop: "static",
scope: $scope,
size: size,
});
modal.result.then(
//close
function (result) {
var a = result;
},
//dismiss
function (result) {
var a = result;
});
};
and in the html I would use something like the following:
<button ng-click="openModal('lg')">open Modal</button>
.htaccess
, httpd.conf
or VirtualHost
sectionHeader set X-Frame-Options SAMEORIGIN
this is the best optionAllow from URI
is not supported by all browsers. Reference: X-Frame-Options on MDN
I've found that modifying the textbox style (ie: controltemplate
) and then modifying the PART_ContentHost
vertical alignment to Center will do the trick
A compiler, in general, reads higher level language computer code and converts it to either p-code or native machine code. An interpreter runs directly from p-code or an interpreted code such as Basic or Lisp. Typically, compiled code runs much faster, is more compact, and has already found all of the syntax errors and many of the illegal reference errors. Interpreted code only finds such errors after the application attempts to interpret the affected code. Interpreted code is often good for simple applications that will only be used once or at most a couple times, or maybe even for prototyping. Compiled code is better for serious applications. A compiler first takes in the entire program, checks for errors, compiles it and then executes it. Whereas, an interpreter does this line by line, so it takes one line, checks it for errors, and then executes it.
If you need more information, just Google for "difference between compiler and interpreter".
My thought is that you can never just swap ends, you must always move from beginning-to-end, move through the string and look for "how many bytes will this character require?" I attach the character starting at the original end position, and remove the character from the front of the string.
void StringReverser(std::string *original)
{
int eos = original->length() - 1;
while (eos > 0) {
char c = (*original)[0];
int characterBytes;
switch( (c & 0xF0) >> 4 ) {
case 0xC:
case 0xD: /* U+000080-U+0007FF: two bytes. */
characterBytes = 2;
break;
case 0xE: /* U+000800-U+00FFFF: three bytes. */
characterBytes = 3;
break;
case 0xF: /* U+010000-U+10FFFF: four bytes. */
characterBytes = 4;
break;
default:
characterBytes = 1;
break;
}
for (int i = 0; i < characterBytes; i++) {
original->insert(eos+i, 1, (*original)[i]);
}
original->erase(0, characterBytes);
eos -= characterBytes;
}
}
Use the -s
or --strategy
option combined with the -X
option. In your specific question, you want to keep all of the remote files and replace the local files of the same name.
Replace conflicts with the remote version
git merge -s recursive -Xtheirs upstream/master
will use the remote repo version of all conflicting files.
Replace conflicts with the local version
git merge -s recursive -Xours upstream/master
will use the local repo version of all conflicting files.
Probably "new f-strings in Python 3.6" is the most efficient way of concatenating strings.
Using %s
>>> timeit.timeit("""name = "Some"
... age = 100
... '%s is %s.' % (name, age)""", number = 10000)
0.0029734770068898797
Using .format
>>> timeit.timeit("""name = "Some"
... age = 100
... '{} is {}.'.format(name, age)""", number = 10000)
0.004015227983472869
Using f
>>> timeit.timeit("""name = "Some"
... age = 100
... f'{name} is {age}.'""", number = 10000)
0.0019175919878762215
Angular CLI version 9 (used to create Angular 9 projects) now picks up
style
from schematics instead ofstyleext
. Use the command like this:
ng config schematics.@schematics/angular:component.style scss
and the resulting angular.json shall look like this"schematics": { "@schematics/angular:component": { "style": "scss" } }
Other possible solutions & explanations:
To create a new project with angular CLI with sass support, try this:
ng new My_New_Project --style=scss
You can also use --style=sass
& if you don't know the difference, read this short & easy article and if you still don't know, just go with scss
& keep learning.
If you have an angular 5 project, use this command to update the config for your project.
ng set defaults.styleExt scss
For Latest Versions
For Angular 6 to set new style on existing project with CLI:
ng config schematics.@schematics/angular:component.styleext scss
Or Directly into angular.json:
"schematics": {
"@schematics/angular:component": {
"styleext": "scss"
}
}
In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:
http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/
Personally, when I have 3 or more cases, I usually just go with case/switch.
even shorter if you can lose the yearStart value:
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
while(yearStart < yearEnd+1){
arr.push(yearStart++);
}
UPDATE: If you can use the ES6 syntax you can do it the way proposed here:
let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
.fill()
.map(() => yearStart++);
var thisList = new List<string>{ "a", "b", "c" };
var otherList = new List<string> {"a", "b"};
var theOnesThatDontMatch = thisList
.Where(item=> otherList.All(otherItem=> item != otherItem))
.ToList();
var theOnesThatDoMatch = thisList
.Where(item=> otherList.Any(otherItem=> item == otherItem))
.ToList();
Console.WriteLine("don't match: {0}", string.Join(",", theOnesThatDontMatch));
Console.WriteLine("do match: {0}", string.Join(",", theOnesThatDoMatch));
//Output:
//don't match: c
//do match: a,b
Adapt the list types and lambdas accordingly, and you can filter out anything.
It is due to OS
In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:
"scripts": {
"start": "node app.js",
"dev": "nodemon server.js",
"prod": "NODE_ENV=production & nodemon app.js"
}
For windows
Also set up your .env file variable having NODE_ENV=development
If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)
const dotenv = require('dotenv'); dotenv.config({ path: './config/config.env' });
SWIFT 3 Version of Alex Reynolds' Answer
let image = UIImage(named: "name") as UIImage?
let button = UIButton(type: UIButtonType.custom) as UIButton
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: Selector("btnTouched:"), for:.touchUpInside)
self.view.addSubview(button)
If you want to return a boolean value, then you can use something like this (much faster than filter):
players.stream().anyMatch(player -> player.getName().contains(name));
This will refresh current fragment :
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (Build.VERSION.SDK_INT >= 26) {
ft.setReorderingAllowed(false);
}
ft.detach(this).attach(this).commit();
If you use Java Web Start (you can start applications from any URL, even the local file system) it will take care of finding the right version for your application.
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
If you don't want 'a' in the index
In :
col = ['a','b','c']
data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In :
data2 = data.set_index('a')
Out:
b c
a
1 2 3
10 11 12
20 21 22
In :
data2.index.name = None
Out:
b c
1 2 3
10 11 12
20 21 22
pro swing:
But at the bottom line I wouldn't suggest to use 'pure' swing or swt ;-) There are several application frameworks for swing/swt out. Look here. The biggest players are netbeans (swing) and eclipse (swt). Another nice framework could be griffon and a nice 'set of components' is pivot (swing). Griffon is very interesting because it integrates a lot of libraries and not only swing; also pivot, swt, etc
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
you need just in scss varible
$input-btn-focus-width: .05rem !default;
$(window).mouseleave(function() {
alert('mouse leave');
});
INSERTED
and DELETED
are virtual tables. They need to be used in a FROM
clause.
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
IF EXISTS (SELECT foo
FROM database2.dbo.table2
WHERE id IN (SELECT deleted.id FROM deleted)
AND bar = 4)
Try this:
TextView textview = (TextView) findViewById(R.id.textview);
Typeface tf= Typeface.createFromAsset(getAssets(),"fonts/Tahoma.ttf");
textview .setTypeface(tf);
Late to the party, but if you use there's an excellent plugin called Moment:jQuery
then
var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();
http://momentjs.com/docs/#/manipulating/
And lots of other good stuff in there!
Edit: jQuery reference removed thanks to aikeru's comment
I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)
Note that the values for the position of the variable in the array go after the closing brace.
${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";
${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;
echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];
Basically, a Candidate Key is a Super Key from which no more Attribute can be pruned.
A Super Key identifies uniquely rows/tuples in a table/relation of a database. It is composed by a set of attributes that combined can assume values unique over the rows/tuples of a table/relation. A Candidate Key is built by a Super Key, iteratively removing/pruning non-key attributes, keeping an invariant: the newly created Key still need to uniquely identifies the rows/tuples.
A Candidate Key might be seen as a minimal Super Key, in terms of attributes.
Candidate Keys can be used to reference uniquely rows/tuples but from the RDBMS engine perspective the burden to maintain indexes on them is far heavier.
None of these answers helped me, but I found a solution.
I had a webproject used in Wildfly 8.2, built with Maven, source and target was set to 1.8 on maven-compiler-plugin, as well as all Eclipse and Maven settings were set to Java 1.8.
The problem was that Wildfly 8.2 cannot handle Java 1.8, so I had to set everything to 1.7 and it worked.
Surprised to see no mention of setTimeout.
To run a function without arguments:
var functionWithoutArguments = function(){
console.log("Executing functionWithoutArguments");
}
setTimeout("functionWithoutArguments()", 0);
To run function with arguments:
var functionWithArguments = function(arg1, arg2) {
console.log("Executing functionWithArguments", arg1, arg2);
}
setTimeout("functionWithArguments(10, 20)");
To run deeply namespaced function:
var _very = {
_deeply: {
_defined: {
_function: function(num1, num2) {
console.log("Execution _very _deeply _defined _function : ", num1, num2);
}
}
}
}
setTimeout("_very._deeply._defined._function(40,50)", 0);
Update alpha 47
As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows
http
.get('Some Url')
.map(res => res.json())
.subscribe(
(data) => this.data = data,
(err) => this.error = err); // Reach here if fails
Alpha 46 and below
You can handle the response in the map(...)
, before the subscribe
.
http
.get('Some Url')
.map(res => {
// If request fails, throw an Error that will be caught
if(res.status < 200 || res.status >= 300) {
throw new Error('This request has failed ' + res.status);
}
// If everything went fine, return the response
else {
return res.json();
}
})
.subscribe(
(data) => this.data = data, // Reach here if res.status >= 200 && <= 299
(err) => this.error = err); // Reach here if fails
Here's a plnkr with a simple example.
Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.
You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY
to your curl_setopt_array
method.
For example:
$proxy = '127.0.0.1:8888';
$opt = array (
CURLOPT_URL => "http://www.example.com",
CURLOPT_PROXY => $proxy,
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
);
$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);
If you are running postgresql on mac os, try these:
Edit the pg_hba.conf file
sudo vi /Library/PostgreSQL/9.2/data/pg_hba.conf
Change the "md5" method for all users to "trust" near the bottom of the file
Find the name of the service
ls /Library/LaunchDaemons
Look for postgresql
Stop the postgresql service
sudo launchctl stop com.edb.launchd.postgresql-9.2
Start the postgresql service
sudo launchctl start com.edb.launchd.postgresql-9.2
Start psql session as postgres
psql -U postgres
(shouldn't ask for password because of 'trust' setting)
Reset password in psql session by typing
ALTER USER postgres with password 'secure-new-password';
enter
Edit the pg_hba.conf file
Switch it back to 'md5'
Restart services again
Use
text-align: right
The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.
See
<td class='alnright'>text to be aligned to right</td>
<style>
.alnright { text-align: right; }
</style>
I was trying to go from godaddy to app engine. What did the trick was using this line:
openssl req -new -newkey rsa:2048 -nodes -keyout name.unencrypted.priv.key -out name.csr
Exactly as is, but replacing name with my domain name (not that it really even mattered)
And I answered all the questions pertaining to common name / organization as www.name.com
Then I opened the csr, copied it, pasted it in go daddy, then downloaded it, unzipped it, navigated to the unzipped folder with the terminal and entered:
cat otherfilegodaddygivesyou.crt gd_bundle-g2-g1.crt > name.crt
Then I used these instructions from Trouble with Google Apps Custom Domain SSL, which were:
openssl rsa -in privateKey.key -text > private.pem
openssl x509 -inform PEM -in www_mydomain_com.crt > public.pem
exactly as is, except instead of privateKey.key I used name.unencrypted.priv.key, and instead of www_mydomain_com.crt, I used name.crt
Then I uploaded the public.pem to the admin console for the "PEM encoded X.509 certificate", and uploaded the private.pem for the "Unencrypted PEM encoded RSA private key"..
.. And that finally worked.
You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.
Use JSON.stringify(object)
to turn it into (a string of) JSON text.
Check out your php.ini, you can set these values there.
Here's the description in the php manual: http://php.net/manual/en/mail.configuration.php
If you want to use several different SMTP servers in your application, I recommend using a "bigger" mailing framework, p.e. Swiftmailer
OTRS, Cerberus
You can also set the property programmatically during startup:
final String key = "java.protocol.handler.pkgs";
String newValue = "org.my.protocols";
if (System.getProperty(key) != null) {
final String previousValue = System.getProperty(key);
newValue += "|" + previousValue;
}
System.setProperty(key, newValue);
Using this class:
package org.my.protocols.classpath;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class Handler extends URLStreamHandler {
@Override
protected URLConnection openConnection(final URL u) throws IOException {
final URL resourceUrl = ClassLoader.getSystemClassLoader().getResource(u.getPath());
return resourceUrl.openConnection();
}
}
Thus you get the least intrusive way to do this. :) java.net.URL will always use the current value from the system properties.
A way to check if a path is directory can be following:
function isDirectory($path) {
$all = @scandir($path);
return $all !== false;
}
NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows
You need to first import header file <QuartzCore/QuartzCore.h>
#import QuartzCore/QuartzCore.h>
[yourView.layer setCornerRadius:8.0f];
yourView.layer.borderColor = [UIColor redColor].CGColor;
yourView.layer.borderWidth = 2.0f;
[yourView.layer setMasksToBounds:YES];
Don't miss to use -setMasksToBounds
, otherwise the effect may not be shown.
passlib seems to be useful if you need to use hashes stored by an existing system. If you have control of the format, use a modern hash like bcrypt or scrypt. At this time, bcrypt seems to be much easier to use from python.
passlib supports bcrypt, and it recommends installing py-bcrypt as a backend: http://pythonhosted.org/passlib/lib/passlib.hash.bcrypt.html
You could also use py-bcrypt directly if you don't want to install passlib. The readme has examples of basic use.
see also: How to use scrypt to generate hash for password and salt in Python
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
use ng-pattern, so that ng-valid and ng-dirty can act correctly
Email:<input type="email" name="email1" ng-model="emailReg">
Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-pattern="emailReg">
<span ng-show="registerForm.email2.$error.pattern">Emails have to match!</span>
Read file contents into a variable:
for /f "delims=" %%x in (version.txt) do set Build=%%x
or
set /p Build=<version.txt
Both will act the same with only a single line in the file, for more lines the for
variant will put the last line into the variable, while set /p
will use the first.
Using the variable – just like any other environment variable – it is one, after all:
%Build%
So to check for existence:
if exist \\fileserver\myapp\releasedocs\%Build%.doc ...
Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.
Bdizzle,
I would recommend that you read this link
You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.
Be happy, Julian
Abstract classes and interfaces are semantically different, although their usage can overlap.
An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.
An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.
Both source and target should be specified. I recommend providing ant defaults, that way you do not need to specify source/target attribute for every javac task:
<property name="ant.build.javac.source" value="1.5"/>
<property name="ant.build.javac.target" value="1.5"/>
See Java cross-compiling notes for more information.
Port: In simple language, "Port" is a number used by a particular software to identify its data coming from internet.
Each software, like Skype, Chrome, Youtube has its own port number and that's how they know which internet data is for itself.
Socket: "IP address and Port " together is called "Socket". It is used by another computer to send data to one particular computer's particular software.
IP address is used to identify the computer and Port is to identify the software such as IE, Chrome, Skype etc.
In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.
Try This
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($startDate)), date("d",strtotime($startDate)), date("Y",strtotime($startDate))+1));
It's simple, get the character you want, and convert it to int.
String name = "admin";
int ascii = name.charAt(0);
I don't know much about jQuery, but try this:
row_id = "#5";
row = $("body").find(row_id);
Edit: Of course, if the variable is a number, you have to add "#"
to the front:
row_id = 5
row = $("body").find("#"+row_id);
To avoid the problem caused when you change the outline property on a focus, is tho give a visual effect when the user Tab on the input button or click on it.
In this case is a submit type, but you can apply to a type="button" too.
input[type="submit"]:focus {_x000D_
outline: none !important;_x000D_
background-color: rgb(208, 192, 74);_x000D_
}
_x000D_
The pop
method of dicts (like self.data
, i.e. {'a':'aaa','b':'bbb','c':'ccc'}
, here) takes two arguments -- see the docs
The second argument, default
, is what pop
returns if the first argument, key
, is absent.
(If you call pop
with just one argument, key
, it raises an exception if that key's absent).
In your example, print b.pop('a',{'b':'bbb'})
, this is irrelevant because 'a'
is a key in b.data
. But if you repeat that line...:
b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
you'll see it makes a difference: the first pop
removes the 'a'
key, so in the second pop
the default
argument is actually returned (since 'a'
is now absent from b.data
).
In case \n or \r is not working and if you are working with uiwebview and trying to load html using < br > tag to insert new line. Don't just use < br > tag in NSString stringWithFormat.
Instead use the same by appending. i.e by using stringByAppendingString
yourNSString = [yourNSString stringByAppendingString:@"<br>"];
Try adding this line before your dialog line.
$( "#dialog" ).dialog( "open" );
This method worked for me. It seems that the "close" command messes up the dialog opening again with only the .dialog() .
Using your code as an example, it would go in like this (note that you may need to add more to your code for it to make sense):
<script type="text/javascript">
$(document).ready(function() {
//$('#dialog').dialog();
$('#dialog_link').click(function() {
$( "#dialog" ).dialog( "open" );
$('#dialog').dialog();
return false;
});
});
</script>
</head><body>
<div id="dialog" title="Dialog Title" style="display:none"> Some text</div>
<p id="dialog_link">Open Dialog</p>
</body></html>
var fs = require("fs");
function readFileLineByLine(filename, processline) {
var stream = fs.createReadStream(filename);
var s = "";
stream.on("data", function(data) {
s += data.toString('utf8');
var lines = s.split("\n");
for (var i = 0; i < lines.length - 1; i++)
processline(lines[i]);
s = lines[lines.length - 1];
});
stream.on("end",function() {
var lines = s.split("\n");
for (var i = 0; i < lines.length; i++)
processline(lines[i]);
});
}
var linenumber = 0;
readFileLineByLine(filename, function(line) {
console.log(++linenumber + " -- " + line);
});
try this one
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(
"http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000);
urlc.setReadTimeout(4000);
urlc.connect();
// networkcode2 = urlc.getResponseCode();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return (false);
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
you'll have to add the following permission to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Then call like that:
if((new ConnectionDetector(MyService.this)).isConnectingToInternet()){
Log.d("internet status","Internet Access");
}else{
Log.d("internet status","no Internet Access");
}
Incase you are not able to resolve the issue in any other way, then try this(it worked for me!):
Keep this below code into your web config file then rename value="yourwebformname.aspx"
<system.webServer>
<defaultDocument>
<files>
<add value="insertion.aspx" />
</files>
</defaultDocument>
<directoryBrowse enabled="false" />
</system.webServer>
else Try:
<system.webServer>
<directoryBrowse enabled="true" />
</system.webServer>
function playSound(url) {
const audio = new Audio(url);
audio.play();
}
<button onclick="playSound('https://your-file.mp3');">Play</button>
Edge 12+, Firefox 20+, Internet Explorer 9+, Opera 15+, Safari 4+, Chrome
Just use MP3
(for legacy browsers)
function playSound(filename){
var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename +'.mp3">';
document.getElementById("sound").innerHTML='<audio autoplay="autoplay">' + mp3Source + oggSource + embedSource + '</audio>';
}
<button onclick="playSound('bing');">Play</button>
<div id="sound"></div>
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
Turn OFF "Safe Update Mode" temporary
SET SQL_SAFE_UPDATES = 0;
UPDATE options SET title= 'kiemvieclam24h' WHERE url = 'http://kiemvieclam24h.net';
SET SQL_SAFE_UPDATES = 1;
Turn OFF "Safe Update Mode" forever
Mysql workbench 8.0:
MySQL Workbench => [ Edit ] => [ Preferences ] -> [ SQL Editor ] -> Uncheck "Safe Updates"
MySQL Workbench => [Edit] => [Preferences] => [SQL Queries]
SafeAreaLayoutGuide
is UIView
property,
The top of the safeAreaLayoutGuide indicates the unobscured top edge of the view (e.g, not behind the status bar or navigation bar, if present). Similarly for the other edges.
Use safeAreaLayoutGuide
for avoid our objects clipping/overlapping from rounded corners, navigation bars, tab bars, toolbars, and other ancestor views.
We can create safeAreaLayoutGuide
object & set object constraints respectively.
Constraints for Portrait + Landscape is -
self.edgesForExtendedLayout = []//Optional our as per your view ladder
let newView = UIView()
newView.backgroundColor = .red
self.view.addSubview(newView)
newView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
newView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
newView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
newView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
else {
NSLayoutConstraint(item: newView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: newView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: newView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
I forgot to push the image tagged 1.0.8 to the ECR (AWS images hub)... If you are using Helm and upgrade by:
helm upgrade minta-user ./src/services/user/helm-chart
make sure that image tag inside values.yaml is pushed (to ECR or Docker Hub, etc) for example: (this is my helm-chart/values.yaml)
replicaCount: 1
image:
repository:dkr.ecr.us-east-1.amazonaws.com/minta-user
tag: 1.0.8
you need to make sure that the image:1.0.8 is pushed!
Another Workaround. Much easier in Angular Router V3 Alpha. by injecting Router
import {Router} from "@angular/router";
export class AppComponent{
constructor(private router : Router){}
routeIsActive(routePath: string) {
return this.router.url == routePath;
}
}
usage
<div *ngIf="routeIsActive('/')"> My content </div>
I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:
s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]
Do git status
, this will show you what files have changed. Since you stated that you don't want to keep the changes you can do git checkout -- <file name>
or git reset --hard
to get rid of the changes.
For the most part, git will tell you what to do about changes. For example, your error message said to git stash
your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop
and your changes would be reapplied.
git status
also has how to get rid of changes depending on if the file is staged for commit or not.
after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.
I tried the callback way and could not get this to work, what you have to understand is that values are still atomic even though execution is not. For example:
alert('1');
<--- these two functions will be executed at the same time
alert('2');
<--- these two functions will be executed at the same time
but doing like this will force us to know the order of execution:
loop=2;
total=0;
for(i=0;i<loop;i++) {
total+=1;
if(total == loop)
alert('2');
else
alert('1');
}
As complement to Mark's answer, the compile function does not have access to scope, but the link function does.
I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).
>>> import numpy
>>> print numpy.power.__doc__
power(x1, x2[, out])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
Examples
--------
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
>>>
As per the discussed observation on numerical precision as per @GarethRees objection in comments:
>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677
>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241
>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )
>>> import zmq
>>> aClk = zmq.Stopwatch()
>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]
>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]
>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]
>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]
>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]
I came up with some kind of solution to the problem. It involves jquery and css. This works like toggle but instead of toggling the display of elements it just changes its properties upon alternate clicks. Upon clicking the div it rotates the element with tag 180 degrees and when you click it again the element with tag returns to its original position. If you want to change the animation duration just change transition-duration property.
CSS
#example1{
transition-duration:1s;
}
jQuery
$(document).ready( function () { var toggle = 1;
$('div').click( function () {
toggle++;
if ( (toggle%2)==0){
$('#example1').css( {'transform': 'rotate(180deg)'});
}
else{
$('#example1').css({'transform': 'rotate(0deg)'});
}
});
});
If you have empty rows, not NAs, you can do:
data[!apply(data == "", 1, all),]
To remove both (NAs and empty):
data <- data[!apply(is.na(data) | data == "", 1, all),]
Here is a function that calculates the current position of an element within the viewport:
/**
* Calculates the position of a given element within the viewport
*
* @param {string} obj jQuery object of the dom element to be monitored
* @return {array} An array containing both X and Y positions as a number
* ranging from 0 (under/right of viewport) to 1 (above/left of viewport)
*/
function visibility(obj) {
var winw = jQuery(window).width(), winh = jQuery(window).height(),
elw = obj.width(), elh = obj.height(),
o = obj[0].getBoundingClientRect(),
x1 = o.left - winw, x2 = o.left + elw,
y1 = o.top - winh, y2 = o.top + elh;
return [
Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),
Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))
];
}
The return values are calculated like this:
Usage:
visibility($('#example')); // returns [0.3742887830933581, 0.6103752759381899]
Demo:
function visibility(obj) {var winw = jQuery(window).width(),winh = jQuery(window).height(),elw = obj.width(),_x000D_
elh = obj.height(), o = obj[0].getBoundingClientRect(),x1 = o.left - winw, x2 = o.left + elw, y1 = o.top - winh, y2 = o.top + elh; return [Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))];_x000D_
}_x000D_
setInterval(function() {_x000D_
res = visibility($('#block'));_x000D_
$('#x').text(Math.round(res[0] * 100) + '%');_x000D_
$('#y').text(Math.round(res[1] * 100) + '%');_x000D_
}, 100);
_x000D_
#block { width: 100px; height: 100px; border: 1px solid red; background: yellow; top: 50%; left: 50%; position: relative;_x000D_
} #container { background: #EFF0F1; height: 950px; width: 1800px; margin-top: -40%; margin-left: -40%; overflow: scroll; position: relative;_x000D_
} #res { position: fixed; top: 0; z-index: 2; font-family: Verdana; background: #c0c0c0; line-height: .1em; padding: 0 .5em; font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="res">_x000D_
<p>X: <span id="x"></span></p>_x000D_
<p>Y: <span id="y"></span></p>_x000D_
</div>_x000D_
<div id="container"><div id="block"></div></div>
_x000D_
I did this recently but included double quotes around my values.
For example, change these two lines:
sb.Append("\"" + col.ColumnName + "\",");
...
sb.Append("\"" + row[i].ToString() + "\",");
As many said - this version
int maxAge = context.Persons.Max(p => p.Age);
throws an exception when table is empty.
Use
int maxAge = context.Persons.Max(x => (int?)x.Age) ?? 0;
or
int maxAge = context.Persons.Select(x => x.Age).DefaultIfEmpty(0).Max()
Here you go:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<style type="text/css">
div {
border: 1px solid black;
padding: 5px;
margin: 5px;
width: 600px;
height: 600px;
float: left;
color: white;
}
.grayscale {
background: url(yourimagehere.jpg);
-moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-webkit-filter: grayscale(100%);
filter: gray;
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
}
.nongrayscale {
background: url(yourimagehere.jpg);
}
</style>
</head>
<body>
<div class="nongrayscale">
this is a non-grayscale of the bg image
</div>
<div class="grayscale">
this is a grayscale of the bg image
</div>
</body>
</html>
Tested it in FireFox, Chrome and IE. I've also attached an image to show my results of my implementation of this.
EDIT: Also, if you want the image to just toggle back and forth with jQuery, here's the page source for that...I've included the web link to jQuery and and image that's online so you should just be able to copy/paste to test it out:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style type="text/css">
div {
border: 1px solid black;
padding: 5px;
margin: 5px;
width: 600px;
height: 600px;
float: left;
color: white;
}
.grayscale {
background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
-moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-webkit-filter: grayscale(100%);
filter: gray;
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
}
.nongrayscale {
background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$("#image").mouseover(function () {
$(".nongrayscale").removeClass().fadeTo(400,0.8).addClass("grayscale").fadeTo(400, 1);
});
$("#image").mouseout(function () {
$(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
});
});
</script>
</head>
<body>
<div id="image" class="nongrayscale">
rollover this image to toggle grayscale
</div>
</body>
</html>
EDIT 2 (For IE10-11 Users): The solution above will not work with the changes Microsoft has made to the browser as of late, so here's an updated solution that will allow you to grayscale (or desaturate) your images.
<svg>_x000D_
<defs>_x000D_
<filter xmlns="http://www.w3.org/2000/svg" id="desaturate">_x000D_
<feColorMatrix type="saturate" values="0" />_x000D_
</filter>_x000D_
</defs>_x000D_
<image xlink:href="http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg" width="600" height="600" filter="url(#desaturate)" />_x000D_
</svg>
_x000D_
If possible I would try to write those test without Spring Context. If you create this class in your test without spring, then you have full control over its fields.
To set the @value
field you can use Springs ReflectionTestUtils
- it has a method setField
to set private fields.
@see JavaDoc: ReflectionTestUtils.setField(java.lang.Object, java.lang.String, java.lang.Object)
To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.
I think it's not simple to set caret to some position in contenteditable element. I wrote my own code for this. It bypasses the node tree calcing how many characters left and sets caret in needed element. I didn't test this code much.
//Set offset in current contenteditable field (for start by default or for with forEnd=true)
function setCurSelectionOffset(offset, forEnd = false) {
const sel = window.getSelection();
if (sel.rangeCount !== 1 || !document.activeElement) return;
const firstRange = sel.getRangeAt(0);
if (offset > 0) {
bypassChildNodes(document.activeElement, offset);
}else{
if (forEnd)
firstRange.setEnd(document.activeElement, 0);
else
firstRange.setStart(document.activeElement, 0);
}
//Bypass in depth
function bypassChildNodes(el, leftOffset) {
const childNodes = el.childNodes;
for (let i = 0; i < childNodes.length && leftOffset; i++) {
const childNode = childNodes[i];
if (childNode.nodeType === 3) {
const curLen = childNode.textContent.length;
if (curLen >= leftOffset) {
if (forEnd)
firstRange.setEnd(childNode, leftOffset);
else
firstRange.setStart(childNode, leftOffset);
return 0;
}else{
leftOffset -= curLen;
}
}else
if (childNode.nodeType === 1) {
leftOffset = bypassChildNodes(childNode, leftOffset);
}
}
return leftOffset;
}
}
I also wrote code to get current caret position (didn't test):
//Get offset in current contenteditable field (start offset by default or end offset with calcEnd=true)
function getCurSelectionOffset(calcEnd = false) {
const sel = window.getSelection();
if (sel.rangeCount !== 1 || !document.activeElement) return 0;
const firstRange = sel.getRangeAt(0),
startContainer = calcEnd ? firstRange.endContainer : firstRange.startContainer,
startOffset = calcEnd ? firstRange.endOffset : firstRange.startOffset;
let needStop = false;
return bypassChildNodes(document.activeElement);
//Bypass in depth
function bypassChildNodes(el) {
const childNodes = el.childNodes;
let ans = 0;
if (el === startContainer) {
if (startContainer.nodeType === 3) {
ans = startOffset;
}else
if (startContainer.nodeType === 1) {
for (let i = 0; i < startOffset; i++) {
const childNode = childNodes[i];
ans += childNode.nodeType === 3 ? childNode.textContent.length :
childNode.nodeType === 1 ? childNode.innerText.length :
0;
}
}
needStop = true;
}else{
for (let i = 0; i < childNodes.length && !needStop; i++) {
const childNode = childNodes[i];
ans += bypassChildNodes(childNode);
}
}
return ans;
}
}
You also need to be aware of range.startOffset and range.endOffset contain character offset for text nodes (nodeType === 3) and child node offset for element nodes (nodeType === 1). range.startContainer and range.endContainer may refer to any element node of any level in the tree (of course they also can refer to text nodes).
I think it would look better if we add border-color : transparent as per below:
<hr style="width: 100%; background-color: black; height: 1px; border-color : transparent;" />
If you don't put the border transparent it will be white and i don't think that is good all time.
I would like to make a addon for tiago's answer:
Suppose you're hiding element using ng-show
and adding a required
attribute on the same:
<div ng-show="false">
<input required name="something" ng-model="name"/>
</div>
will throw an error something like :
An invalid form control with name='' is not focusable
This is because you just cannot impose required
validation on hidden
elements. Using ng-required
makes it easier to conditionally apply required validation which is just awesome!!
You can use PowerShell.
New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
You're calling br.readLine()
a second time inside the loop.
Therefore, you end up reading two lines each time you go around.
You can use esentutl to copy (mainly big) files with a progress bar:
esentutl /y "my.file" /d "another.file" /o
the progress bar looks like this:
There is pure CSS4 solution:
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
user-select
is a CSS Module Level 4 specification, that is currently a draft and non-standard CSS property, but browsers support it well — see #search=user-select.
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
_x000D_
<div class="selectable">
click and all this will be selected
</div>
_x000D_
Read more on user-select here on MDN and play with it here in w3scools
When you define different build configurations in your visual studio solution for your projects using a tool like ConfigurationTransform, you may want your Teamcity build, to build you a specified build configuration. You may have build configurations e.g., Debug, Release, Dev, UAT, Prod etc defined. This means, you will have MSBuild Configuration transformation setup for the different configurations. These different configurations are usually used when you have different configurations, e.g. different database connection strings, for the different environment. This is very common because you would have a different database for your production environment from your playground development environment.
They say a picture is worth a thousand words, please see the image below how you would specify multiple build configurations in Teamcity.
In the commandline input text box, specify as below
/p:OutputPath=Publish;Configuration=Dev
Here, I have specified two commandline build configurations/arguments OutputPath
and build Configuration
with values Publish
and Dev
respectively, but it could have been, UAT
or Prod
configuration. If you want more, simply separate them by semi-colon,;
Using your example where...
countries= [nan, 'USA', 'UK', 'France']
Since nan is not equal to nan (nan != nan) and countries[0] = nan, you should observe the following:
countries[0] == countries[0]
False
However,
countries[1] == countries[1]
True
countries[2] == countries[2]
True
countries[3] == countries[3]
True
Therefore, the following should work:
cleanedList = [x for x in countries if x == x]
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.
Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
As others have answered there is no way to get the count of rows without iterating till the end. You could do that, but you may not want to, note the following points:
For a many RDBMS systems ResultSet is a streaming API, this means that it does not load (or maybe even fetch) all the rows from the database server. See this question on SO. By iterating to the end of the ResultSet you may add significantly to the time taken to execute in certain cases.
A default ResultSet object is not updatable and has a cursor
that moves forward only. I think this means that unless you
execute
the query with ResultSet.TYPE_SCROLL_INSENSITIVE
rSet.beforeFirst()
will throw
SQLException
. The reason it is this way is because there is cost
with scrollable cursor. According to the documentation, it may throw SQLFeatureNotSupportedException
even if you create a scrollable cursor.
Populating and returning a List<Operations>
means that you will
also need extra memory. For very large resultsets this will not
work
at all.
So the big question is which RDBMS?. All in all I would suggest not logging the number of records.
In my case, I had the wrong IP Address in the virtual host file. The listen was 443, and the stanza was <VirtualHost 192.168.0.1:443>
but the server did not have the 192.168.0.1 address!
Since version 3.2 :
def toSigned(n, byte_count):
return int.from_bytes(n.to_bytes(byte_count, 'little'), 'little', signed=True)
output :
In [8]: toSigned(5, 1)
Out[8]: 5
In [9]: toSigned(0xff, 1)
Out[9]: -1
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').value = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
</HTML>
This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags
Note This is an improvement in @user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of @user3516549 but in some cases it was not working properly.
I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as
content://com.android.providers.media.documents/document/image%3A52530
while if user select gallery from sliding drawer instead of recent then we will get uri as
content://media/external/images/media/52530
So I have handle it in getRealPathFromURI_API19()
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
return getRealPathFromURI_BelowAPI11(context,uri)
}
}
EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question
EDIT2 Here is complete code with handling virtual files and host other than com.android.providers
I have tested this method with content://com.adobe.scan.android.documents/document/
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
I would try any(byte[].class)
Note that the following:
var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);
will alert 1
from manual:
: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.
As this returns always zero therefore is is similar to be used as true
Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?
import os
import os.path
import shutil
You find your current directory:
d = os.getcwd() #Gets the current working directory
Then you change one directory up:
os.chdir("..") #Go up one directory from working directory
Then you can get a tupple/list of all the directories, for one directory up:
o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple
Then you can search the tuple for the directory you want and open the file in that directory:
for item in o:
if os.path.exists(item + '\\testfile.txt'):
file = item + '\\testfile.txt'
Then you can do stuf with the full file path 'file'
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
For those wanting to have the more common undo/redo functionality, someone has written undo-tree.el
. It provides the look and feel of non-Emacs undo, but provides access to the entire 'tree' of undo history.
I like Emacs' built-in undo system, but find this package to be very intuitive.
Here's the commentary from the file itself:
Emacs has a powerful undo system. Unlike the standard undo/redo system in most software, it allows you to recover any past state of a buffer (whereas the standard undo/redo system can lose past states as soon as you redo). However, this power comes at a price: many people find Emacs' undo system confusing and difficult to use, spawning a number of packages that replace it with the less powerful but more intuitive undo/redo system.
Both the loss of data with standard undo/redo, and the confusion of Emacs' undo, stem from trying to treat undo history as a linear sequence of changes. It's not. The `undo-tree-mode' provided by this package replaces Emacs' undo system with a system that treats undo history as what it is: a branching tree of changes. This simple idea allows the more intuitive behaviour of the standard undo/redo system to be combined with the power of never losing any history. An added side bonus is that undo history can in some cases be stored more efficiently, allowing more changes to accumulate before Emacs starts discarding history.
the easiest way is :
static void lineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit - 1] = newText;
File.WriteAllLines(fileName, arrLine);
}
usage :
lineChanger("new content for this line" , "sample.text" , 34);
try:
#if it gone wrong then it will go to except
except:
try:
#if it also go wrong then it will go to except
except:
try:
#if it also go wrong then it will go to except
except:
print('write what is your need')
def():
try:
A = 5
raise SyntaxError
except:
try:
A = 5
raise SyntaxError
except:
try:
A = 5
raise SyntaxError
except:
print('None')
finally:
return A
The above formatting approach works but only for three levels. The above used KB, MB, and GB. Here I've expanded it to six. Right-click on the cell(s) and select Format Cells. Under the Number tab, select Custom. Then in the Type: box, put the following:
[<1000]##0.00" B";[<1000000]##0.00," KB";##0.00,," MB"
Then select OK. This covers B, KB, and MB. Then, with the same cells selected, click Home ribbon, Conditional Formatting, New Rule. Select Format only cells that contain. Then below in the rule description, Format only cells with, Cell Value, greater than or equal to, 1000000000 (that's 9 zeros.) Then click on Format, Number tab, Custom, and in the Type: box, put the following:
[<1000000000000]##0.00,,," GB";[<1000000000000000]##0.00,,,," TB";#,##0.00,,,,," PB"
Select OK, and OK. This conditional formatting will take over only if the value is bigger than 1,000,000,000. And it will take care of the GB, TB, and PB ranges.
567.00 B
5.67 KB
56.70 KB
567.00 KB
5.67 MB
56.70 MB
567.00 MB
5.67 GB
56.70 GB
567.00 GB
5.67 TB
56.70 TB
567.00 TB
5.67 PB
56.70 PB
Anything bigger than PB will just show up as a bigger PB, e.g. 56,700 PB. You could add another conditional formatting to handle even bigger values, EB, and so on.
I can't answer your original question but I would like to offer you some advice -- don't depend on the JVM's default encoding. It's always best to explicitly specify the desired encoding (i.e. "UTF-8") in your code. That way, you know it will work even across different systems and JVM configurations.
Get today's date (& time) and apply them as maximum date.
Calendar c = Calendar.getInstance();
c.set(2017, 0, 1);//Year,Mounth -1,Day
your_date_picker.setMaxDate(c.getTimeInMillis());
ALSO WE MAY DO THIS (check this Stackoverflow answer for System.currentTimeMillis() vs Calendar method)
long now = System.currentTimeMillis() - 1000;
dp_time.setMinDate(now);
dp_time.setMaxDate(now+(1000*60*60*24*7)); //After 7 Days from Now
If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:
var x =
"<div> \
<span> \
<p> \
some text \
</p> \
</div>";
This is what I used for similar type of use case as yours.
<style type="text/css">
#element1 {display:inline-block; width:45%; padding:10px}
#element2 {display:inline-block; width:45%; padding:10px}
</style>
<div id="element1">
element 1 markup
</div>
<div id="element2">
element 2 markup
</div>
Adjust your width and padding as per your requirement. Note - Do not exceed 'width' more than 100% altogether (ele1_width+ ele2_width) to add 'padding', keep it less than 100%.
You can use Notepad++ to evaluate a file's encoding without needing to write code. The evaluated encoding of the open file will display on the bottom bar, far right side. The encodings supported can be seen by going to Settings -> Preferences -> New Document/Default Directory
and looking in the drop down.
open my Computer ==>
right click inside my computer and select properties ==>
Click on Advanced System Settings ==>
Environment Variables ==>
from the System Variables box select "PATH" ==>
Edit... ==>
then add this at the end of whatever you find their
;C:\PostgreSQL\9.2\bin; C:\PostgreSQL\9.2\lib
after that continue to click OK
open cmd/command prompt.... open psql in command prompt with this
psql -U username database
eg. i have a database name FRIENDS and a user MEE.. it will be
psql -U MEE FRIENDS
you will be then prompted to give the password of the user in question. Thanks
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
What is the difference between g++
and gcc
?
gcc
has evolved from a single language "GNU C Compiler" to be a multi-language "GNU Compiler Collection". The term "GNU C Compiler" is still used sometimes in the context of C programming.
The g++
is the C++ compiler for the GNU Compiler Collection. Like gnat
is the Ada compiler for gcc
. see Using the GNU Compiler Collection (GCC)
For example, the Ubuntu 16.04 and 18.04 man g++
command returns the GCC(1)
manual page.
The Ubuntu 16.04 and 18.04 man gcc
states that ...
g++
accepts mostly the same options asgcc
and that the default ...
... use of
gcc
does not add the C++ library.g++
is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations.
Search the gcc
man pages for more details on the option variances between gcc
and g++
.
Which one should be used for general c++ development?
Technically, either gcc
or g++
can be used for general C++ development with applicable option settings. However, the g++
default behavior is naturally aligned to a C++ development.
The Ubuntu 18.04 'gcc' man page added, and Ubuntu 20.04 continues to have, the following paragraph:
The usual way to run GCC is to run the executable called
gcc
, ormachine-gcc
when cross-compiling, ormachine-gcc-version
to run a specific version of GCC. When you compile C++ programs, you should invoke GCC asg++
instead.
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
This gets and alerts the id of the element with the id "ele".
var id = document.getElementById("ele").id;
alert("ID: " + id);
You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.
I have code on GitHub which uses System.Windows.Forms
NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs
Here are the summary bits:
Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.
At class-level:
private System.Windows.Forms.NotifyIcon notifyIcon = null;
During OnInitialize():
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];
During OnLoaded():
notifyIcon.Visible = true;
And for interaction (shown as notifyIcon.Click and DoubleClick above):
void notifyIcon_Click(object sender, EventArgs e)
{
ShowQuickLaunchMenu();
}
From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.
It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.
Hope that helps.
It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.
At first, you need to convert time span to DateTime structure:
var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)
Then you need to convert the value to string with Short Time format
var result = dt.ToString("t"); // Convert to string using Short Time format
1. install moment
npm install moment --save
2. test this code in your typescript file
import moment = require('moment');
console.log(moment().format('LLLL'));
If ASP.NET 4.0 is not registered with IIS
*****Use this step if u cant access using run command*****
Go to
C Drive
-->>windows
-->>Microsoft.Net
-->>Framework
-->>v4.0.30319
(Choose whatever framework to register with IIS me selecting Framework 4)-->>aspnet_regiis
(Double-click or right click & choose run as administrator)
If you know the bitrate, it's simply bitrate (bits per second) multiplied by number of seconds. Given that HDV is 25 Mbit/s and one hour has 3,600 seconds, non-transcoded it would be:
25 Mbit/s * 3,600 s/hr = 3.125 MB/s * 3,600 s/hr = 11,250 MB/hr ˜ 11 GB/hr
Google's calculator can confirm
The same applies with H.264 footage, although the above might not be as accurate (being variable bitrate and such).
I want to archive approximately 100 hours of such content and want to figure out whether I'm looking at a big hard drive, a multi-drive unit like a Drobo, or an enterprise-level storage system.
First, do not buy an "enterprise-level" storage system (you almost certainly don't need things like hot-swap drives and the same level of support - given the costs)..
I would suggest buying two big drives: One would be your main drive, another in a USB enclosure, and would be connected daily and mirror the primary system (as a backup).
Drives are incredibly cheap, using the above calculation of ~11 GB/hour, that's only 1.1 TB of data (for 100 hours, uncompressed). and you can buy 2 TB drives now.
Drobo, or a machine with a few drives and software RAID is an option, but a single large drive plus backups would be simpler.
Storage is almost a non-issue now, but encode time can still be an issue. Encoding H.264 is very resource-intensive. On a quad-core ~2.5 GHz Xeon, I think I got around 60 fps encoding standard-def (DVD) to H.264 (compared to around 300 fps with MPEG 4). I suppose that's only about 50 hours, but it's something worth considering. Also, assuming the HDV is on tapes, it's a 1:1 capture time, so that's 150 hours of straight processing, never mind things like changing tapes, entering metadata, and general delays (sleep) and errors ("opps, wrong tape").
As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases
In the options panel you can configure which header to inject and specific website to have it enabled automatically.
I found the issue. This is a firewall message and an error was occurring in the VB script due to wrong data in database, but the error was not logged/caught properly.
If you're open to using AWK:
awk '/textstring/ {print FNR}' textfile
In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.
I find it easier to pass a value as a temporal data type (e.g. DATETIME
) then use temporal functionality, specifically DATEADD
and DATEPART
, to find the start and end dates for the period, in this case the month e.g. this finds the start date and end date pair for the current month, just substitute CURRENT_TIMESTAMP
for you parameter of of type DATETIME
(note the 1990-01-01 value is entirely arbitrary):
SELECT DATEADD(M,
DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP),
'1990-01-01T00:00:00.000'),
DATEADD(M,
DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP),
'1990-01-31T23:59:59.997')
If you know in advance which fields to use to make the comparison, then other people gave right answers.
What you may be interested in is to sort your collection in case you don't know at compile-time which criteria to apply.
Imagine you have a program dealing with cities:
protected Set<City> cities;
(...)
Field temperatureField = City.class.getDeclaredField("temperature");
Field numberOfInhabitantsField = City.class.getDeclaredField("numberOfInhabitants");
Field rainfallField = City.class.getDeclaredField("rainfall");
program.showCitiesSortBy(temperatureField, numberOfInhabitantsField, rainfallField);
(...)
public void showCitiesSortBy(Field... fields) {
List<City> sortedCities = new ArrayList<City>(cities);
Collections.sort(sortedCities, new City.CityMultiComparator(fields));
for (City city : sortedCities) {
System.out.println(city.toString());
}
}
where you can replace hard-coded field names by field names deduced from a user request in your program.
In this example, City.CityMultiComparator<City>
is a static nested class of class City
implementing Comparator
:
public static class CityMultiComparator implements Comparator<City> {
protected List<Field> fields;
public CityMultiComparator(Field... orderedFields) {
fields = new ArrayList<Field>();
for (Field field : orderedFields) {
fields.add(field);
}
}
@Override
public int compare(City cityA, City cityB) {
Integer score = 0;
Boolean continueComparison = true;
Iterator itFields = fields.iterator();
while (itFields.hasNext() && continueComparison) {
Field field = itFields.next();
Integer currentScore = 0;
if (field.getName().equalsIgnoreCase("temperature")) {
currentScore = cityA.getTemperature().compareTo(cityB.getTemperature());
} else if (field.getName().equalsIgnoreCase("numberOfInhabitants")) {
currentScore = cityA.getNumberOfInhabitants().compareTo(cityB.getNumberOfInhabitants());
} else if (field.getName().equalsIgnoreCase("rainfall")) {
currentScore = cityA.getRainfall().compareTo(cityB.getRainfall());
}
if (currentScore != 0) {
continueComparison = false;
}
score = currentScore;
}
return score;
}
}
You may want to add an extra layer of precision, to specify, for each field, whether sorting should be ascendant or descendant. I guess a solution is to replace Field
objects by objects of a class you could call SortedField
, containing a Field
object, plus another field meaning ascendant or descendant.
1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.
value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion. http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html
Size of Tiny Int = 1 Byte ( -128 to 127)
Int = 4 Bytes (-2147483648 to 2147483647)
Here is how to use this in your program:
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
Arrays.sort(array);
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}