Lazy man can use this lib, Just import inside your project and
ImageView mImageView;
PhotoViewAttacher mAttacher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Any implementation of ImageView can be used!
mImageView = (ImageView) findViewById(R.id.iv_photo);
// Set the Drawable displayed
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
mImageView.setImageDrawable(bitmap);
// Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
mAttacher = new PhotoViewAttacher(mImageView);
}
// If you later call mImageView.setImageDrawable/setImageBitmap/setImageResource/etc then you just need to call
mAttacher.update();
I implemented a pinch zoom for my TextView
, using this tutorial. The resulting code is this:
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;
and in onCreate():
// Zoom handlers
gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
// We can be in one of these 2 states
static final int NONE = 0;
static final int ZOOM = 1;
int mode = NONE;
static final int MIN_FONT_SIZE = 10;
static final int MAX_FONT_SIZE = 50;
float oldDist = 1f;
@Override
public boolean onTouch(View v, MotionEvent event) {
TextView textView = (TextView) findViewById(R.id.text);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
mode = ZOOM;
Log.d(TAG, "mode=ZOOM" );
}
break;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if (mode == ZOOM) {
float newDist = spacing(event);
// If you want to tweak font scaling, this is the place to go.
if (newDist > 10f) {
float scale = newDist / oldDist;
if (scale > 1) {
scale = 1.1f;
} else if (scale < 1) {
scale = 0.95f;
}
float currentSize = textView.getTextSize() * scale;
if ((currentSize < MAX_FONT_SIZE && currentSize > MIN_FONT_SIZE)
||(currentSize >= MAX_FONT_SIZE && scale < 1)
|| (currentSize <= MIN_FONT_SIZE && scale > 1)) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, currentSize);
}
}
}
break;
}
return false;
}
Magic constants 1.1 and 0.95 were chosen empirically (using scale
variable for this purpose made my TextView
behave kind of weird).
If your website is properly designed for a mobile device you could decide not allow scaling.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
This solves the problem that your mobile page or form is going to 'float' around.
You can try using the LayoutParams for this
public void zoom(boolean flag){
if(flag){
int width=40;
int height=40;
}
else{
int width=20;
int height=20;
}
RelativeLayout.LayoutParams param=new RelativeLayout.LayoutParams(width,height); //use the parent layout of the ImageView;
imageView.setLayoutParams(param); //imageView is the view which needs zooming.
}
ZoomIn = zoom(true); ZoomOut = zoom(false);
The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:
User Pinch Zooms and controls appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP
User Pinch Zoom and Controls don't appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP
Can you shed more light on your solution?
For me this works to counter the difference between zoom and scale transform, adjust for the intended origin desired:
zoom: 0.5;
-ms-zoom: 0.5;
-webkit-zoom: 0.5;
-moz-transform: scale(0.5,0.5);
-moz-transform-origin: left center;
On Chrome
var ratio = (screen.availWidth / document.documentElement.clientWidth);
var zoomLevel = Number(ratio.toFixed(1).replace(".", "") + "0");
CSS to disable double-tap zoom globally (on any element):
* {
touch-action: manipulation;
}
manipulation
Enable panning and pinch zoom gestures, but disable additional non-standard gestures such as double-tap to zoom.
Thanks Ross, my answer extends his: https://stackoverflow.com/a/53236027/9986657
Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.
var currFFZoom = 1;
var currIEZoom = 100;
$('#plusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom += step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom += step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
$('#minusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom -= step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom -= step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
Good news everyone some people! Newer browsers will trigger a window resize event when the zoom is changed.
One addition to the superb solution provided by @Wieslaw Šoltés answer above
The existing code resets the image position using right click, but I am more accustomed to doing that with a double click. Just replace the existing child_MouseLeftButtonDown handler:
private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (child != null)
{
var tt = GetTranslateTransform(child);
start = e.GetPosition(this);
origin = new Point(tt.X, tt.Y);
this.Cursor = Cursors.Hand;
child.CaptureMouse();
}
}
With this:
private void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 1))
{
if (child != null)
{
var tt = GetTranslateTransform(child);
start = e.GetPosition(this);
origin = new Point(tt.X, tt.Y);
this.Cursor = Cursors.Hand;
child.CaptureMouse();
}
}
if ((e.ChangedButton == MouseButton.Left && e.ClickCount == 2))
{
this.Reset();
}
}
The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.
For your purpose, you probably want something like:
FOR %i IN (*.ext) DO my-function %i
Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).
The (*.ext)
part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:
FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i
To perform an operation in a different directory.
There are scores of options for the filespec and FOR in general. See
HELP FOR
from the command prompt for more information.
You could create a .bat-file with following content:
net stop "my service name"
net start "my service name"
Have just solved. Just two f. days of brutforce
For me the secret was in following:
I called POST /api/auth and see that cookies were successfully received.
Then calling GET /api/users/ with credentials: 'include'
and got 401 unauth, because of no cookies were sent with the request.
The KEY is to set credentials: 'include'
for the first /api/auth
call too.
Yes, this can be done with the UIWebView.
If you are trying to display a PDF file residing on a server somewhere, you can simply load it in your web view directly:
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSURL(string: "https://www.example.com/document.pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
Or if you have a PDF file bundled with your application (in this example named "document.pdf"):
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"document" withExtension:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSBundle.mainBundle().URLForResource("document", withExtension: "pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
You can find more information here: Technical QA1630: Using UIWebView to display select document types.
An easily broken way to do this is :
<?php
// Send the headers
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<xml>';
// echo some dynamically generated content here
/*
<track>
<path>song_path</path>
<title>track_number - track_title</title>
</track>
*/
echo '</xml>';
?>
save it as .php
Do you mean the mysql text console? Then:
START TRANSACTION;
...
your queries.
...
COMMIT;
Is what I recommend.
However if you want to avoid typing this each time you need to run this sort of query, add the following to the [mysqld] section of your my.cnf file.
init_connect='set autocommit=0'
This would set autocommit
to be off for every client though.
I think this might help you:
Here is the JSFiddle demo:
And here is the code:
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
init: function() {_x000D_
if (arguments.callee.done) return;_x000D_
arguments.callee.done = true;_x000D_
if (_timer) clearInterval(_timer);_x000D_
if (!document.createElement || !document.getElementsByTagName) return;_x000D_
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
forEach(document.getElementsByTagName('table'), function(table) {_x000D_
if (table.className.search(/\bsortable\b/) != -1) {_x000D_
sorttable.makeSortable(table);_x000D_
}_x000D_
});_x000D_
},_x000D_
makeSortable: function(table) {_x000D_
if (table.getElementsByTagName('thead').length == 0) {_x000D_
the = document.createElement('thead');_x000D_
the.appendChild(table.rows[0]);_x000D_
table.insertBefore(the, table.firstChild);_x000D_
}_x000D_
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
if (table.tHead.rows.length != 1) return;_x000D_
sortbottomrows = [];_x000D_
for (var i = 0; i < table.rows.length; i++) {_x000D_
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
}_x000D_
}_x000D_
if (sortbottomrows) {_x000D_
if (table.tFoot == null) {_x000D_
tfo = document.createElement('tfoot');_x000D_
table.appendChild(tfo);_x000D_
}_x000D_
for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
tfo.appendChild(sortbottomrows[i]);_x000D_
}_x000D_
delete sortbottomrows;_x000D_
}_x000D_
headrow = table.tHead.rows[0].cells;_x000D_
for (var i = 0; i < headrow.length; i++) {_x000D_
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
if (mtch) {_x000D_
override = mtch[1];_x000D_
}_x000D_
if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
} else {_x000D_
headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
}_x000D_
headrow[i].sorttable_columnindex = i;_x000D_
headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
sorttable.reverse(this.sorttable_tbody);_x000D_
this.className = this.className.replace('sorttable_sorted',_x000D_
'sorttable_sorted_reverse');_x000D_
this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
sortrevind = document.createElement('span');_x000D_
sortrevind.id = "sorttable_sortrevind";_x000D_
sortrevind.innerHTML = stIsIE ? ' <font face="webdings">5</font>' : ' ▴';_x000D_
this.appendChild(sortrevind);_x000D_
return;_x000D_
}_x000D_
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
sorttable.reverse(this.sorttable_tbody);_x000D_
this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
'sorttable_sorted');_x000D_
this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
sortfwdind = document.createElement('span');_x000D_
sortfwdind.id = "sorttable_sortfwdind";_x000D_
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';_x000D_
this.appendChild(sortfwdind);_x000D_
return;_x000D_
}_x000D_
theadrow = this.parentNode;_x000D_
forEach(theadrow.childNodes, function(cell) {_x000D_
if (cell.nodeType == 1) {_x000D_
cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
}_x000D_
});_x000D_
sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
if (sortfwdind) {_x000D_
sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
}_x000D_
sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
if (sortrevind) {_x000D_
sortrevind.parentNode.removeChild(sortrevind);_x000D_
}_x000D_
_x000D_
this.className += ' sorttable_sorted';_x000D_
sortfwdind = document.createElement('span');_x000D_
sortfwdind.id = "sorttable_sortfwdind";_x000D_
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';_x000D_
this.appendChild(sortfwdind);_x000D_
row_array = [];_x000D_
col = this.sorttable_columnindex;_x000D_
rows = this.sorttable_tbody.rows;_x000D_
for (var j = 0; j < rows.length; j++) {_x000D_
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
}_x000D_
row_array.sort(this.sorttable_sortfunction);_x000D_
tb = this.sorttable_tbody;_x000D_
for (var j = 0; j < row_array.length; j++) {_x000D_
tb.appendChild(row_array[j][1]);_x000D_
}_x000D_
delete row_array;_x000D_
});_x000D_
}_x000D_
}_x000D_
},_x000D_
_x000D_
guessType: function(table, column) {_x000D_
sortfn = sorttable.sort_alpha;_x000D_
for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
if (text != '') {_x000D_
if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
return sorttable.sort_numeric;_x000D_
}_x000D_
possdate = text.match(sorttable.DATE_RE)_x000D_
if (possdate) {_x000D_
first = parseInt(possdate[1]);_x000D_
second = parseInt(possdate[2]);_x000D_
if (first > 12) {_x000D_
return sorttable.sort_ddmm;_x000D_
} else if (second > 12) {_x000D_
return sorttable.sort_mmdd;_x000D_
} else {_x000D_
sortfn = sorttable.sort_ddmm;_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
return sortfn;_x000D_
},_x000D_
getInnerText: function(node) {_x000D_
if (!node) return "";_x000D_
hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
node.getElementsByTagName('input').length;_x000D_
if (node.getAttribute("sorttable_customkey") != null) {_x000D_
return node.getAttribute("sorttable_customkey");_x000D_
} else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
} else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
} else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
return node.text.replace(/^\s+|\s+$/g, '');_x000D_
} else {_x000D_
switch (node.nodeType) {_x000D_
case 3:_x000D_
if (node.nodeName.toLowerCase() == 'input') {_x000D_
return node.value.replace(/^\s+|\s+$/g, '');_x000D_
}_x000D_
case 4:_x000D_
return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
break;_x000D_
case 1:_x000D_
case 11:_x000D_
var innerText = '';_x000D_
for (var i = 0; i < node.childNodes.length; i++) {_x000D_
innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
}_x000D_
return innerText.replace(/^\s+|\s+$/g, '');_x000D_
break;_x000D_
default:_x000D_
return '';_x000D_
}_x000D_
}_x000D_
},_x000D_
reverse: function(tbody) {_x000D_
// reverse the rows in a tbody_x000D_
newrows = [];_x000D_
for (var i = 0; i < tbody.rows.length; i++) {_x000D_
newrows[newrows.length] = tbody.rows[i];_x000D_
}_x000D_
for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
tbody.appendChild(newrows[i]);_x000D_
}_x000D_
delete newrows;_x000D_
},_x000D_
sort_numeric: function(a, b) {_x000D_
aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
if (isNaN(aa)) aa = 0;_x000D_
bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
if (isNaN(bb)) bb = 0;_x000D_
return aa - bb;_x000D_
},_x000D_
sort_alpha: function(a, b) {_x000D_
if (a[0] == b[0]) return 0;_x000D_
if (a[0] < b[0]) return -1;_x000D_
return 1;_x000D_
},_x000D_
sort_ddmm: function(a, b) {_x000D_
mtch = a[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
m = mtch[2];_x000D_
d = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt1 = y + m + d;_x000D_
mtch = b[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
m = mtch[2];_x000D_
d = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt2 = y + m + d;_x000D_
if (dt1 == dt2) return 0;_x000D_
if (dt1 < dt2) return -1;_x000D_
return 1;_x000D_
},_x000D_
sort_mmdd: function(a, b) {_x000D_
mtch = a[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
d = mtch[2];_x000D_
m = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt1 = y + m + d;_x000D_
mtch = b[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
d = mtch[2];_x000D_
m = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt2 = y + m + d;_x000D_
if (dt1 == dt2) return 0;_x000D_
if (dt1 < dt2) return -1;_x000D_
return 1;_x000D_
},_x000D_
shaker_sort: function(list, comp_func) {_x000D_
var b = 0;_x000D_
var t = list.length - 1;_x000D_
var swap = true;_x000D_
while (swap) {_x000D_
swap = false;_x000D_
for (var i = b; i < t; ++i) {_x000D_
if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
var q = list[i];_x000D_
list[i] = list[i + 1];_x000D_
list[i + 1] = q;_x000D_
swap = true;_x000D_
}_x000D_
}_x000D_
t--;_x000D_
_x000D_
if (!swap) break;_x000D_
_x000D_
for (var i = t; i > b; --i) {_x000D_
if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
var q = list[i];_x000D_
list[i] = list[i - 1];_x000D_
list[i - 1] = q;_x000D_
swap = true;_x000D_
}_x000D_
}_x000D_
b++;_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
var script = document.getElementById("__ie_onload");_x000D_
script.onreadystatechange = function() {_x000D_
if (this.readyState == "complete") {_x000D_
sorttable.init(); // call the onload handler_x000D_
}_x000D_
};_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
var _timer = setInterval(function() {_x000D_
if (/loaded|complete/.test(document.readyState)) {_x000D_
sorttable.init(); // call the onload handler_x000D_
}_x000D_
}, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
if (element.addEventListener) {_x000D_
element.addEventListener(type, handler, false);_x000D_
} else {_x000D_
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
if (!element.events) element.events = {};_x000D_
var handlers = element.events[type];_x000D_
if (!handlers) {_x000D_
handlers = element.events[type] = {};_x000D_
if (element["on" + type]) {_x000D_
handlers[0] = element["on" + type];_x000D_
}_x000D_
}_x000D_
handlers[handler.$$guid] = handler;_x000D_
element["on" + type] = handleEvent;_x000D_
}_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
if (element.removeEventListener) {_x000D_
element.removeEventListener(type, handler, false);_x000D_
} else {_x000D_
if (element.events && element.events[type]) {_x000D_
delete element.events[type][handler.$$guid];_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
var returnValue = true;_x000D_
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
var handlers = this.events[event.type];_x000D_
for (var i in handlers) {_x000D_
this.$$handleEvent = handlers[i];_x000D_
if (this.$$handleEvent(event) === false) {_x000D_
returnValue = false;_x000D_
}_x000D_
}_x000D_
return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
event.preventDefault = fixEvent.preventDefault;_x000D_
event.stopPropagation = fixEvent.stopPropagation;_x000D_
return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
Array.forEach = function(array, block, context) {_x000D_
for (var i = 0; i < array.length; i++) {_x000D_
block.call(context, array[i], i, array);_x000D_
}_x000D_
};_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
for (var key in object) {_x000D_
if (typeof this.prototype[key] == "undefined") {_x000D_
block.call(context, object[key], key, object);_x000D_
}_x000D_
}_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
Array.forEach(string.split(""), function(chr, index) {_x000D_
block.call(context, chr, index, string);_x000D_
});_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
if (object) {_x000D_
var resolve = Object;_x000D_
if (object instanceof Function) {_x000D_
resolve = Function;_x000D_
} else if (object.forEach instanceof Function) {_x000D_
object.forEach(block, context);_x000D_
return;_x000D_
} else if (typeof object == "string") {_x000D_
resolve = String;_x000D_
} else if (typeof object.length == "number") {_x000D_
resolve = Array;_x000D_
}_x000D_
resolve.forEach(object, block, context);_x000D_
}_x000D_
}
_x000D_
table.sortable thead {_x000D_
background-color: #eee;_x000D_
color: #666666;_x000D_
font-weight: bold;_x000D_
cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>S.L.</th>_x000D_
<th>name</th>_x000D_
<th>Goal</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Ronaldo</td>_x000D_
<td>120</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Messi</td>_x000D_
<td>66</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>Ribery</td>_x000D_
<td>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>Bale</td>_x000D_
<td>22</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
JS is used here without any other JQuery Plugin.
i had the same Error , but due to different issue ,i was using a 3rd party library which cause this issue, and i did not need to have this library in my exposure ,so i used the below solution that is posted here .
Create somewhere class ApiExplorerIgnores with following content
public class ApiExplorerIgnores : IActionModelConvention
{
public void Apply(ActionModel action)
{
if (action.Controller.ControllerName.Equals("ImportExport"))
action.ApiExplorer.IsVisible = false;
}
}
Add following code to method ConfigureServices in Startup.cs
services.AddMvc(c => c.Conventions.Add(new ApiExplorerIgnores()))
this will get read of all methods in that controller ,you can also use a specific level ,like method name or so ,also you can remove one Method only and so one ,
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode
needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql
is deprecated as of PHP 5.5.0, use mysqli
extension instead http://php.net/manual/en/migration55.deprecated.php.
This can be done quite easily if you:
Use str
to convert the number into a string so that you can iterate over it.
Use a list comprehension to split the string into individual digits.
Use int
to convert the digits back into integers.
Below is a demonstration:
>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>
In my case, it was because the images I used were stored on a Mac, which generates many hidden files like .image_file.png, so they turned out to not even be the actual images I needed and I could safely ignore the warning or delete the hidden files. It was just an oversight in my case.
Check that you're not overriding window.self
My issue: I had created a component and wrote self = this
instead of var self = this
. If you don't use the keyword var
, JS will put that variable on the window object, so I overwrote window.self
which caused this error.
Just addition to above answers ..
[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring
For Ex..
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
[Route("{Latitude}/{Longitude}")]
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
Can be called like:
http://localhost/api/values/47.678558/-122.130989
According to this, cmd + / should do it.
And for Windows and Linux, it is ctrl + /.
This is another way of solving this problem.
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
What is a virtual destructor or how to use virtual destructor
A class destructor is a function with same name of the class preceding with ~ that will reallocate the memory that is allocated by the class. Why we need a virtual destructor
See the following sample with some virtual functions
The sample also tell how you can convert a letter to upper or lower
#include "stdafx.h"
#include<iostream>
using namespace std;
// program to convert the lower to upper orlower
class convertch
{
public:
//void convertch(){};
virtual char* convertChar() = 0;
~convertch(){};
};
class MakeLower :public convertch
{
public:
MakeLower(char *passLetter)
{
tolower = true;
Letter = new char[30];
strcpy(Letter, passLetter);
}
virtual ~MakeLower()
{
cout<< "called ~MakeLower()"<<"\n";
delete[] Letter;
}
char* convertChar()
{
size_t len = strlen(Letter);
for(int i= 0;i<len;i++)
Letter[i] = Letter[i] + 32;
return Letter;
}
private:
char *Letter;
bool tolower;
};
class MakeUpper : public convertch
{
public:
MakeUpper(char *passLetter)
{
Letter = new char[30];
toupper = true;
strcpy(Letter, passLetter);
}
char* convertChar()
{
size_t len = strlen(Letter);
for(int i= 0;i<len;i++)
Letter[i] = Letter[i] - 32;
return Letter;
}
virtual ~MakeUpper()
{
cout<< "called ~MakeUpper()"<<"\n";
delete Letter;
}
private:
char *Letter;
bool toupper;
};
int _tmain(int argc, _TCHAR* argv[])
{
convertch *makeupper = new MakeUpper("hai");
cout<< "Eneterd : hai = " <<makeupper->convertChar()<<" ";
delete makeupper;
convertch *makelower = new MakeLower("HAI");;
cout<<"Eneterd : HAI = " <<makelower->convertChar()<<" ";
delete makelower;
return 0;
}
From the above sample you can see that the destructor for both MakeUpper and MakeLower class is not called.
See the next sample with the virtual destructor
#include "stdafx.h"
#include<iostream>
using namespace std;
// program to convert the lower to upper orlower
class convertch
{
public:
//void convertch(){};
virtual char* convertChar() = 0;
virtual ~convertch(){}; // defined the virtual destructor
};
class MakeLower :public convertch
{
public:
MakeLower(char *passLetter)
{
tolower = true;
Letter = new char[30];
strcpy(Letter, passLetter);
}
virtual ~MakeLower()
{
cout<< "called ~MakeLower()"<<"\n";
delete[] Letter;
}
char* convertChar()
{
size_t len = strlen(Letter);
for(int i= 0;i<len;i++)
{
Letter[i] = Letter[i] + 32;
}
return Letter;
}
private:
char *Letter;
bool tolower;
};
class MakeUpper : public convertch
{
public:
MakeUpper(char *passLetter)
{
Letter = new char[30];
toupper = true;
strcpy(Letter, passLetter);
}
char* convertChar()
{
size_t len = strlen(Letter);
for(int i= 0;i<len;i++)
{
Letter[i] = Letter[i] - 32;
}
return Letter;
}
virtual ~MakeUpper()
{
cout<< "called ~MakeUpper()"<<"\n";
delete Letter;
}
private:
char *Letter;
bool toupper;
};
int _tmain(int argc, _TCHAR* argv[])
{
convertch *makeupper = new MakeUpper("hai");
cout<< "Eneterd : hai = " <<makeupper->convertChar()<<" \n";
delete makeupper;
convertch *makelower = new MakeLower("HAI");;
cout<<"Eneterd : HAI = " <<makelower->convertChar()<<"\n ";
delete makelower;
return 0;
}
The virtual destructor will call explicitly the most derived run time destructor of class so that it will be able to clear the object in a proper way.
Or visit the link
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) { }
To execute your command directly from within C#, you would use the SqlCommand class.
Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
If you want to read CSV file with some lines, so this the solution.
while IFS=, read -ra line
do
test $i -eq 1 && ((i=i+1)) && continue
for col_val in ${line[@]}
do
echo -n "$col_val|"
done
echo
done < "$csvFile"
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
Floating point numbers are represented in scientific notation as a number of only seven significant digits multiplied by a larger number that represents the place of the decimal place. More information about it on Wikipedia:
I have these extensions:
@IBDesignable class GradientView: UIView {
@IBInspectable var firstColor: UIColor = UIColor.red
@IBInspectable var secondColor: UIColor = UIColor.green
@IBInspectable var vertical: Bool = true
lazy var gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.colors = [firstColor.cgColor, secondColor.cgColor]
layer.startPoint = CGPoint.zero
return layer
}()
//MARK: -
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
applyGradient()
}
override init(frame: CGRect) {
super.init(frame: frame)
applyGradient()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
applyGradient()
}
override func layoutSubviews() {
super.layoutSubviews()
updateGradientFrame()
}
//MARK: -
func applyGradient() {
updateGradientDirection()
layer.sublayers = [gradientLayer]
}
func updateGradientFrame() {
gradientLayer.frame = bounds
}
func updateGradientDirection() {
gradientLayer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)
}
}
@IBDesignable class ThreeColorsGradientView: UIView {
@IBInspectable var firstColor: UIColor = UIColor.red
@IBInspectable var secondColor: UIColor = UIColor.green
@IBInspectable var thirdColor: UIColor = UIColor.blue
@IBInspectable var vertical: Bool = true {
didSet {
updateGradientDirection()
}
}
lazy var gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.colors = [firstColor.cgColor, secondColor.cgColor, thirdColor.cgColor]
layer.startPoint = CGPoint.zero
return layer
}()
//MARK: -
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
applyGradient()
}
override init(frame: CGRect) {
super.init(frame: frame)
applyGradient()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
applyGradient()
}
override func layoutSubviews() {
super.layoutSubviews()
updateGradientFrame()
}
//MARK: -
func applyGradient() {
updateGradientDirection()
layer.sublayers = [gradientLayer]
}
func updateGradientFrame() {
gradientLayer.frame = bounds
}
func updateGradientDirection() {
gradientLayer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)
}
}
@IBDesignable class RadialGradientView: UIView {
@IBInspectable var outsideColor: UIColor = UIColor.red
@IBInspectable var insideColor: UIColor = UIColor.green
override func awakeFromNib() {
super.awakeFromNib()
applyGradient()
}
func applyGradient() {
let colors = [insideColor.cgColor, outsideColor.cgColor] as CFArray
let endRadius = sqrt(pow(frame.width/2, 2) + pow(frame.height/2, 2))
let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)
let context = UIGraphicsGetCurrentContext()
context?.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
#if TARGET_INTERFACE_BUILDER
applyGradient()
#endif
}
}
Usage:
Using {dplyr}:
library(dplyr)
# percentiles
infert %>%
mutate(PCT = ntile(age, 100))
# quartiles
infert %>%
mutate(PCT = ntile(age, 4))
# deciles
infert %>%
mutate(PCT = ntile(age, 10))
like this:
var items = $filter('filter')(array, {Column1:false,Column2:'Pending'});
No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):
Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC
The SQL standard only defines a single operator for "not equals" and that is <>
Along the lines of @halfcube's suggestion, this works really well:
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb
here is a working version :
function countbackgrounds() {
var book = SpreadsheetApp.getActiveSpreadsheet();
var range_input = book.getRange("B3:B4");
var range_output = book.getRange("B6");
var cell_colors = range_input.getBackgroundColors();
var color = "#58FA58";
var count = 0;
for( var i in cell_colors ){
Logger.log(cell_colors[i][0])
if( cell_colors[i][0] == color ){ ++count }
}
range_output.setValue(count);
}
install wkhtmltoimage on your server then use my package packagist.org/packages/tohidhabiby/htmltoimage for generate an image from url of your target.
In researching Matt's comment, I have revised my original statement. He is correct, there will be a difference in performance between an inline table valued function (ITVF) and a multi-statement table valued function (MSTVF) even if they both simply execute a SELECT statement. SQL Server will treat an ITVF somewhat like a VIEW
in that it will calculate an execution plan using the latest statistics on the tables in question. A MSTVF is equivalent to stuffing the entire contents of your SELECT statement into a table variable and then joining to that. Thus, the compiler cannot use any table statistics on the tables in the MSTVF. So, all things being equal, (which they rarely are), the ITVF will perform better than the MSTVF. In my tests, the performance difference in completion time was negligible however from a statistics standpoint, it was noticeable.
In your case, the two functions are not functionally equivalent. The MSTV function does an extra query each time it is called and, most importantly, filters on the customer id. In a large query, the optimizer would not be able to take advantage of other types of joins as it would need to call the function for each customerId passed. However, if you re-wrote your MSTV function like so:
CREATE FUNCTION MyNS.GetLastShipped()
RETURNS @CustomerOrder TABLE
(
SaleOrderID INT NOT NULL,
CustomerID INT NOT NULL,
OrderDate DATETIME NOT NULL,
OrderQty INT NOT NULL
)
AS
BEGIN
INSERT @CustomerOrder
SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
FROM Sales.SalesOrderHeader a
INNER JOIN Sales.SalesOrderHeader b
ON a.SalesOrderID = b.SalesOrderID
INNER JOIN Production.Product c
ON b.ProductID = c.ProductID
WHERE a.OrderDate = (
Select Max(SH1.OrderDate)
FROM Sales.SalesOrderHeader As SH1
WHERE SH1.CustomerID = A.CustomerId
)
RETURN
END
GO
In a query, the optimizer would be able to call that function once and build a better execution plan but it still would not be better than an equivalent, non-parameterized ITVS or a VIEW
.
ITVFs should be preferred over a MSTVFs when feasible because the datatypes, nullability and collation from the columns in the table whereas you declare those properties in a multi-statement table valued function and, importantly, you will get better execution plans from the ITVF. In my experience, I have not found many circumstances where an ITVF was a better option than a VIEW but mileage may vary.
Thanks to Matt.
Addition
Since I saw this come up recently, here is an excellent analysis done by Wayne Sheffield comparing the performance difference between Inline Table Valued functions and Multi-Statement functions.
Here's the proper way to do things:
<?PHP
$sql = 'some query...';
$result = mysql_query($q);
if (! $result){
throw new My_Db_Exception('Database error: ' . mysql_error());
}
while($row = mysql_fetch_assoc($result)){
//handle rows.
}
Note the check on (! $result) -- if your $result is a boolean, it's certainly false, and it means there was a database error, meaning your query was probably bad.
range creates a list, so if you do
range(1, 10000000)
it creates a list in memory with9999999
elements.
xrange
is a generator, so itis a sequence objectis athat evaluates lazily.
This is true, but in Python 3, range()
will be implemented by the Python 2 xrange()
. If you need to actually generate the list, you will need to do:
list(range(1,100))
The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.
Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.
* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
I was trying the above examples and couldn't get them to sync with a (non-master) branch I had created on a different computer. For background, I created this repository on computer A (git v 1.8) and then cloned the repository onto computer B (git 2.14). I made all my changes on comp B, but when I tried to pull the changes onto computer A I was unable to do so, getting the same above error. Similar to the above solutions, I had to do:
git branch --set-upstream-to=origin/<my_repository_name>
git pull
slightly different but hopefully helps someone
And if your dates are standardized by importing datetime package, you can simply use:
df[(df['date']>datetime.date(2016,1,1)) & (df['date']<datetime.date(2016,3,1))]
For standarding your date string using datetime package, you can use this function:
import datetime
datetime.datetime.strptime
MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.
A = 1:5;
for i = A
A = B;
disp(i);
end
If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])
Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:
A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);
itr = A.listIterator();
while itr.hasNext()
k = itr.next();
disp(k);
% modify data structure while iterating
itr.remove();
itr.add(k);
end
For CSS style sheets, the base URI is that of the style sheet, not that of the source document.
(Anything else would be broken, IMNSHO)
Edit: Note that the original post has been edited since this answer was written and has been reformatted. You should look at the history to see the original formatting to understand the context for this answer.
This error occurs often when you have mismatched structure - that is, you do not have matching double quotes, matching single quotes, have not closed a control structure such as a missing fi
with an if
, or a missing done
with a for
.
The best way to spot these is to use correct indentation, which will show you where you have a broken control structure, and syntax highlighting, which will show you where quotes are not matched.
In this particular case, I can see you are missing a fi
. In the latter part of your code, you have 5 if
s and 4 fi
s. However you also have a number of other problems - your backquoted touch /tmp/alert.txt...
command is syntactically invalid, and you need a space before the closing bracket of an if
test.
Clean up your code, and errors start to stand out.
<html>
<head>
<title>Cars</title>
</head>
<body >
<h1>Cars</h1>
<p>Name </p>
<select id="selectBox" onchange="myFunction(value);">
<option value="volvo" >Volvo</option>
<option value="saab" >Saab</option>
<option value="mercedes">Mercedes</option>
</select>
<p id="result"> Price : </p>
<script>
function myFunction($value)
{
if($value=="volvo")
{document.getElementById("result").innerHTML = "30L";}
else if($value=="saab")
{document.getElementById("result").innerHTML = "40L";}
else if($value=="mercedes")
{document.getElementById("result").innerHTML = "50L";}
}
</script>
</body>
</html>```
If you want to use @Column(...), then use small-case letters always even though your actual DB column is in camel-case.
Example: If your actual DB column name is TestName
then use:
@Column(name="testname") //all small-case
If you don't like that, then simply change the actual DB column name into: test_name
a list of what ?
Assuming map
is your instance of Map
map.values()
will return a Collection
containing all of the map's values.map.keySet()
will return a Set
containing all of the map's keys.The only thing you have to do is to install requests[security]
in your virtualenv. You should not have to use Python 3 (it should work in Python 2.7). Moreover, if you are using a recent version of macOS, you don't have to use homebrew
to separately install OpenSSL either.
$ virtualenv --python=/usr/bin/python tempenv # uses system python
$ . tempenv/bin/activate
$ pip install requests
$ python
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 0.9.8zh 14 Jan 2016' # this is the built-in openssl
>>> import requests
>>> requests.get('https://api.github.com/users/octocat/orgs')
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: /users/octocat/orgs (Caused by SSLError(SSLError(1, u'[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)'),))
$ pip install 'requests[security]'
$ python # install requests[security] and try again
>>> import requests
>>> requests.get('https://api.github.com/users/octocat/orgs')
<Response [200]>
requests[security]
allows requests to use the latest version of TLS when negotiating the connection. The built-in openssl on macOS supports TLS v1.2.
Before you install your own version of OpenSSL, ask this question: how is Google Chrome loading https://github.com?
The offset under Windows 10 is 0x022C (x64-bit-Application) and 0x0160 (x32-bit-Application):
public static int GetNativeThreadId(Thread thread)
{
var f = typeof(Thread).GetField("DONT_USE_InternalThread",
BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
var pInternalThread = (IntPtr)f.GetValue(thread);
var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 0x022C : 0x0160); // found by analyzing the memory
return nativeId;
}
in c#.net
this.WindowState = FormWindowState.Minimized
var stringToSplit = "0, 10, 20, 30, 100, 200";
// To parse your string
var elements = test.Split(new[]
{ ',' }, System.StringSplitOptions.RemoveEmptyEntries);
// To Loop through
foreach (string items in elements)
{
// enjoy
}
In c/c++ land, when not using stl containers, I tend to use quicksort, because it is built into the run time, while mergesort is not.
So I believe that in many cases, it is simply the path of least resistance.
In addition performance can be much higher with quick sort, for cases where the entire dataset does not fit into the working set.
In the version 5.x, you can use useHistory
hook of react-router-dom
:
// Sample extracted from https://reacttraining.com/react-router/core/api/Hooks/usehistory
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x
will be true otherwise it will be false.
Definitely avoid using eval
to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.
For example, if you were to use the eval
solutions proposed here, a nefarious user could send a link to their victim that looked like this:
http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}
And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.
So, make sure you never eval
untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:
// set up the possible functions:
var myFuncs = {
func1: function () { alert('Function 1'); },
func2: function () { alert('Function 2'); },
func3: function () { alert('Function 3'); },
func4: function () { alert('Function 4'); },
func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();
This will fail if the funcToRun
variable doesn't point to anything in the myFuncs
object, but it won't execute any code.
I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.
In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.
In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile
or /etc/.bashrc
but otherwise, they're not permanent. They're stored in RAM.
There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.
You can view shell variables with the set
command (though note that unlike windows, variables are not set in linux with the set command).
set -o posix; set
(doing that set -o posix once first, helps not display too much unnecessary stuff). So set
displays shell variables.
You can view environment variables with the env
command
shell variables are set with e.g. just a = 5
environment variables are set with export, export also sets the shell variable
Here you see shell variable zzz set with zzz = 5, and see it shows when running set
but doesn't show as an environment variable.
Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables
$ zzz=5
$ set | grep zzz
zzz=5
$ env | grep zzz
$ export yyy=5
$ set | grep yyy
yyy=5
$ env | grep yyy
yyy=5
$
other useful threads
https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables
https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf
then it sets $1 to asdf, and if you do echo $1
you see asdf. If you do set a=5
it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose
, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose
to turn verbose off. Windows has no such usage for its set command.
If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.
For this example however I don't think you need the first s:
DELETE s
FROM spawnlist AS s
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate
WHERE n.type = "monster";
It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:
SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";
You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html
IF OBJECT_ID('master..test') is not null Drop table test
CREATE TABLE test (ID INTEGER, NAME VARCHAR (50), VALUE INTEGER );
INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);
select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = _a.name for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc
My table name is test , and for concatination I use the For XML Path('') syntax. The stuff function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )
character_expression Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
start Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.
length Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.
I has able to choose a simplier solution > Add a new Headers to the defaults options merge or load by your api get (or other) function.
get(endpoint: string, params?: any, options?: RequestOptions) {
if (!options) {
options = new RequestOptions();
options.headers = new Headers( { "Accept": "application/json" } ); <<<<
}
// [...]
}
Of course you can externalize this Headers in default options or whatever in your class. This is in the Ionic generated api.ts @Injectable() export class API {}
It is very quick and it work for me. I didn't want json/ld format.
It is because Gerrit is configured to require Change-Id in the commit messages.
http://gerrit.googlecode.com/svn-history/r6114/documentation/2.1.7/error-missing-changeid.html
You have to change the messages of every commit that you are pushing to include the change id ( using git filter-branch
) and only then push.
Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.
It happens when you use some emulator like androVM which is not installed google map by default.
Not the answer for this question but this question helped me to find the answer for my problem.
I had this problem when using inside a Docker container.
I solved by installing locales, adding my language to the locale.gen file, executing locale-gen (it reads from locale.gen) and finally setting LANG to my language.
For example, my Dockerfile:
RUN apt-get install -y locales
RUN echo "pt_BR.UTF-8 UTF-8" >> /etc/locale.gen
RUN locale-gen pt_BR.UTF-8
ENV LANG=pt_BR.UTF-8
@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.
In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.
- Florina Muntenescu (source)
build.gradle
android {
// [...]
defaultConfig {
// [...]
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
// add the schema location to the source sets
// used by Room, to test migrations
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
// [...]
}
I discovered that if I have an image and some text inside a div
, then I can use text-align:center
to align the text and the image in one swoop.
HTML:
<div class="picture-group">
<h2 class="picture-title">Picture #1</h2>
<img src="http://lorempixel.com/99/100/" alt="" class="picture-img" />
<p class="picture-caption">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus sapiente fuga, quia?</p>
</div>
CSS:
.picture-group {
border: 1px solid black;
width: 25%;
float: left;
height: 300px;
#overflow:scroll;
padding: 5px;
text-align:center;
}
CodePen: https://codepen.io/artforlife/pen/MoBzrL?editors=1100
it is just as simple as
if([object length] >0)
{
// do something
}
remember that in objective C if object is null it returns 0 as the value.
This will get you both a null string and a 0 length string.
Open the Android SDK Manager
and Update with latest :
Then Sync ,Re-Build and Restart Your Project
Demo Code for build.gradle
compileSdkVersion 21 // Now 23
buildToolsVersion '21.1.2' //Now 23.0.1
defaultConfig
{
minSdkVersion 15
targetSdkVersion 19
}
Hope this helps .
If you are looking to do an exact match, use the following syntax:
(param)?
.
Eg.
<Route path={`my/(exact)?/path`} component={MyComponent} />
The nice thing about this is that you'll have props.match
to play with, and you don't need to worry about checking the value of the optional parameter:
{ props: { match: { "0": "exact" } } }
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, 1, "test");
$sheet->mergeCells('A1:B1');
$sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");
?>
Here are the two functions I use. They are based on matrix rotations. and can rotate around arbitrary axes. To rotate using the world's axes you would want to use the second function rotateAroundWorldAxis().
// Rotate an object around an arbitrary axis in object space
var rotObjectMatrix;
function rotateAroundObjectAxis(object, axis, radians) {
rotObjectMatrix = new THREE.Matrix4();
rotObjectMatrix.makeRotationAxis(axis.normalize(), radians);
// old code for Three.JS pre r54:
// object.matrix.multiplySelf(rotObjectMatrix); // post-multiply
// new code for Three.JS r55+:
object.matrix.multiply(rotObjectMatrix);
// old code for Three.js pre r49:
// object.rotation.getRotationFromMatrix(object.matrix, object.scale);
// old code for Three.js r50-r58:
// object.rotation.setEulerFromRotationMatrix(object.matrix);
// new code for Three.js r59+:
object.rotation.setFromRotationMatrix(object.matrix);
}
var rotWorldMatrix;
// Rotate an object around an arbitrary axis in world space
function rotateAroundWorldAxis(object, axis, radians) {
rotWorldMatrix = new THREE.Matrix4();
rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
// old code for Three.JS pre r54:
// rotWorldMatrix.multiply(object.matrix);
// new code for Three.JS r55+:
rotWorldMatrix.multiply(object.matrix); // pre-multiply
object.matrix = rotWorldMatrix;
// old code for Three.js pre r49:
// object.rotation.getRotationFromMatrix(object.matrix, object.scale);
// old code for Three.js pre r59:
// object.rotation.setEulerFromRotationMatrix(object.matrix);
// code for r59+:
object.rotation.setFromRotationMatrix(object.matrix);
}
So you should call these functions within your anim
function (requestAnimFrame callback), resulting in a rotation of 90 degrees on the x-axis:
var xAxis = new THREE.Vector3(1,0,0);
rotateAroundWorldAxis(mesh, xAxis, Math.PI / 180);
I found a way to change the Application Output theme and everything that can't be edited from .css
.
If you use osX:
You need to destroy:
myLineChart.destroy();
Then re-initialize the chart:
var ctx = document.getElementById("myChartLine").getContext("2d");
myLineChart = new Chart(ctx).Line(data, options);
Google services have a polyglot persistence architecture. BigTable is leveraged by most of its services like YouTube, Google Search, Google Analytics etc. The search service initially used MapReduce for its indexing infrastructure but later transitioned to BigTable during the Caffeine release.
Google Cloud datastore has over 100 applications in production at Google both facing internal and external users. Applications like Gmail, Picasa, Google Calendar, Android Market & AppEngine use Cloud Datastore & Megastore.
Google Trends use MillWheel for stream processing. Google Ads initially used MySQL later migrated to F1 DB - a custom written distributed relational database. Youtube uses MySQL with Vitess. Google stores exabytes of data across the commodity servers with the help of the Google File System.
Source: Google Databases: How Do Google Services Store Petabyte-Exabyte Scale Data?
YouTube Database – How Does It Store So Many Videos Without Running Out Of Storage Space?
I simply delete all error in the buttom: problem list. then close project and reopen project clean project build all run
then those stupids errors go.
In Acrobat XI, (Close Form Editing if open) File > Save As Other > Reader Extended PDF > Enable Additional Features
I think a lot of people concentrate on the fact that this value is nullable, and don't think about what they actually want :)
bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else { ... } // false or null
Or if you want more options...
bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else if (nullableBool == false) { ... } // false
else { ... } // null
(nullableBool == true)
will never return true if the bool? is null :P
This also works for me
>>> val_int = int(a)
>>> val_fract = a - val_int
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
This answer is not the direct answer for the question. But it should help you figure out which solution fits best for your problem.
When analysing the problem you should activate the debug option -vv
Then rsync will output which files are included or excluded by which pattern:
building file list ...
[sender] hiding file FILE1 because of pattern FILE1*
[sender] showing file FILE2 because of pattern *
rand() / double(RAND_MAX)
generates a floating-point random number between 0 (inclusive) and 1 (inclusive), but it's not a good way for the following reasons (because RAND_MAX is usually 32767):
Due to the above limitations of rand(), a better choice for generation of random numbers between 0 (inclusive) and 1 (exclusive) would be the following snippet (similar to the example at http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):
#include <iostream>
#include <random>
#include <chrono>
int main()
{
std::mt19937_64 rng;
// initialize the random number generator with time-dependent seed
uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::seed_seq ss{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
rng.seed(ss);
// initialize a uniform distribution between 0 and 1
std::uniform_real_distribution<double> unif(0, 1);
// ready to generate random numbers
const int nSimulations = 10;
for (int i = 0; i < nSimulations; i++)
{
double currentRandomNumber = unif(rng);
std::cout << currentRandomNumber << std::endl;
}
return 0;
}
This is easy to modify to generate random numbers between 1 (inclusive) and 2 (exclusive) by replacing unif(0, 1)
with unif(1, 2)
.
For a true logical XOR operation, this will work:
if(!A != !B) {
// code here
}
Note the !
are there to convert the values to booleans and negate them, so that two unequal positive integers (each a true
) would evaluate to false
.
Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).
Apple provides detailed, illustrated instructions covering every step of the process. Log in to the iPhone developer site and click the "program portal" link. In the program portal you'll find a link to the program portal user's guide, which is a really good reference and guide on this topic.
In Access 2013. Drop a "Text Box" control onto your form. On the Property Sheet for the control under the Format tab find the Format property. Set this to one of the date format options. Job's done.
(Ctrl+H) -> Find and Replace window opens -> Find what "0" ,Replace with " "(leave it blank )-> click options tick match entire cell contents -> click "Replace All" button .
I also had to add white-space: nowrap;
to the style, otherwise elements would wrap down into the area that we're removing the ability to scroll to.
You can use JavaScript like... Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
You want to use a Set
or List
implementation (e.g. HashSet
, TreeSet
, etc, or ArrayList
, LinkedList
, etc..), since Java does not have dynamically sized arrays.
List<String> zoom = new ArrayList<>();
zoom.add("String 1");
zoom.add("String 2");
for (String z : zoom) {
System.err.println(z);
}
Edit: Here is a more succinct way to initialize your List with an arbitrary number of values using varargs:
List<String> zoom = Arrays.asList("String 1", "String 2", "String n");
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
From getDefault
's documentation:
Returns the user's preferred locale. This may have been overridden for this process with setDefault(Locale).
Also from the Locale
docs:
The default locale is appropriate for tasks that involve presenting data to the user.
Seems like you should just use it.
Python Implementation:
import itertools
list = [1, 1, 2, 3, 4, 5,]
uniquelist = set(list)
targetsum = 5
for n in itertools.combinations(uniquelist, 2):
if n[0] + n[1] == targetsum:
print str(n[0]) + " + " + str(n[1])
Output:
1 + 4
2 + 3
Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv
I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:
Get-Module -ListAvailable | Import-Module
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
I had the very same error message. Finally I figured out I misspelled the name of the table in the command:
ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES country (id);
versus
ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES countries (id);
I wonder why on earth MySQL cannot tell such a table does not exist...
If the external configuration file is also valid batch file, you can just use:
call externalconfig.bat
inside your script. Try creating following a.bat:
@echo off
call b.bat
echo %MYVAR%
and b.bat:
set MYVAR=test
Running a.bat should generate output:
test
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
Just one more alternative using URL
var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string
Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.
The static
block is a "static initializer".
It's automatically invoked when the class is loaded, and there's no other way to invoke it (not even via Reflection).
I've personally only ever used it when writing JNI code:
class JNIGlue {
static {
System.loadLibrary("foo");
}
}
There are many articles about writing code to import an excel file, but this is a manual/shortcut version:
If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.
The quickest way to get your Excel file into SQL is by using the import wizard:
The next window is 'Choose a Data Source', select Excel:
In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).
Click the 'Browse' button to select the path to the Excel file you want to import.
On the 'Specify Table Copy or Query' window:
'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.
As in TDD & BDD you/ team focus the most on test and behavior of the system than code implementation.
Similar way when system analyst, product owner, development team and ofcourse the code - entities/ classes, variables, functions, user interfaces processes communicate using the same language, its called Domain Driven Design
DDD is a thought process. When modeling a design of software you need to keep business domain/process in the center of attention rather than data structures, data flows, technology, internal and external dependencies.
There are many approaches to model systerm using DDD
In very naive words, an object which
Also, eclipse offers the possibility to sort class members for you, if you for some reason mixed them up:
Open your class file, the go to "Source" in the main menu and select "Sort Members".
taken from here: Sorting methods in Eclipse
For SQL Server 2017
Download and run the installer, you are given 3 options:
Download Media <- pick this one!
Extract ISO using your preferred archive utility or mount
If you just want to pass some data from one screen to the next, you can pass them with the navigation.navigate
method like this:
<Button onPress={()=> {this.props.navigation.navigate('NextScreen',{foo:bar)} />
and in 'NextScreen' you can access them with the navigation.getParam()
method:
let foo=this.props.navigation.getParam(foo);
But it can get really "messy" if you have more than a couple of variables to pass..
You can try this:
"ab c d efg hi ".split.map(&:strip)
in order to get this:
["ab, "c", "d", "efg", "hi"]
or if you want a single string, just use:
"ab c d efg hi ".split.join
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
Reset all sequences, no assumptions about names except that the primary key of each table is "id":
CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text)
RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
EXECUTE 'SELECT setval( pg_get_serial_sequence(''' || tablename || ''', ''' || columnname || '''),
(SELECT COALESCE(MAX(id)+1,1) FROM ' || tablename || '), false)';
END;
$body$ LANGUAGE 'plpgsql';
select table_name || '_' || column_name || '_seq', reset_sequence(table_name, column_name) from information_schema.columns where column_default like 'nextval%';
You might want to use
return_value = os.popen('ls').read()
instead. os.system
only returns the error value.
The os.popen
is a neater wrapper for subprocess.Popen
function as is seen within the python source code.
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
You can use this function :
function SendByFTP {
param (
$userFTP = "anonymous",
$passFTP = "anonymous",
[Parameter(Mandatory=$True)]$serverFTP,
[Parameter(Mandatory=$True)]$localFile,
[Parameter(Mandatory=$True)]$remotePath
)
if(Test-Path $localFile){
$remoteFile = $localFile.Split("\")[-1]
$remotePath = Join-Path -Path $remotePath -ChildPath $remoteFile
$ftpAddr = "ftp://${userFTP}:${passFTP}@${serverFTP}/$remotePath"
$browser = New-Object System.Net.WebClient
$url = New-Object System.Uri($ftpAddr)
$browser.UploadFile($url, $localFile)
}
else{
Return "Unable to find $localFile"
}
}
This function send specified file by FTP. You must call the function with these parameters :
For example :
SendByFTP -userFTP "USERNAME" -passFTP "PASSWORD" -serverFTP "MYSERVER" -localFile "toto.zip" -remotePath "path/on/the/FTP/"
I think to force StringLenght to 191 is a really bad idea. So I investigate to understand what is going on.
I noticed that this message error :
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
Started to show up after I updated my MySQL version. So I've checked the tables with PHPMyAdmin and I've noticed that all the new tables created were with the collation utf8mb4_unicode_ci instead of utf8_unicode_ci for the old ones.
In my doctrine config file, I noticed that charset was set to utf8mb4, but all my previous tables were created in utf8, so I guess this is some update magic that it start to work on utf8mb4.
Now the easy fix is to change the line charset in your ORM config file. Then to drop the tables using utf8mb4_unicode_ci if you are in dev mode or fixe the charset if you can't drop them.
For Symfony 4
change charset: utf8mb4 to charset: utf8 in config/packages/doctrine.yaml
Now my doctrine migrations are working again just fine.
This works in May 2020 using PDFminer six in Python3.
$ pip install pdfminer.six
from pdfminer.high_level import extract_text
text = extract_text('report.pdf')
Or alternatively:
with open('report.pdf','rb') as f:
text = extract_text(f)
If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io
library:
import io
response = requests.get(url)
text = extract_text(io.BytesIO(response.content))
PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7
However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.
I timed text extraction with timeit
on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:
PDFminer.six: 2.88 sec
PyPDF2: 0.45 sec
pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.
With reference to Cori's answer, I modified it and used below command, which is working. Without exit
, remaining command was actually logging to remote machine, which I didn't want in script
ssh -o StrictHostKeyChecking=no user@ip_of_remote_machine "exit"
Run below command into the current branch folder to merge from this <commit-id>
to current branch, --no-commit
do not make a new commit automatically
git merge --no-commit <commit-id>
git merge --continue
can only be run after the merge has resulted in conflicts.
git merge --abort
Abort the current conflict resolution process, and try to reconstruct the pre-merge state.
Before using the $result
variable, you should use $row = mysqli_fetch_array($result)
or mysqli_fetch_assoc()
functions.
Like this:
$row = mysqli_fetch_array($result);
and use the $row
array as you need.
Another case of android witchcraft, if nothing else works, try increasing your versionCode and versionName by 1 in the manifest.
It worked for me.
It can be done like this
int totalMinutesInt = Integer.valueOf(totalMinutes.toString());
int hours = totalMinutesInt / 60;
int hoursToDisplay = hours;
if (hours > 12) {
hoursToDisplay = hoursToDisplay - 12;
}
int minutesToDisplay = totalMinutesInt - (hours * 60);
String minToDisplay = null;
if(minutesToDisplay == 0 ) minToDisplay = "00";
else if( minutesToDisplay < 10 ) minToDisplay = "0" + minutesToDisplay ;
else minToDisplay = "" + minutesToDisplay ;
String displayValue = hoursToDisplay + ":" + minToDisplay;
if (hours < 12)
displayValue = displayValue + " AM";
else
displayValue = displayValue + " PM";
return displayValue;
} catch (Exception e) {
LOGGER.error("Error while converting currency.");
}
return totalMinutes.toString();
A column with default value:
CREATE TABLE <TableName>(
...
<ColumnName> <Type> DEFAULT <DefaultValue>
...
)
<DefaultValue>
is a placeholder for a:
(
expression )
Examples:
Count INTEGER DEFAULT 0,
LastSeen TEXT DEFAULT (datetime('now'))
You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm
My own standard loop looks something like this:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
'Perform an edit
rs.Edit
rs!VendorYN = True
rs("VendorYN") = True 'The other way to refer to a field
rs.Update
'Save contact name into a variable
sContactName = rs!FirstName & " " & rs!LastName
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Finished looping through records."
rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
I think not. But styling body
with overflow: scroll
should do. You seem to know that, though.
There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.
Here is an example using Posh-SSH:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Some additional notes:
That should give you a decent starting point.
str.matches(regex)
behaves like Pattern.matches(regex, str)
which attempts to match the entire input sequence against the pattern and returns
true
if, and only if, the entire input sequence matches this matcher's pattern
Whereas matcher.find()
attempts to find the next subsequence of the input sequence that matches the pattern and returns
true
if, and only if, a subsequence of the input sequence matches this matcher's pattern
Thus the problem is with the regex. Try the following.
String test = "User Comments: This is \t a\ta \ntest\n\n message \n";
String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find()); //true
String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2)); //true
Thus in short, the (\\W)*(\\S)*
portion in your first regex matches an empty string as *
means zero or more occurrences and the real matched string is User Comments:
and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W
matches a non word character, ie [^a-zA-Z0-9_]
and the first character is T
, a word character.
Reboot the phone.
Seriously! Completely power down and power up. That fixed it for me.
Here's a simple, working example:
package main
import (
"io"
"net/http"
)
func queryParamDisplayHandler(res http.ResponseWriter, req *http.Request) {
io.WriteString(res, "name: "+req.FormValue("name"))
io.WriteString(res, "\nphone: "+req.FormValue("phone"))
}
func main() {
http.HandleFunc("/example", func(res http.ResponseWriter, req *http.Request) {
queryParamDisplayHandler(res, req)
})
println("Enter this in your browser: http://localhost:8080/example?name=jenny&phone=867-5309")
http.ListenAndServe(":8080", nil)
}
For me it was a windows firewall issue. Allow incoming connections. Opening port didn't work but allow programs did.
The information on this answer is out of date. You need to go to Configure Jenkins > And you can then click to add an Environment Variable key-value pair from there.
eg: export MYVAR=test
would be MYVAR
is the key, and test
is the value.
There is also a function in pandas
called factorize
which you can use to automatically do this type of work. It converts labels to numbers: ['male', 'female', 'male'] -> [0, 1, 0]
. See this answer for more information.
<a [ngClass]="{'class1':array.status === 'active','class2':array.status === 'idle','class3':array.status === 'inactive',}">
In a query you can just do something like:
SELECT ColumnA * ColumnB FROM table
or
SELECT ColumnA - ColumnB FROM table
You can also create computed columns in your table where you can permanently use your formula.
Just to clarify, be aware bracket placement is important!
These can be added to any HTML tags... span, div, table, p, tr, td etc.
AngularJS
ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
Angular2+
*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.
boolean check1 = Your conditional check here...
...
This is an answer to question 8391979, "Does java have a int.tryparse that doesn't throw an exception for bad data? [duplicate]" which is closed and linked to this question.
Edit 2016 08 17: Added ltrimZeroes methods and called them in tryParse(). Without leading zeroes in numberString may give false results (see comments in code). There is now also public static String ltrimZeroes(String numberString) method which works for positive and negative "numbers"(END Edit)
Below you find a rudimentary Wrapper (boxing) class for int with an highly speed optimized tryParse() method (similar as in C#) which parses the string itself and is a little bit faster than Integer.parseInt(String s) from Java:
public class IntBoxSimple {
// IntBoxSimple - Rudimentary class to implement a C#-like tryParse() method for int
// A full blown IntBox class implementation can be found in my Github project
// Copyright (c) 2016, Peter Sulzer, Fürth
// Program is published under the GNU General Public License (GPL) Version 1 or newer
protected int _n; // this "boxes" the int value
// BEGIN The following statements are only executed at the
// first instantiation of an IntBox (i. e. only once) or
// already compiled into the code at compile time:
public static final int MAX_INT_LEN =
String.valueOf(Integer.MAX_VALUE).length();
public static final int MIN_INT_LEN =
String.valueOf(Integer.MIN_VALUE).length();
public static final int MAX_INT_LASTDEC =
Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(1));
public static final int MAX_INT_FIRSTDIGIT =
Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(0, 1));
public static final int MIN_INT_LASTDEC =
-Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(2));
public static final int MIN_INT_FIRSTDIGIT =
Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(1,2));
// END The following statements...
// ltrimZeroes() methods added 2016 08 16 (are required by tryParse() methods)
public static String ltrimZeroes(String s) {
if (s.charAt(0) == '-')
return ltrimZeroesNegative(s);
else
return ltrimZeroesPositive(s);
}
protected static String ltrimZeroesNegative(String s) {
int i=1;
for ( ; s.charAt(i) == '0'; i++);
return ("-"+s.substring(i));
}
protected static String ltrimZeroesPositive(String s) {
int i=0;
for ( ; s.charAt(i) == '0'; i++);
return (s.substring(i));
}
public static boolean tryParse(String s,IntBoxSimple intBox) {
if (intBox == null)
// intBoxSimple=new IntBoxSimple(); // This doesn't work, as
// intBoxSimple itself is passed by value and cannot changed
// for the caller. I. e. "out"-arguments of C# cannot be simulated in Java.
return false; // so we simply return false
s=s.trim(); // leading and trailing whitespace is allowed for String s
int len=s.length();
int rslt=0, d, dfirst=0, i, j;
char c=s.charAt(0);
if (c == '-') {
if (len > MIN_INT_LEN) { // corrected (added) 2016 08 17
s = ltrimZeroesNegative(s);
len = s.length();
}
if (len >= MIN_INT_LEN) {
c = s.charAt(1);
if (!Character.isDigit(c))
return false;
dfirst = c-'0';
if (len > MIN_INT_LEN || dfirst > MIN_INT_FIRSTDIGIT)
return false;
}
for (i = len - 1, j = 1; i >= 2; --i, j *= 10) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt -= (c-'0')*j;
}
if (len < MIN_INT_LEN) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt -= (c-'0')*j;
} else {
if (dfirst >= MIN_INT_FIRSTDIGIT && rslt < MIN_INT_LASTDEC)
return false;
rslt -= dfirst * j;
}
} else {
if (len > MAX_INT_LEN) { // corrected (added) 2016 08 16
s = ltrimZeroesPositive(s);
len=s.length();
}
if (len >= MAX_INT_LEN) {
c = s.charAt(0);
if (!Character.isDigit(c))
return false;
dfirst = c-'0';
if (len > MAX_INT_LEN || dfirst > MAX_INT_FIRSTDIGIT)
return false;
}
for (i = len - 1, j = 1; i >= 1; --i, j *= 10) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt += (c-'0')*j;
}
if (len < MAX_INT_LEN) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt += (c-'0')*j;
}
if (dfirst >= MAX_INT_FIRSTDIGIT && rslt > MAX_INT_LASTDEC)
return false;
rslt += dfirst*j;
}
intBox._n=rslt;
return true;
}
// Get the value stored in an IntBoxSimple:
public int get_n() {
return _n;
}
public int v() { // alternative shorter version, v for "value"
return _n;
}
// Make objects of IntBoxSimple (needed as constructors are not public):
public static IntBoxSimple makeIntBoxSimple() {
return new IntBoxSimple();
}
public static IntBoxSimple makeIntBoxSimple(int integerNumber) {
return new IntBoxSimple(integerNumber);
}
// constructors are not public(!=:
protected IntBoxSimple() {} {
_n=0; // default value an IntBoxSimple holds
}
protected IntBoxSimple(int integerNumber) {
_n=integerNumber;
}
}
Test/example program for class IntBoxSimple:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IntBoxSimpleTest {
public static void main (String args[]) {
IntBoxSimple ibs = IntBoxSimple.makeIntBoxSimple();
String in = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.printf(
"Enter an integer number in the range %d to %d:%n",
Integer.MIN_VALUE, Integer.MAX_VALUE);
try { in = br.readLine(); } catch (IOException ex) {}
} while(! IntBoxSimple.tryParse(in, ibs));
System.out.printf("The number you have entered was: %d%n", ibs.v());
}
}
a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume
getline(file, genero, ' ') ;
it is newline \n
so change that line to
getline(file, genero); // \n is default delimiter
You need a different seed at every execution.
You can start to call at the beginning of your program:
srand(time(NULL));
Note that % 10
yields a result from 0
to 9
and not from 1
to 10
: just add 1
to your %
expression to get 1
to 10
.
you can use $.param to assign data :
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: $.param({"foo":"bar"})
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
look at this : AngularJS + ASP.NET Web API Cross-Domain Issue
When you call test
with &nKByte
, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.
Either do not use a reference for the argument, or better yet don't use a pointer.
There's two answers in this question.
Use:
expires modified +90d;
E.G.:
location ~* ^.+\.(css|js|jpg|gif|png|txt|ico|swf|xml)$ {
access_log off;
root /path/to/htdocs;
expires modified +90d;
}
You don't use the :
syntax - pull
always modifies the currently checked-out branch. Thus:
git pull origin my_remote_branch
while you have my_local_branch
checked out will do what you want.
Since you already have the tracking branch set, you don't even need to specify - you could just do...
git pull
while you have my_local_branch
checked out, and it will update from the tracked branch.
String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
.buildAndExpand(params)
.toUri();
uri = UriComponentsBuilder
.fromUri(uri)
.queryParam("name", "myName")
.build()
.toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);
The safe way is to expand the path variables first, and then add the query parameters:
For me this resulted in duplicated encoding, e.g. a space was decoded to %2520 (space -> %20 -> %25).
I solved it by:
String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
uriComponentsBuilder.uriVariables(params);
Uri uri = uriComponentsBuilder.queryParam("name", "myName");
.build()
.toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);
Essentially I am using uriComponentsBuilder.uriVariables(params);
to add path parameters. The documentation says:
... In contrast to UriComponents.expand(Map) or buildAndExpand(Map), this method is useful when you need to supply URI variables without building the UriComponents instance just yet, or perhaps pre-expand some shared default values such as host and port. ...
this works for me
brew cask upgrade chromedriver
I came across this question, and figured out sorting the iterators directly would be a way to sort the values and keep track of indices; There is no need to define an extra container of pair
s of ( value, index ) which is helpful when the values are large objects; The iterators provides the access to both the value and the index:
/*
* a function object that allows to compare
* the iterators by the value they point to
*/
template < class RAIter, class Compare >
class IterSortComp
{
public:
IterSortComp ( Compare comp ): m_comp ( comp ) { }
inline bool operator( ) ( const RAIter & i, const RAIter & j ) const
{
return m_comp ( * i, * j );
}
private:
const Compare m_comp;
};
template <class INIter, class RAIter, class Compare>
void itersort ( INIter first, INIter last, std::vector < RAIter > & idx, Compare comp )
{
idx.resize ( std::distance ( first, last ) );
for ( typename std::vector < RAIter >::iterator j = idx.begin( ); first != last; ++ j, ++ first )
* j = first;
std::sort ( idx.begin( ), idx.end( ), IterSortComp< RAIter, Compare > ( comp ) );
}
as for the usage example:
std::vector < int > A ( n );
// populate A with some random values
std::generate ( A.begin( ), A.end( ), rand );
std::vector < std::vector < int >::const_iterator > idx;
itersort ( A.begin( ), A.end( ), idx, std::less < int > ( ) );
now, for example, the 5th smallest element in the sorted vector would have value **idx[ 5 ]
and its index in the original vector would be distance( A.begin( ), *idx[ 5 ] )
or simply *idx[ 5 ] - A.begin( )
.
Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:
ContextWrapper.getFilesDir()
Found here.
use a Relativelayout to wrap LinearLayout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:round="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text="<"/>
<TextView
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:layout_weight = "1"/>
<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text=">"/>
</LinearLayout>
</RelativeLayout>`
It's even possible to restore without creating a blank database at all.
In Sql Server Management Studio, right click on Databases and select Restore Database...
In the Restore Database dialog, select the Source Database or Device as normal. Once the source database is selected, SSMS will populate the destination database name based on the original name of the database.
It's then possible to change the name of the database and enter a new destination database name.
With this approach, you don't even need to go to the Options tab and click the "Overwrite the existing database" option.
Also, the database files will be named consistently with your new database name and you still have the option to change file names if you want.
If you have any dependencies in pom.xml specific to your organisation than you need to update path of setting.xml for your project which is by default set to your user directory in Ubuntu : /home/user/.m2/settings.xml -> (change it to your apache-maven conf path)
I have encountered the very similar problem today. For some reason IntelliJ IDEA
haven't included Spring Security jar files while deploying the application. I think I should agree with the majority of posters here.
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
Data List is a new HTML tag in HTML5 supported browsers. It renders as a text box with some list of options. For Example for Gender Text box it will give you options as Male Female when you type 'M' or 'F' in Text Box.
<input list="Gender">
<datalist id="Gender">
<option value="Male">
<option value="Female>
</datalist>
you can try
isfar <- get(load('c:/users/isfar.Rdata'))
this will assign the variable in isfar.Rdata to isfar . After this assignment, you can use str(isfar) or ls(isfar) or head(isfar) to get a rough look of the isfar.
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
In SQL Server if you need only the hh:mi
, you can use:
DECLARE @datetime datetime
SELECT @datetime = GETDATE()
SELECT RIGHT('0'+CAST(DATEPART(hour, @datetime) as varchar(2)),2) + ':' +
RIGHT('0'+CAST(DATEPART(minute, @datetime)as varchar(2)),2)
function logout() {
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf("msie") != -1) {
document.execCommand("ClearAuthenticationCache", false);
}
xhr_objectCarte = null;
if(window.XMLHttpRequest)
xhr_object = new XMLHttpRequest();
else if(window.ActiveXObject)
xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
else
alert ("Your browser doesn't support XMLHTTPREQUEST");
xhr_object.open ('GET', 'http://yourserver.com/rep/index.php', false, 'username', 'password');
xhr_object.send ("");
xhr_object = null;
document.location = 'http://yourserver.com';
return false;
}
The following regex matches alphanumeric characters and underscore:
^[a-zA-Z0-9_]+$
For example, in Perl:
#!/usr/bin/perl -w
my $arg1 = $ARGV[0];
# check that the string contains *only* one or more alphanumeric chars or underscores
if ($arg1 !~ /^[a-zA-Z0-9_]+$/) {
print "Failed.\n";
} else {
print "Success.\n";
}
To answer your original question, it's (x1, y1)
to (x2, y2)
.
For example,
This is to draw a horizontal line:
g.drawLine( 10, 30, 90, 30 );
vs
This is to draw a vertical line:
g.drawLine( 10, 30, 10, 90 );
I hope it helps.
I think, best way to use/set boolean value as parameter is to use in your PS script it like this:
Param(
[Parameter(Mandatory=$false)][ValidateSet("true", "false")][string]$deployApp="false"
)
$deployAppBool = $false
switch($deployPmCmParse.ToLower()) {
"true" { $deployAppBool = $true }
default { $deployAppBool = $false }
}
So now you can use it like this:
.\myApp.ps1 -deployAppBool True
.\myApp.ps1 -deployAppBool TRUE
.\myApp.ps1 -deployAppBool true
.\myApp.ps1 -deployAppBool "true"
.\myApp.ps1 -deployAppBool false
#and etc...
So in arguments from cmd you can pass boolean value as simple string :).
I think your best shot is a border-left
property that is assigned to each one of the li
s except the first one (You would have to give the first one a class named first
and explicitly remove the border for that).
Even if you are generating the <li>
programmatically, assigning a first
class should be easy.
you can reset your branch with HEAD
git reset --hard branch_name
then fetch branches and delete branches which are not on remote from local,
git fetch -p
Adding
font-weight: normal;
To your @font-face fonts will fix the bold appearance in Firefox.
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'
It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.
You can do it by subfolders (example /css/v1/style.css)
or by filename (example: css/style_v1.css)
or even by setting different folders for your website, example:
www.mywebsite.com/site1
www.mywebsite.com/site2
www.mywebsite.com/site3
And use a .htaccess or even change httpd.conf to redirect to your current application.
If's about one image or page:
<?$time = date("H:i:s");?>
<img src="myfile.jpg?time=<?$time;?>">
You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.
At this time, there is no need for the script tag inside the iframe. This works for me (tested in Chrome, Firefox, IE11 and node-webkit 0.12):
<script>
window.onload = function() {
var body = 'dddddd';
var newWin = document.getElementById('printf').contentWindow;
newWin.document.write(body);
newWin.document.close(); //important!
newWin.focus(); //IE fix
newWin.print();
}
</script>
<iframe id="printf"></iframe>
Thanks to all answers, save my day.
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
If you would like to use thumbnail through pure js/jquery no api, you can use this tool to capture a frame from the video and voila! Insert url thumb in which ever source you like.
Here is a code pen :
<img src="https://i.vimeocdn.com/video/531141496_640.jpg"` alt="" />
Here is the site to get thumbnail:
from IPython.display import Image
Image(filename =r'C:\user\path')
I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.
// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
// set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
var postEnc, method;
if (post == null)
{
postEnc = '';
method = 'GET';
}
else
{
method = 'POST';
postEnc = new FormData();
for(var i in post)
postEnc.append(i, post[i]);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var res = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(res);
reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
}
}
xhr.open(method, url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('fname=Henry&lname=Ford');
xhr.responseType = 'blob';
xhr.send(postEnc);
}
Here you go:
^[^<>]*$
This will test for string that has no <
and no >
If you want to test for a string that may have <
and >
, but must also have something other you should use just
[^<>] (or ^.*[^<>].*$)
Where [<>]
means any of <
or >
and [^<>]
means any that is not of <
or >
.
And of course the mandatory link.
From looking at the source code, it seems like the pg_stat_database query gives you the number of connections to the current database for all users. On the other hand, the pg_stat_activity query gives the number of connections to the current database for the querying user only.
And this option?
list_name<-list()
for(i in 1:100){
paste("orca",i,sep="")->list_name[[i]]
}
It works perfectly. In the example you put, first line is missing, and then gives you the error message.
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
you are looking for this:
a:visited{
color:blue;
}
Links have several states you can alter... the way I remember them is LVHFA (Lord Vader's Handle Formerly Anakin)
Each letter stands for a pseudo class: (Link,Visited,Hover,Focus,Active)
a:link{
color:blue;
}
a:visited{
color:purple;
}
a:hover{
color:orange;
}
a:focus{
color:green;
}
a:active{
color:red;
}
If you want the links to always be blue, just change all of them to blue. I would note though on a usability level, it would be nice if the mouse click caused the color to change a little bit (even if just a lighter/darker blue) to help indicate that the link was actually clicked (this is especially important in a touchscreen interface where you're not always sure the click was actually registered)
If you have different types of links that you want to all have the same color when clicked, add a class to the links.
a.foo, a.foo:link, a.foo:visited, a.foo:hover, a.foo:focus, a.foo:active{
color:green;
}
a.bar, a.bar:link, a.bar:visited, a.bar:hover, a.bar:focus, a.bar:active{
color:orange;
}
It should be noted that not all browsers respect each of these options ;-)
date
and datetime
objects (and time
as well) support a mini-language to specify output, and there are two ways to access it:
dt.strftime('format here')
'{:format here}'.format(dt)
f'{dt:format here}'
So your example could look like:
dt.strftime('The date is %b %d, %Y')
'The date is {:%b %d, %Y}'.format(dt)
f'The date is {dt:%b %d, %Y}'
In all three cases the output is:
The date is Feb 23, 2012
For completeness' sake: you can also directly access the attributes of the object, but then you only get the numbers:
'The date is %s/%s/%s' % (dt.month, dt.day, dt.year)
# The date is 02/23/2012
The time taken to learn the mini-language is worth it.
For reference, here are the codes used in the mini-language:
%a
Weekday as locale’s abbreviated name.%A
Weekday as locale’s full name.%w
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.%d
Day of the month as a zero-padded decimal number.%b
Month as locale’s abbreviated name.%B
Month as locale’s full name.%m
Month as a zero-padded decimal number. 01, ..., 12%y
Year without century as a zero-padded decimal number. 00, ..., 99%Y
Year with century as a decimal number. 1970, 1988, 2001, 2013%H
Hour (24-hour clock) as a zero-padded decimal number. 00, ..., 23%I
Hour (12-hour clock) as a zero-padded decimal number. 01, ..., 12%p
Locale’s equivalent of either AM or PM.%M
Minute as a zero-padded decimal number. 00, ..., 59%S
Second as a zero-padded decimal number. 00, ..., 59%f
Microsecond as a decimal number, zero-padded on the left. 000000, ..., 999999%z
UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030%Z
Time zone name (empty if naive), UTC, EST, CST%j
Day of the year as a zero-padded decimal number. 001, ..., 366%U
Week number of the year (Sunday is the first) as a zero padded decimal number.%W
Week number of the year (Monday is first) as a decimal number.%c
Locale’s appropriate date and time representation.%x
Locale’s appropriate date representation.%X
Locale’s appropriate time representation.%%
A literal '%' character.I linux this works too:
import sys
sys.path.extend(["/path/to/dotpy/file/"])
jQuery Library must be in the head section then.
<button onclick="var less = parseInt($('#qty').val()) - 1; $('#qty').val(less);"></button>
<input type="text" id="qty" value="2">
<button onclick="var add = parseInt($('#qty').val()) + 1; $('#qty').val(add);">+</button>
Another cause is accidentally putting the data=...
inside the aes(...)
instead of outside:
RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
In particular this can happen when you prototype your plot command with qplot()
, which doesn't use an explicit aes()
, then edit/copy-and-paste it into a ggplot()
qplot(data=..., x=...,y=..., ...)
ggplot(data=..., aes(x=...,y=...,...))
It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.
You can use CssClass
attribute and pass a value as a css class name
<asp:Button CssClass="button" Text="Submit" runat="server"></asp:Button>`
.button
{
//write more styles
}
As an alternative to using the import approach described in several answers, have a look a the configparser module.
The ConfigParser class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.
The easiest way to call a function safely using the name stored in a variable is,
//I want to call method deploy that is stored in functionname
$functionname = 'deploy';
$retVal = {$functionname}('parameters');
I have used like below to create migration tables in Laravel dynamically,
foreach(App\Test::$columns as $name => $column){
$table->{$column[0]}($name);
}
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
lst = lst[0:2] + lst[6:]
This is a single step operation. It does not use a loop and therefore executes fast. It uses list slicing.
There are two variants of CASE
, and you're not using the one that you think you are.
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE
Each condition is loosely equivalent to a if (case_value == when_value)
(pseudo-code).
However, you've put an entire condition as when_value
, leading to something like:
if (case_value == (case_value > 100))
Now, (case_value > 100)
evaluates to FALSE
, and is the only one of your conditions to do so. So, now you have:
if (case_value == FALSE)
FALSE
converts to 0
and, through the resulting full expression if (case_value == 0)
you can now see why the third condition fires.
Drop the first course_enrollment_settings
so that there's no case_value
, causing MySQL to know that you intend to use the second variant of CASE
:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE
Now you can provide your full conditionals as search_condition
.
Also, please read the documentation for features that you use.
Something like:
function populate(selector) {
$(selector)
.append('<option value="foo">foo</option>')
.append('<option value="bar">bar</option>')
}
populate('#myform .myselect');
Or even:
$.fn.populate = function() {
$(this)
.append('<option value="foo">foo</option>')
.append('<option value="bar">bar</option>')
}
$('#myform .myselect').populate();
You can use either of these functions:
// This should work in node.js and other ES5 compliant implementations.
function isEmptyObject(obj) {
return !Object.keys(obj).length;
}
// This should work both there and elsewhere.
function isEmptyObject(obj) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
Example usage:
if (isEmptyObject(query)) {
// There are no queries.
} else {
// There is at least one query,
// or at least the query object is not empty.
}
For folks that are here looking for a solution for images in particular here it is.
private Bitmap getBitmapFromUri(Uri contentUri) {
String path = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
path = cursor.getString(columnIndex);
}
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(path);
return bitmap;
}
You could just change the shebang line. I do this all the time on new systems.
If you want pip
to install to a current version of Python installed just update the shebang line to the correct version of pythons path.
For example, to change pip (not pip3) to install to Python 3:
#!/usr/bin/python
To:
#!/usr/bin/python3
Any module you install using pip
should install to Python not Python.
Or you could just change the path.
try Select * from openquery("aa-db-dev01",'Select * from users')
,the database connection should be defined in he linked server configuration
https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html
The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:
SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;
If your project does not use stdafx.h, you can put the following lines as the first lines in your .cpp file and the compiler warning should go away -- at least it did for me in Visual Studio C++ 2008.
#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1
It's ok to have comment and blank lines before them.
I'm having this problem myself - my page breaks work in every browser but Chrome - and was able to isolate it down to the page-break-after element being inside a table cell. (Old, inherited templates in the CMS.)
Apparently Chrome doesn't honor the page-break-before or page-break-after properties inside table cells, so this modified version of Phil's example puts the second and third headline on the same page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Paginated HTML</title>
<style type="text/css" media="print">
div.page
{
page-break-after: always;
page-break-inside: avoid;
}
</style>
</head>
<body>
<div class="page">
<h1>This is Page 1</h1>
</div>
<table>
<tr>
<td>
<div class="page">
<h1>This is Page 2</h1>
</div>
<div class="page">
<h1>This is, sadly, still Page 2</h1>
</div>
</td>
</tr>
</table>
</body>
</html>
Chrome's implementation is (dubiously) allowed given the CSS specification - you can see more here: http://www.google.com/support/forum/p/Chrome/thread?tid=32f9d9629d6f6789&hl=en
So use a semi-colon:
alias lock='gnome-screensaver; gnome-screen-saver-command --lock'
This doesn't work well if you want to supply arguments to the first command. Alternatively, create a trivial script in your $HOME/bin directory.
I usually do this to switch back and forth between forms.
Firstly, in Program file I keep ApplicationContext and add a helper SwitchMainForm method.
static class Program
{
public static ApplicationContext AppContext { get; set; }
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Save app context
Program.AppContext = new ApplicationContext(new LoginForm());
Application.Run(AppContext);
}
//helper method to switch forms
public static void SwitchMainForm(Form newForm)
{
var oldMainForm = AppContext.MainForm;
AppContext.MainForm = newForm;
oldMainForm?.Close();
newForm.Show();
}
}
Then anywhere in the code now I call SwitchMainForm method to switch easily to the new form.
// switch to some other form
var otherForm = new MyForm();
Program.SwitchMainForm(otherForm);
Use Date.Now
instead of DateTime.Now
double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);
TimeSpan.TotalMinutes: The total number of minutes represented by this instance.
Hello I can suggest you universal method. use recursion.
public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
// We need to know keys of Jsonobject
JSONObject json = new JSONObject()
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i<jArray.length();i++) {
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
It should work. If you have questions, go ahead.. I'm ready.
There is not currently any way to style HTML5 <audio>
players using CSS. Instead, you can leave off the control
attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.
Easily extracting multiple properties from array of objects:
let arrayOfObjects = [
{id:1, name:'one', desc:'something'},
{id:2, name:'two', desc:'something else'}
];
//below will extract just the id and name
let result = arrayOfObjects.map(({id, name}) => ({id, name}));
result
will be [{id:1, name:'one'},{id:2, name:'two'}]
Add or remove properties as needed in the map function
DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month
Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int>
mapping the month's name to its value.
Below code is very useful to hide default browse button and use custom instead:
(function($) {_x000D_
$('input[type="file"]').bind('change', function() {_x000D_
$("#img_text").html($('input[type="file"]').val());_x000D_
});_x000D_
})(jQuery)
_x000D_
.file-input-wrapper {_x000D_
height: 30px;_x000D_
margin: 2px;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
width: 118px;_x000D_
background-color: #fff;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper>input[type="file"] {_x000D_
font-size: 40px;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
opacity: 0;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper>.btn-file-input {_x000D_
background-color: #494949;_x000D_
border-radius: 4px;_x000D_
color: #fff;_x000D_
display: inline-block;_x000D_
height: 34px;_x000D_
margin: 0 0 0 -1px;_x000D_
padding-left: 0;_x000D_
width: 121px;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper:hover>.btn-file-input {_x000D_
//background-color: #494949;_x000D_
}_x000D_
_x000D_
#img_text {_x000D_
float: right;_x000D_
margin-right: -80px;_x000D_
margin-top: -14px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
<div class="file-input-wrapper">_x000D_
<button class="btn-file-input">SELECT FILES</button>_x000D_
<input type="file" name="image" id="image" value="" />_x000D_
</div>_x000D_
<span id="img_text"></span>_x000D_
</body>
_x000D_
If you want to use array without knowing the size first you have to declare it and later you can instantiate it like
string[] myArray;
...
...
myArray=new string[someItems.count];
You may want to try out simple function I posted on another thread related to reading date value from excel sheet.
It simply takes text from the cell as input and gives DateTime as output.
I would be happy to see improvement in my sample code provided for benefit of the .Net development community.
Here is the link for the thread C# not reading excel date from spreadsheet
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
Joshua Bloch has a talk about API design that covers how bad ones make boilerplate code necessary. (Minute 46 for reference to boilerplate, listening to this today)
To list all local groups which have users assigned to them, use this command:
cut -d: -f1 /etc/group | sort
For more info- > Unix groups, Cut command, sort command
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
originalArrayList.addAll(copyArrayList);
Please Note: When using the addAll() method to copy, the contents of both the array lists (originalArrayList and copyArrayList) refer to the same objects or contents. So if you modify any one of them the other will also reflect the same change.
If you don't wan't this then you need to copy each element from the originalArrayList to the copyArrayList, like using a for or while loop.
Check out my answer : https://stackoverflow.com/a/40285262/5879376
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"@s.whatsapp.net");//phone number without "+" prefix
startActivity(sendIntent);