$('#myModal').on('hidden.bs.modal', function () {
$(this).data('bs.modal', null).remove();
});
//Just add .remove();
//Bootstrap v3.0.3
Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch
from props, do not pass mapDispatchToProps
function to connect
.
class ModalContainer extends React.Component {
handleDelete = () => {
const { dispatch, onClose } = this.props;
dispatch({type: 'DELETE_POST'});
someAsyncOperation().then(() => {
dispatch({type: 'DELETE_POST_SUCCESS'});
onClose();
})
}
render() {
const { onClose } = this.props;
return <Modal onClose={onClose} onSubmit={this.handleDelete} />
}
}
export default connect(/* no map dispatch to props here! */)(ModalContainer);
The App where the modal is rendered and its visibility state is set:
class App extends React.Component {
state = {
isModalOpen: false
}
handleModalClose = () => this.setState({ isModalOpen: false });
...
render(){
return (
...
<ModalContainer onClose={this.handleModalClose} />
...
)
}
}
I had the same problem with jquery-ui overlay dialog box - it would work only once and then stop unless i reload the page. I found the answer in one of their examples -
Multiple overlays on a same page
flowplayer_tools_multiple_open_close
- who would have though, right?? :-) -
the important setting appeared to be
oneInstance: false
so, now i have it like this -
$(document).ready(function() {
var overlays = null;
overlays = jQuery("a[rel]");
for (var n = 0; n < overlays.length; n++) {
$(overlays[n]).overlay({
oneInstance: false,
mask: '#669966',
effect: 'apple',
onBeforeLoad: function() {
overlay_before_load(this);
}
});
}
}
and everything works just fine
hope this helps somebody
O.
In my application, I am using the below piece of code to show Bootstrap modal via jQuery.
$('#myModall').modal({
backdrop: 'static',
keyboard: true,
show: true
});
Use a document.ready()
event around your call.
$(document).ready(function () {
$('#memberModal').modal('show');
});
jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/
I Found that applying ionic framework (ionic.min.cs) after bootstrap coursing this issue for me.
You can add the class to the title like this:
$('#dialog_style1').siblings('div.ui-dialog-titlebar').addClass('dialog1');
The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
Try this
$(function() {
$('#clickMe').click(function(event) {
var mytext = $('#myText').val();
$('<div id="dialog">'+mytext+'</div>').appendTo('body');
event.preventDefault();
$("#dialog").dialog({
width: 600,
modal: true,
close: function(event, ui) {
$("#dialog").remove();
}
});
}); //close click
});
And in HTML
<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>
Faced with the same problem, I was able to solve it using only vanilla JS, but in an ugly way. To be more accurate, in a non-procedural way. I removed all my function parameters and return values and replaced them with global variables, and now the functions only serve as containers for lines of code - they're no longer logical units.
In my case, I also had the added complication of needing many confirmations (as a parser works through a text). My solution was to put everything up to the first confirmation in a JS function that ends by painting my custom popup on the screen, and then terminating.
Then the buttons in my popup call another function that uses the answer and then continues working (parsing) as usual up to the next confirmation, when it again paints the screen and then terminates. This second function is called as often as needed.
Both functions also recognize when the work is done - they do a little cleanup and then finish for good. The result is that I have complete control of the popups; the price I paid is in elegance.
Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.
We can close the modal pop-up in the following ways:
// We use data-dismiss property of modal-up in html to close the modal-up,such as
<div class='modal-footer'><button type='button' class="btn btn-default" data-dismiss='modal'>Close</button></div>
// We can close the modal pop-up through java script, such as
<div class='modal fade pageModal' id='openModal' tabindex='-1' data-keyboard='false' data-backdrop='static'>
$('#openModal').modal('hide'); //Using modal pop-up Id.
$('.pageModal').modal('hide'); //Using class that is defined in modal html.
It's not a good way, but for me it seems the most simplest.
Add an anchor tag which contains the modal data-target and data-toggle, have an id associated with it. (Can be added mostly anywhere in the html view)
<a href="" data-toggle="modal" data-target="#myModal" id="myModalShower"></a>
Now,
Inside the angular controller, from where you want to trigger the modal just use
angular.element('#myModalShower').trigger('click');
This will mimic a click to the button based on the angular code and the modal will appear.
Try this:
$(document).ready(function(){
$("#showSimpleModal").click(function() {
$("div#simpleModal").addClass("show");
$("#videoContainer")[0].play();
return false;
});
$("#closeSimple").click(function() {
$("div#simpleModal").removeClass("show");
$("#videoContainer")[0].pause();
return false;
});
});
I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html
A little cleaner and more modular solution might be:
$(document).ready(function(){
$('.modal').success(function() {
$('input:text:visible:first').focus();
});
});
Or using your ID as an example instead:
$(document).ready(function(){
$('#modal-content').modal('show').success(function() {
$('input:text:visible:first').focus();
});
});
Hope that helps..
You hide Bootstrap modals with:
$('#modal').modal('hide');
Saying $().hide()
makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.
I would do it like this:
$('body').on('hidden.bs.modal', '#myModal', function(){ //this call your method });
The rest has already been written by others. I also recommend reading the documentation:jquery - on method
Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:
I hope that helps
Well this is the answer of your questions...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE>Santa Luisa</TITLE>
<style>
body{margin:0;padding:0;background-color:#ffffff;}
a:link {color:black;}
a:visited {color:black;}
a:hover {color:red;}
a:active {color:red;}
</style>
</HEAD>
<body>
<link rel="stylesheet" href="jquery/themes/base/jquery.ui.all.css">
<script src="jquery-1.4.4.js"></script>
<script src="external/jquery.bgiframe-2.1.2.js"></script>
<script src="ui/jquery.ui.core.js"></script>
<script src="ui/jquery.ui.widget.js"></script>
<script src="ui/jquery.ui.mouse.js"></script>
<script src="ui/jquery.ui.draggable.js"></script>
<script src="ui/jquery.ui.position.js"></script>
<script src="ui/jquery.ui.resizable.js"></script>
<script src="ui/jquery.ui.dialog.js"></script>
<link rel="stylesheet" href="demos.css">
<script>
var lastdel;
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,modal: true,closeOnEscape: true
});
$(".confirmLink").click(function(e) {
e.preventDefault();
var lastdel = $(this).attr("href");
});
$("#si").click( function() {
$('#dialog').dialog('close');
window.location.href =lastdel;
});
$("#no").click( function() {
$('#dialog').dialog('close');
});
});
</script>
<SCRIPT LANGUAGE="JavaScript">
<!--
var currentimgx;
var cimgoverx=200-6;
var cimgoutx=200;
function overbx(obj){
color='#FF0000';
width='3px';
obj.style.borderTopWidth = width;
obj.style.borderTopColor =color;
obj.style.borderTopStyle ='solid';
obj.style.borderLeftWidth = width;
obj.style.borderLeftColor =color;
obj.style.borderLeftStyle ='solid';
obj.style.borderRightWidth = width;
obj.style.borderRightColor =color;
obj.style.borderRightStyle ='solid';
obj.style.borderBottomWidth = width;
obj.style.borderBottomColor =color;
obj.style.borderBottomStyle ='solid';
currentimgx.style.width=cimgoverx+"px";
currentimgx.style.height=cimgoverx+"px";
}
function outbx(obj){
obj.style.borderTopWidth = '0px';
obj.style.borderLeftWidth = '0px';
obj.style.borderRightWidth = '0px';
obj.style.borderBottomWidth = '0px';
currentimgx.style.width=cimgoutx+"px";
currentimgx.style.height=cimgoutx+"px";
}
function ifocusx(obj){
color='#FF0000';
width='3px';
obj.style.borderTopWidth = width;
obj.style.borderTopColor =color;
obj.style.borderTopStyle ='solid';
obj.style.borderLeftWidth = width;
obj.style.borderLeftColor =color;
obj.style.borderLeftStyle ='solid';
obj.style.borderRightWidth = width;
obj.style.borderRightColor =color;
obj.style.borderRightStyle ='solid';
obj.style.borderBottomWidth = width;
obj.style.borderBottomColor =color;
obj.style.borderBottomStyle ='solid';
}
function iblurx(obj){
color='#000000';
width='3px';
obj.style.borderTopWidth = width;
obj.style.borderTopColor =color;
obj.style.borderTopStyle ='solid';
obj.style.borderLeftWidth = width;
obj.style.borderLeftColor =color;
obj.style.borderLeftStyle ='solid';
obj.style.borderRightWidth = width;
obj.style.borderRightColor =color;
obj.style.borderRightStyle ='solid';
obj.style.borderBottomWidth = width;
obj.style.borderBottomColor =color;
obj.style.borderBottomStyle ='solid';
}
function cimgx(obj){
currentimgx=obj;
}
function pause(millis){
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
//-->
</SCRIPT>
<div id="dialog" title="CONFERMA L`AZIONE" style="text-align:center;">
<p><FONT COLOR="#000000" style="font-family:Arial;font-size:22px;font-style:bold;COLOR:red;">CONFERMA L`AZIONE:<BR>POSSO CANCELLARE<BR>QUESTA RIGA ?</FONT></p>
<p><INPUT TYPE="submit" VALUE="SI" NAME="" id="si"> --><INPUT TYPE="submit" VALUE="NO" NAME="" id="no"></p>
</div>
<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%" height="100%">
<TR valign="top" align="center">
<TD>
<FONT COLOR="red" style="font-family:Arial;font-size:25px;font-style:bold;color:red;">Modifica/Dettagli:<font style="font-family:Arial;font-size:20px;font-style:bold;background-color:yellow;color:red;"> 298 </font><font style="font-family:Arial;font-size:20px;font-style:bold;background-color:red;color:yellow;">dsadas sadsadas </font> </FONT>
</TD>
</TR>
<tr valign="top">
<td align="center">
<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">
<TR align="left">
<TD>
<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">
<TR align="left">
<TD>
<font style="font-sixe:30px;"><span style="color:red;">1</span></font><br><TABLE class="tabela" CELLSPACING="0" CELLPADDING="0" BORDER="1" WIDTH="800px"><TR style="color:white;background-color:black;"><TD align="center">DATA</TD><TD align="center">CODICE</TD><TD align="center">NOME/NOMI</TD><TD align="center">TESTO</TD><td> </td><td> </td></TR><TR align="center"><TD>12/22/2010 </TD><TD>298 </TD><TD>daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</TD><TD><A HREF="modificarigadiario.php?codice=298" style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);" style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=1';alert(lastdel);" class="confirmLink">Cancella</A></TD><TR align="center"><TD>22/10/2010 </TD><TD>298 </TD><TD>dfdsfsdfsf</TD><TD><A HREF="modificarigadiario.php?codice=298" style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);" style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=2';alert(lastdel);" class="confirmLink">Cancella</A></TD></TABLE><font style="font-sixe:30px;"><span style="color:red;">1</span></font><br>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</td>
</tr>
</tbody></table>
</body>
</html>
make sure you have jquery 1.4.4 and jquery.ui
I was looking for the onClick option to set the title and body of the modal based on the item in a list. T145's answer helped a lot, so I wanted to share how I used it.
Make sure the tag containing the JavaScript function is of type text/javascript to avoid conflicts:
<script type="text/javascript"> function showMyModalSetTitle(myTitle, myBodyHtml) {
/*
* '#myModayTitle' and '#myModalBody' refer to the 'id' of the HTML tags in
* the modal HTML code that hold the title and body respectively. These id's
* can be named anything, just make sure they are added as necessary.
*
*/
$('#myModalTitle').html(myTitle);
$('#myModalBody').html(myBodyHtml);
$('#myModal').modal('show');
}</script>
This function can now be called in the onClick method from inside an element such as a button:
<button type="button" onClick="javascript:showMyModalSetTitle('Some Title', 'Some body txt')"> Click Me! </button>
With the modal open in the browser window, use the browser's console to try
$('#myModal').modal('hide');
If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.
If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?
Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.
A simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
use eModal to display a modal for alert, ajax, prompt or confirm
// Display an alert modal with default title (Attention)
eModal.ajax('your/url.html');
$(document).ready(function () {/* activate scroll spy menu */_x000D_
_x000D_
var iconPrefix = '.glyphicon-';_x000D_
_x000D_
_x000D_
$(iconPrefix + 'cloud').click(ajaxDemo);_x000D_
$(iconPrefix + 'comment').click(alertDemo);_x000D_
$(iconPrefix + 'ok').click(confirmDemo);_x000D_
$(iconPrefix + 'pencil').click(promptDemo);_x000D_
$(iconPrefix + 'screenshot').click(iframeDemo);_x000D_
///////////////////* Implementation *///////////////////_x000D_
_x000D_
// Demos_x000D_
function ajaxDemo() {_x000D_
var title = 'Ajax modal';_x000D_
var params = {_x000D_
buttons: [_x000D_
{ text: 'Close', close: true, style: 'danger' },_x000D_
{ text: 'New content', close: false, style: 'success', click: ajaxDemo }_x000D_
],_x000D_
size: eModal.size.lg,_x000D_
title: title,_x000D_
url: 'http://maispc.com/app/proxy.php?url=http://loripsum.net/api/' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'_x000D_
};_x000D_
_x000D_
return eModal_x000D_
.ajax(params)_x000D_
.then(function () { alert('Ajax Request complete!!!!', title) });_x000D_
}_x000D_
_x000D_
function alertDemo() {_x000D_
var title = 'Alert modal';_x000D_
return eModal_x000D_
.alert('You welcome! Want clean code ?', title)_x000D_
.then(function () { alert('Alert modal is visible.', title); });_x000D_
}_x000D_
_x000D_
function confirmDemo() {_x000D_
var title = 'Confirm modal callback feedback';_x000D_
return eModal_x000D_
.confirm('It is simple enough?', 'Confirm modal')_x000D_
.then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })_x000D_
.fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });_x000D_
}_x000D_
_x000D_
function iframeDemo() {_x000D_
var title = 'Insiders';_x000D_
return eModal_x000D_
.iframe('https://www.youtube.com/embed/VTkvN51OPfI', title)_x000D_
.then(function () { alert('iFrame loaded!!!!', title) });_x000D_
}_x000D_
_x000D_
function promptDemo() {_x000D_
var title = 'Prompt modal callback feedback';_x000D_
return eModal_x000D_
.prompt({ size: eModal.size.sm, message: 'What\'s your name?', title: title })_x000D_
.then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: 'https://avatars0.githubusercontent.com/u/4276775?v=3&s=89' }) })_x000D_
.fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });_x000D_
}_x000D_
_x000D_
//#endregion_x000D_
});
_x000D_
.fa{_x000D_
cursor:pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet" >_x000D_
<link href="http//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">_x000D_
_x000D_
<div class="row" itemprop="about">_x000D_
<div class="col-sm-1 text-center"></div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Ajax</h3>_x000D_
<p>You must get the message from a remote server? No problem!</p>_x000D_
<i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Alert</h3>_x000D_
<p>Traditional alert box. Using only text or a lot of magic!?</p>_x000D_
<i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Confirm</h3>_x000D_
<p>Get an okay from user, has never been so simple and clean!</p>_x000D_
<i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Prompt</h3>_x000D_
<p>Do you have a question for the user? We take care of it...</p>_x000D_
<i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>iFrame</h3>_x000D_
<p>IFrames are hard to deal with it? We don't think so!</p>_x000D_
<i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-1 text-center"></div>_x000D_
</div>
_x000D_
Your code is working when i click out side the modal, but if i use html input
field inside modal-body then focus your cursor on that input then press esc
key the modal has closed.
Click here
Simple
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate">
<%Html.RenderPartial("Modal");%>
</script>
...which lets me keep my templates in a partial view called Modal.ascx
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{Name}}</h3>
</div>
<div class="modal-body">
<table class="table table-striped table-condensed">
<tbody>
<tr><td>ID</td><td>{{Id}}</td></tr>
<tr><td>Name</td><td>{{Name}}</td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%>
<div data-id="<%=Html.Encode(item.Id)%>"
id="modelModal<%=Html.Encode(item.Id)%>"
class="modal hide fade">
</div>
<%}%>
...and make ajax calls with jQuery:
<script type="text/javascript">
var modalTemplate = $("#modalTemplate").html()
$(".modal[data-id]").each(function() {
var $this = $(this)
var id = $this.attr("data-id")
$this.on("show", function() {
if ($this.html()) return
$.ajax({
type: "POST",
url: "<%=Url.Action("SomeAction")%>",
data: { id: id },
success: function(data) {
$this.append(Mustache.to_html(modalTemplate, data))
}
})
})
})
</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%>
<a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
<%=Html.Encode(item.DutModel.Name)%>
</a>
<%}%>
.modal('hide') manually hides a modal. Use following code to close your bootstrap model
$('#myModal').modal('hide');
Take a look at working codepen here
Or
Try here
$(function () {_x000D_
$(".custom-close").on('click', function() {_x000D_
$('#myModal').modal('hide');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- Button trigger modal -->_x000D_
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
_x000D_
_x000D_
<a class="custom-close"> My Custom Close Link </a>_x000D_
_x000D_
_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
<button type="button" class="btn btn-primary">Save changes</button>_x000D_
</div>_x000D_
</div><!-- /.modal-content -->_x000D_
</div><!-- /.modal-dialog -->_x000D_
</div><!-- /.modal -->
_x000D_
may be this code may give you some idea.
http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/
$(document).ready(function() {
$('#page-help').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
autoOpen: false,
title: $link.attr('title'),
width: 500,
height: 300
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
});
});
I found the solution at: Passing data to a bootstrap modal
So simply use:
$(e.relatedTarget).data('book-id');
with 'book-id
' is a attribute of modal with pre-fix 'data-
'
Something shorter version based off Yermo Lamers' suggestion, this seems to work alright. Even with basic animations like fade in/out and even crazy batman newspaper rotate. http://jsfiddle.net/ketwaroo/mXy3E/
$('.modal').on('show.bs.modal', function(event) {
var idx = $('.modal:visible').length;
$(this).css('z-index', 1040 + (10 * idx));
});
$('.modal').on('shown.bs.modal', function(event) {
var idx = ($('.modal:visible').length) -1; // raise backdrop after animation.
$('.modal-backdrop').not('.stacked').css('z-index', 1039 + (10 * idx));
$('.modal-backdrop').not('.stacked').addClass('stacked');
});
I had the same problem. I discovered it was due to a conflict between Bootstrap and JQueryUI.
Both use the class "close". Changing the class in one or the other fixes this.
try to use ng-window, it's allow developer to open and full control multiple windows in single page applications in simple way, No Jquery, No Bootstrap.
Avilable Configration
Your problem is on the call for the dialog
If you dont initialize the dialog, you don't have to pass "open" for it to show:
$("#dialog").dialog();
Also, this code needs to be on a $(document).ready();
function or be below the elements for it to work.
As a workaround I personally use a custom global flag to determine whether the modal has been opened or not and I reset it on 'hidden.bs.modal'
You can use the shown event/show event based on what you need:
$( "#code" ).on('shown', function(){
alert("I want this to appear after the modal has opened!");
});
Demo: Plunker
For Bootstrap 3.0 you can still use the shown event but you would use it like this:
$('#code').on('shown.bs.modal', function (e) {
// do something...
})
See the Bootstrap 3.0 docs here under "Events".
I had this issue and the easiest way to fix it was addind z-index greater than 1040 on the modal-dialog div:
<div class="modal-dialog" style="z-index: 1100;">
I believe bootstrap create a div modal-backdrop fade in which in my case has the z-index 1040, so if You put the modal-dialog on top of this, it should not be grey out anymore.
I want to share how I did this. I spent the last few days rattling my head with how to pass a couple of parameters to the bootstrap modal dialog. After much head bashing, I came up with a rather simple way of doing this.
Here is my modal code:
<div class="modal fade" id="editGroupNameModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div id="editGroupName" class="modal-header">Enter new name for group </div>
<div class="modal-body">
<%= form_tag( { action: 'update_group', port: portnum } ) do %>
<%= text_field_tag( :gid, "", { type: "hidden" }) %>
<div class="input-group input-group-md">
<span class="input-group-addon" style="font-size: 16px; padding: 3;" >Name</span>
<%= text_field_tag( :gname, "", { placeholder: "New name goes here", class: "form-control", aria: {describedby: "basic-addon1"}}) %>
</div>
<div class="modal-footer">
<%= submit_tag("Submit") %>
</div>
<% end %>
</div>
</div>
</div>
</div>
And here is the simple javascript to change the gid, and gname input values:
function editGroupName(id, name) {
$('input#gid').val(id);
$('input#gname.form-control').val(name);
}
I just used the onclick event in a link:
// ' is single quote
// ('1', 'admin')
<a data-toggle="modal" data-target="#editGroupNameModal" onclick="editGroupName('1', 'admin'); return false;" href="#">edit</a>
The onclick fires first, changing the value property of the input boxes, so when the dialog pops up, values are in place for the form to submit.
I hope this helps someone someday. Cheers.
use this:
$(document).on('show.bs.modal','#myModal', function () {
alert('hi');
})
Based on Jason Sebring's very useful tip, and on the stuff covered here and there, I found a perfect solution for my case:
Pseudo code with Javascript snippets:
immediately create a blank popup on user action
var importantStuff = window.open('', '_blank');
(Enrich the call to window.open
with whatever additional options you need.)
Optional: add some "waiting" info message. Examples:
a) An external HTML page: replace the above line with
var importantStuff = window.open('http://example.com/waiting.html', '_blank');
b) Text: add the following line below the above one:
importantStuff.document.write('Loading preview...');
fill it with content when ready (when the AJAX call is returned, for instance)
importantStuff.location.href = 'https://example.com/finally.html';
Alternatively, you could close the window here if you don't need it after all (if ajax request fails
, for example - thanks to @Goose for the comment):
importantStuff.close();
I actually use this solution for a mailto redirection, and it works on all my browsers (windows 7, Android). The _blank
bit helps for the mailto redirection to work on mobile, btw.
You've no doubt solved this by now or decided to do something different, but as it has not been answered & I stumbled across this when looking for something similar I thought I'd share my method.
I've taken to using two div sets. One has hidden-xs and is for sm, md & lg device viewing. The other has hidden-sm, -md, -lg and is only for mobile. Now I have a lot more control over the display in my CSS.
You can see a rough idea in this js fiddle where I set the footer and buttons to be smaller when the resolution is of the -xs size.
<div class="modal-footer">
<div class="hidden-xs">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
<div class="hidden-sm hidden-md hidden-lg sml-footer">
<button type="button" class="btn btn-xs btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-xs btn-primary">Save changes</button>
</div>
</div>
Here's one other css only method that works pretty well and is based on this: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/
sass:
.modal {
height: 100%;
.modal-dialog {
top: 50% !important;
margin-top:0;
margin-bottom:0;
}
//keep proper transitions on fade in
&.fade .modal-dialog {
transform: translateY(-100%) !important;
}
&.in .modal-dialog {
transform: translateY(-50%) !important;
}
}
You could try:
.modal.modal-wide .modal-dialog {
width: 90%;
}
.modal-wide .modal-body {
overflow-y: auto;
}
Just add .modal-wide to your classes
Here is a new solution based on Bennett McElwee answer in the same question as mentioned below.
Tested with IE 9 & 10, Opera 12.01, Google Chrome 22 and Firefox 15.0.
jsFiddle example
@media screen {
#printSection {
display: none;
}
}
@media print {
body * {
visibility:hidden;
}
#printSection, #printSection * {
visibility:visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
function printElement(elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
$printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof (delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof (delimiter) === "object") {
$printSection.appendChild(delimiter);
}
}
$printSection.appendChild(domClone);
}?
You're ready to print any element on your site!
Just call printElement()
with your element(s) and execute window.print()
when you're finished.
Note: If you want to modify the content before it is printed (and only in the print version), checkout this example (provided by waspina in the comments): http://jsfiddle.net/95ezN/121/
One could also use CSS in order to show the additional content in the print version (and only there).
I think, you have to hide all other parts of the site via CSS.
It would be the best, to move all non-printable content into a separate DIV
:
<body>
<div class="non-printable">
<!-- ... -->
</div>
<div class="printable">
<!-- Modal dialog comes here -->
</div>
</body>
And then in your CSS:
.printable { display: none; }
@media print
{
.non-printable { display: none; }
.printable { display: block; }
}
Credits go to Greg who has already answered a similar question: Print <div id="printarea"></div> only?
There is one problem in using JavaScript: the user cannot see a preview - at least in Internet Explorer!
I find answer. Thanks all but right answer next:
$("#myModal").on("hidden", function () {
$('#result').html('yes,result');
});
Events here http://bootstrap-ru.com/javascript.php#modals
UPD
For Bootstrap 3.x need use hidden.bs.modal:
$("#myModal").on("hidden.bs.modal", function () {
$('#result').html('yes,result');
});
All of the example above should work just add a document ready action and change the order of how you perform the updates to the texts, also make sure your using Script manager alternatively non of this will work for you. Here is the text within the code behind.
aspx
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><asp:Label ID="lblModalTitle" runat="server" Text=""></asp:Label></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<asp:Label ID="lblModalBody" runat="server" Text=""></asp:Label>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
Code Behind
lblModalTitle.Text = "Validation Errors";
lblModalBody.Text = form.Error;
upModal.Update();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$(document).ready(function () {$('#myModal').modal();});", true);
I tried the accepted answer which prevented the body from scrolling but had the issue of scrolling to the top. This should solve both issues.
As a side note, it appears overflow:hidden doesn't work on body for iOS Safari only as iOS Chrome works fine.
var scrollPos = 0;
$('.modal')
.on('show.bs.modal', function (){
scrollPos = $('body').scrollTop();
$('body').css({
overflow: 'hidden',
position: 'fixed',
top : -scrollPos
});
})
.on('hide.bs.modal', function (){
$('body').css({
overflow: '',
position: '',
top: ''
}).scrollTop(scrollPos);
});
There are several solutions to this but this is the pattern I tend to use.
// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
if(form2.ShowDialog() == DialogResult.OK)
{
someControlOnForm1.Text = form2.TheValue;
}
}
And...
// Inside Form2
// Create a public property to serve the value
public string TheValue
{
get { return someTextBoxOnForm2.Text; }
}
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
Bootstrap 3 and Bootstrap 4 docs refer two events you can use.
hide.bs.modal: This event is fired immediately when the hide instance method has been called.
hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).
And provide an example on how to use them:
$('#myModal').on('hidden.bs.modal', function () {
// do something…
})
Bootstrap's documentation refers two events you can use.
hide: This event is fired immediately when the hide instance method has been called.
hidden: This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).
And provides an example on how to use them:
$('#myModal').on('hidden', function () {
// do something…
})
Use the following code
$("#modal").trigger('click');
if you are using custom CSS instead of defining modal class as "modal fade" or "modal fade in" change it to only "modal" in HTML page then try again.
You can hide the modal and popup the window to review the carts in validateShipping() function itself.
function validateShipping(){
...
...
$('#product-options').modal('hide');
//pop the window to select items
}
Why not just change the content of the modal body?
window.switchContent = function(myFile){
$('.modal-body').load(myFile);
};
In the modal just put a link or a button
<a href="Javascript: switchContent('myFile.html'); return false;">
click here to load another file</a>
If you just want to switch beetween 2 modals:
window.switchModal = function(){
$('#myModal-1').modal('hide');
setTimeout(function(){ $('#myModal-2').modal(); }, 500);
// the setTimeout avoid all problems with scrollbars
};
In the modal just put a link or a button
<a href="Javascript: switchModal(); return false;">
click here to switch to the second modal</a>
Had to face the same issue. The reason is same as the @merv
. Issue was with a calendar component added to the page.The component itself add the modal feature to be used in the calendar popup.
So the reasons to break model popup will be one or more of the following
I noticed some of the answers were not triggering the HTML5 required
attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):
<form id='xform'></form>
with some inputs with the required attribute and place a <input type='submit'>
at the end.<input type='text' name='xconf' value='' required>
modal_1_accept
to the accept button.modal_2_accept
to the accept button.m2_Txt
to the displayed text holder.The JS to intercept before the form is sent:
$("#xform").submit(function(e){
var msg, conf, preventSend;
if($("#xform").attr("data-send")!=="ready"){
msg="Error."; //default error msg
preventSend=false;
conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
if(conf===""){
msg="The field is empty.";
preventSend=true;
}else if(conf!=="ok"){
msg="You didn't write \"ok\" correctly.";
preventSend=true;
}
if(preventSend){ //validation failed, show the error
$("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
$("#modal_2_errMsg").modal("show");
}else{ //validation passed, now let's confirm the action
$("#modal_1_confirm").modal("show");
}
e.preventDefault();
return false;
}
});
`9. Also some stuff when clicking the Buttons from the modals:
$("#modal_1_accept").click(function(){
$("#modal_1_confirm").modal("hide");
$("#xform").attr("data-send", "ready").submit();
});
$("#modal_2_accept").click(function(){
$("#modal_2_errMsg").modal("hide");
});
Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept")
will assume the validation passed and it will add the "ready"
attribute:
$("#modal_1_confirm").modal("show");
is shown only when it passed
the validation, so clicking $("#modal_1_accept")
should be
unreachable without first getting the form validated.You can set the scrollTop
, like this:
$('html,body').scrollTop(0);
Or if you want a little animation instead of a snap to the top:
$('html, body').animate({ scrollTop: 0 }, 'fast');
Well, this is another solution that some of you guys might be looking for (as I was..)
My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.
The solutions presented here were not working 100%.
My solution was this:
showLocationModal = function(loc){
var is_loading = true;
if(is_loading === true) {
is_loading = false;
var $modal = $('#locationModal');
$modal.modal({show:true});
// prevent Modal to close before the iframe is loaded
$modal.on("hide", function (e) {
if(is_loading !== true) {
e.preventDefault();
return false
}
});
// populate Modal
$modal.find('.modal-body iframe').hide().attr('src', location.link).load(function(){
is_loading = true;
});
}};
So I temporarily prevent the Modal from closing with:
$modal.on("hide", function (e) {
if(is_loading !== true) {
e.preventDefault();
return false
}
});
But ith the var is_loading that will re enable closing after the Iframe has loaded.
1.this is my answer for your problem.
.ModalCarrot::before {
content:'';
background: url('blackCarrot.png'); /*url of image*/
height: 16px; /*height of image*/
width: 33px; /*width of image*/
position: absolute;
}
not sure the contetns of your JFrame, if you ask some input from users, you can use JOptionPane, this also can set JFrame as modal
JFrame frame = new JFrame();
String bigList[] = new String[30];
for (int i = 0; i < bigList.length; i++) {
bigList[i] = Integer.toString(i);
}
JOptionPane.showInputDialog(
frame,
"Select a item",
"The List",
JOptionPane.PLAIN_MESSAGE,
null,
bigList,
"none");
}
This worked for me in Swift 5.0. Set the Storyboard Id in the identity inspector as "destinationVC".
@IBAction func buttonTapped(_ sender: Any) {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destVC = storyboard.instantiateViewController(withIdentifier: "destinationVC") as! MyViewController
destVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
destVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(destVC, animated: true, completion: nil)
}
i did this:
$("#myModal").modal({}).draggable();
and it make my very standard/basic modal draggable.
not sure how/why it worked, but it did.
I did this:
$('#myModal').on 'shown.bs.modal', (e) ->
$(e.target).find('.modal-body').load('http://yourserver.com/content')
For bootstrap 3 you should use:
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
If the code of the previous posts doesn't work, give this a try:
$("a.ui-dialog-titlebar-close")[0].click();
There are two ways to do it.
In the method that opens the dialog, pass in the following configuration option disableClose
as the second parameter in MatDialog#open()
and set it to true
:
export class AppComponent {
constructor(private dialog: MatDialog){}
openDialog() {
this.dialog.open(DialogComponent, { disableClose: true });
}
}
Alternatively, do it in the dialog component itself.
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>){
dialogRef.disableClose = true;
}
}
Here's what you're looking for:
And here's a Stackblitz demo
Here's some other use cases and code snippets of how to implement them.
As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:
import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
selector: 'app-third-dialog',
templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {
}
@HostListener('window:keyup.esc') onKeyUp() {
this.dialogRef.close();
}
}
P.S. This is an answer which originated from this answer, where the demo was based on this answer.
To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick
to listen for click events to the backdrop.
Initially, the dialog will have the configuration option disableClose
set as true
. This ensures that the esc
keypress, as well as clicking on the backdrop will not cause the dialog to close.
Afterwards, subscribe to the MatDialogRef#backdropClick
method (which emits when the backdrop gets clicked and returns as a MouseEvent
).
Anyways, enough technical talk. Here's the code:
openDialog() {
let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
// ...
}
Alternatively, this can be done in the dialog component:
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>) {
dialogRef.disableClose = true;
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
}
}
I have tried it, it works for you.
String mainWinHander = webDriver.getWindowHandle();
// code for clicking button to open new window is ommited
//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHander.equals(handle))
{
// Here will block for ever. No exception and timeout!
WebDriver popup = webDriver.switchTo().window(handle);
// do something with popup
popup.close();
}
}
I have found it!
You can catch the close event using the following code:
$('div#popup_content').on('dialogclose', function(event) {
alert('closed');
});
Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()
A method taking into consideration
it takes such a multi-line string which may be messy e.g.
test_str = '\nhej ho \n aaa\r\n a\n '
and produces nice one-line string
>>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
'hej ho aaa a'
UPDATE: To fix multiple new-line character producing redundant spaces:
' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])
This works for the following too
test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '
I faced the same issue. I had missed the forms module import tag in the app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule,
FormsModule
],
I'm using the following to execute commands on the remote from my local computer:
ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2
I had a similar requirement when running test locally instead of in docker. Basically I only wanted to install any .deb files found if they weren't already installed.
# If there are .deb files in the folder, then install them
if [ `ls -1 *.deb 2> /dev/null | wc -l` -gt 0 ]; then
for file in *.deb; do
# Only install if not already installed (non-zero exit code)
dpkg -I ${file} | grep Package: | sed -r 's/ Package:\s+(.*)/\1/g' | xargs dpkg -s
if [ $? != 0 ]; then
dpkg -i ${file}
fi;
done;
else
err "No .deb files found in '$PWD'"
fi
I guess they only problem I can see is that it doesn't check the version number of the package so if .deb file is a newer version, then this wouldn't overwrite the currently installed package.
You can also do this with named ranges so you don't have to copy the cells from Sheet1 to Sheet2:
Define a named range, say Sheet1Vals
for the column that has the values on which you want to base your condition. You can define a new named range by using the Insert\Name\Define...
menu item. Type in your name, then use the cell browser in the Refers to
box to select the cells you want in the range. If the range will change over time (add or remove rows) you can use this formula instead of selecting the cells explicitly:
=OFFSET('SheetName'!$COL$ROW,0,0,COUNTA('SheetName'!$COL:$COL))
.
Add a -1
before the last )
if the column has a header row.
Define a named range, say Sheet2Vals
for the column that has the values you want to conditionally format.
Use the Conditional Formatting dialog to create your conditions. Specify Formula Is
in the dropdown, then put this for the formula:
=INDEX(Sheet1Vals, MATCH([FirstCellInRange],Sheet2Vals))=[Condition]
where [FirstCellInRange]
is the address of the cell you want to format and [Condition]
is the value your checking.
For example, if my conditions in Sheet1 have the values of 1
, 2
and 3
and the column I'm formatting is column B
in Sheet2 then my conditional formats would be something like:
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=1
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=2
=INDEX(Sheet1Vals, MATCH(B1,Sheet2Vals))=3
You can then use the format painter to copy these formats to the rest of the cells.
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
// Key exists
}
else
{
// Key doesn't exist
}
Problem 1:
The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model. Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?
Problem 2:
Make sure you're using the following ng-options:
<select ng-model="object.item" ng-options="item.id as item.name for item in list" />
And put this in your controller to select a default value:
object.item = 4
For all users, I would recommend placing the following line in /etc/profile
export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:/bin/javac::")
This will update dynamically and works well with the alternatives system. Do note though that the update will only take place in a new login shell.
Five years late to the party.
It is mentioned in the provided links of the accepted answer, but I think it deserves an explicit answer on SO - dynamically building the query based on provided parameters. E.g.:
Setup
-- drop table Person
create table Person
(
PersonId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Person PRIMARY KEY,
FirstName NVARCHAR(64) NOT NULL,
LastName NVARCHAR(64) NOT NULL,
Title NVARCHAR(64) NULL
)
GO
INSERT INTO Person (FirstName, LastName, Title)
VALUES ('Dick', 'Ormsby', 'Mr'), ('Serena', 'Kroeger', 'Ms'),
('Marina', 'Losoya', 'Mrs'), ('Shakita', 'Grate', 'Ms'),
('Bethann', 'Zellner', 'Ms'), ('Dexter', 'Shaw', 'Mr'),
('Zona', 'Halligan', 'Ms'), ('Fiona', 'Cassity', 'Ms'),
('Sherron', 'Janowski', 'Ms'), ('Melinda', 'Cormier', 'Ms')
GO
Procedure
ALTER PROCEDURE spDoSearch
@FirstName varchar(64) = null,
@LastName varchar(64) = null,
@Title varchar(64) = null,
@TopCount INT = 100
AS
BEGIN
DECLARE @SQL NVARCHAR(4000) = '
SELECT TOP ' + CAST(@TopCount AS VARCHAR) + ' *
FROM Person
WHERE 1 = 1'
PRINT @SQL
IF (@FirstName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @FirstName'
IF (@LastName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @LastName'
IF (@Title IS NOT NULL) SET @SQL = @SQL + ' AND Title = @Title'
EXEC sp_executesql @SQL, N'@TopCount INT, @FirstName varchar(25), @LastName varchar(25), @Title varchar(64)',
@TopCount, @FirstName, @LastName, @Title
END
GO
Usage
exec spDoSearch @TopCount = 3
exec spDoSearch @FirstName = 'Dick'
Pros:
Cons:
Not direct answer, but related to the problem aka the big picture
Usually, these filtering stored procedures do not float around, but are being called from some service layer. This leaves the option of moving away business logic (filtering) from SQL to service layer.
One example is using LINQ2SQL to generate the query based on provided filters:
public IList<SomeServiceModel> GetServiceModels(CustomFilter filters)
{
var query = DataAccess.SomeRepository.AllNoTracking;
// partial and insensitive search
if (!string.IsNullOrWhiteSpace(filters.SomeName))
query = query.Where(item => item.SomeName.IndexOf(filters.SomeName, StringComparison.OrdinalIgnoreCase) != -1);
// filter by multiple selection
if ((filters.CreatedByList?.Count ?? 0) > 0)
query = query.Where(item => filters.CreatedByList.Contains(item.CreatedById));
if (filters.EnabledOnly)
query = query.Where(item => item.IsEnabled);
var modelList = query.ToList();
var serviceModelList = MappingService.MapEx<SomeDataModel, SomeServiceModel>(modelList);
return serviceModelList;
}
Pros:
Cons:
I have come up with the same issue, instead of storing images, that eventually overflow the local storage, you can just store the path to the image. something like:
let imagen = ev.target.getAttribute('src');
arrayImagenes.push(imagen);
You should write :
if (self.a != 0) and (self.b != 0) :
"&
" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&
" is "and" in Python.
A shorter way to check what you want is to use the "in" operator :
if 0 not in (self.a, self.b) :
You can check if anything is part of a an iterable with "in", it works for :
"foo" in ("foo", 1, c, etc)
will return true"foo" in ["foo", 1, c, etc]
will return true"a" in "ago"
will return true"foo" in {"foo" : "bar"}
will return trueAs an answer to the comments :
Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.
For the triangle check, it's easier to read :
0 not in (self.a, self.b, self.c)
Than
(self.a != 0) and (self.b != 0) and (self.c != 0)
It's easier to refactor too.
Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.
If there is no duplicate value in the list:
for i in ints:
indx = ints.index(i)
print(i, indx)
In my case the problem was caused by trying to mock a static method and forgetting to call mockStatic
on the class. Also I forgot to include the class into the @PrepareForTest()
You can also set language at runtime
sqldeveloper.exe --AddVMOption=-Duser.language=en
to avoid editing sqldeveloper.conf every time you install new version.
Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Subject varchar(50) NULL
)
CREATE TABLE dbo.Owner
(
ID int NOT NULL,
User_ID int NULL,
Group_ID int NULL,
{{AdditionalEntity_ID}} int NOT NULL
)
With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).
If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
Subject varchar(50) NULL
)
With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.
Sorry if I got some SQL wrong, I just threw this together.
I just got this error and it turns out my AD administrator deleted the service account used by EVERY SQL Server instance in the entire company. Thank goodness AD has its own recycle bin.
See if you can run the Active Directory Users and Computers utility (%SystemRoot%\system32\dsa.msc), and check to make sure the account you are relying on still exists.
All solutions work great, except when applied in programming languages that closures (e.g. Coda, Excel, Spreadsheet's REGEXREPLACE
).
Two original solutions of mine below use only 1 concatenation and 1 regex.
The idea is to append replacement values if they are not already in the string. Then, using a single regex, we perform all needed replacements:
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||cat,dog,goat").replace(
/cat(?=[\s\S]*(dog))|dog(?=[\s\S]*(goat))|goat(?=[\s\S]*(cat))|\|\|\|\|.*$/gi, "$1$2$3");
document.body.innerHTML = str;
_x000D_
Explanations:
cat(?=[\s\S]*(dog))
means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise."$1$2$3"
(the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above casesstr+"||||cat,dog,goat"
, we remove them by also matching \|\|\|\|.*$
, in which case the replacement "$1$2$3"
will evaluate to "", the empty string.One problem with Method #1 is that it cannot exceed 9 replacements at a time, which is the maximum number of back-propagation groups. Method #2 states not to append just replacement values, but replacements directly:
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||,cat=>dog,dog=>goat,goat=>cat").replace(
/(\b\w+\b)(?=[\s\S]*,\1=>([^,]*))|\|\|\|\|.*$/gi, "$2");
document.body.innerHTML = str;
_x000D_
Explanations:
(str+"||||,cat=>dog,dog=>goat,goat=>cat")
is how we append a replacement map to the end of the string.(\b\w+\b)
states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else.(?=[\s\S]*...)
is a forward lookup that will typically go to the end of the document until after the replacement map.
,\1=>
means "you should find the matched word between a comma and a right arrow"([^,]*)
means "match anything after this arrow until the next comma or the end of the doc"|\|\|\|\|.*$
is how we remove the replacement map.Of course the best approach is to use the ever-more-supported <input type="search" />
.
Anyway for a bit of coding fun I thought that it could be achieved also using the form's reset button, and this is the working result (it is worth noting that you cannot have other inputs in the form but the search field with this approach, or the reset button will erase them too), no javascript needed:
form{
position: relative;
width: 200px;
}
form input {
width: 100%;
padding-right: 20px;
box-sizing: border-box;
}
form input:placeholder-shown + button{
opacity: 0;
pointer-events: none;
}
form button {
position: absolute;
border: none;
display: block;
width: 15px;
height: 15px;
line-height: 16px;
font-size: 12px;
border-radius: 50%;
top: 0;
bottom: 0;
right: 5px;
margin: auto;
background: #ddd;
padding: 0;
outline: none;
cursor: pointer;
transition: .1s;
}
_x000D_
<form>
<input type="text" placeholder=" " />
<button type="reset">×</button>
</form>
_x000D_
This is all you need to read.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString
var height = 200;
var width = 200;
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.strokeStyle = '#090';
ctx.beginPath();
ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2);
ctx.stroke();
canvas.toBlob(function (blob) {
//consider blob is your file object
var reader = new FileReader();
reader.onload = function () {
console.log(reader.result);
}
reader.readAsBinaryString(blob);
});
I had the same problem, my code is below:
private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
private Statement stmt = conn.createStatement();
I have not loaded the driver class, but it works locally, I can query the results from MySQL, however, it does not work when I deploy it to Tomcat, and the errors below occur:
No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud
so I loaded the driver class, as below, when I saw other answers posted:
Class.forName("com.mysql.jdbc.Driver");
It works now! I don't know why it works well locally, I need your help, thank you so much!
[on hold: broken in Chrome 72; reported to work in Chrome 71]
The "Quick Language Switcher" extension may help too: https://chrome.google.com/webstore/detail/quick-language-switcher/pmjbhfmaphnpbehdanbjphdcniaelfie
The Quick Language Switcher extension allows the user to supersede the locale the browser is currently using in favor of the value chosen through the extension.
Had same issue when I had to develop a fixed length field format.
Usually we do not use line separator for binary files but For some reason our customer wished to add a line break as separator between records. They set
< record_delimiter value="\n"/ >
but this didn't work as records got two additional characters:
< record1 > \n < record2 > \n.... and so on.
Did following change and it just worked.
< record_delimiter value="\n"/> => < record_delimiter value="
"/ >
After unmarshaling Java interprets as new line character.
String ZipPath = @"c:\my\data.zip";
String extractPath = @"d:\\myunzips";
ZipFile.ExtractToDirectory(ZipPath, extractPath);
To use the ZipFile class, you must add a reference to the System.IO.Compression.FileSystem assembly in your project
# dump into file
pg_dump myDB > /tmp/myDB.sql
# create an empty db with the right encoding (on older versions the escaped single quotes are needed!)
psql -c 'CREATE DATABASE "tempDB" WITH OWNER = "myself" LC_COLLATE = '\''de_DE.utf8'\'' TEMPLATE template0;'
# import in the new DB
psql -d tempDB -1 -f /tmp/myDB.sql
# rename databases
psql -c 'ALTER DATABASE "myDB" RENAME TO "myDB_wrong_encoding";'
psql -c 'ALTER DATABASE "tempDB" RENAME TO "myDB";'
# see the result
psql myDB -c "SHOW LC_COLLATE"
Try \n\n , it will work! :)
public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}
To everyone struggling, what worked for me was creating personal access token and then using it as a username AND password (in the prompt that opened).
Either use LINQ:
var value = MyList.First(item => item.name == "foo").value;
(This will just find the first match, of course. There are lots of options around this.)
Or use Find
instead of FindIndex
:
var value = MyList.Find(item => item.name == "foo").value;
I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.
(I'd also suggest following the .NET naming conventions.)
As of BS3 there's a .center-block
helper class. From the docs:
// Classes
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
// Usage as mixins
.element {
.center-block();
}
There is hidden complexity in this seemingly simple problem. All the answers given have some issues.
Create .col-centred
class, but there is a major gotcha.
.col-centred {
float: none !important;
margin: 0 auto;
}
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
Centred content.
</div>
The Gotcha
Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.
The Fixes
You can resolve this issue by using a clearfix
element. Using z-index
to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.
<div class="row">
<div class="col-lg-12">
I get overlapped by `col-lg-7 centered` unless there's a clearfix.
</div>
<div class="clearfix"></div>
<div class="col-lg-7 centred">
</div>
</div>
Or you can isolate the centred column in its own row.
<div class="row">
<div class="col-lg-12">
</div>
</div>
<div class="row">
<div class="col-lg-7 centred">
Look I am in my own row.
</div>
</div>
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
Centred content.
</div>
The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).
Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.
This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.
.col-centred {
margin: 0 auto;
}
<div class="row">
<div class="col-lg-12">
<div class="centred">
Look I am in my own row.
</div>
</div>
</div>
I currently use Corona for business applications with great success. As far as games go, I'm under the impression that it doesn't provide the performance that some of the other cross-platform development engines do. It is worth noting that Carlos (founder of Ansca Mobile/Corona SDK) has started another company on a competing engine; Lanica Platino Engine for Appcelerator Titanium. While I haven't worked with this personally, it does look promising. Keep in mind, however, that it comes with a $999/yr price tag.
All that said, I have been researching Moai for a little while now (since I am already familiar with Lua syntax) and it does seem promising. The fact that it can compile for multiple platforms, not limited to mobile environments, is appealing.
Multimedia Fusion 2 is also a worth contender, considering the complexity of games produced and the performance realized from them. Vincere Totus Astrum (http://gamesare.com) comes to mind.
You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)
EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).
See "URL Encoding (or: 'What are those "%20
" codes in URLs?')".
urlresolver has been removed in the higher version of Django - Please upgrade your django installation. I fixed it using the following command.
pip install django==2.0 --upgrade
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
Improve to @inno answer
delimiter //
DROP PROCEDURE IF EXISTS get_product;
CREATE PROCEDURE get_product()
BEGIN
DECLARE i VARCHAR(100);
DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO i;
SELECT i; -- printing table name
SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%');
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END LOOP read_loop;
CLOSE cur1;
END//
delimiter ;
call get_product();
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
Few more ways.
1) The geekiest and hackiest - it uses the IEXPRESS to create small exe that will create a pop-up with a single button (it can create two more types of pop-up messages). Works on EVERY windows from XP and above:
;@echo off
;setlocal
;set ppopup_executable=popupe.exe
;set "message2=click OK to continue"
;
;del /q /f %tmp%\yes >nul 2>&1
;
;copy /y "%~f0" "%temp%\popup.sed" >nul 2>&1
;(echo(FinishMessage=%message2%)>>"%temp%\popup.sed";
;(echo(TargetName=%cd%\%ppopup_executable%)>>"%temp%\popup.sed";
;(echo(FriendlyName=%message1_title%)>>"%temp%\popup.sed"
;
;iexpress /n /q /m %temp%\popup.sed
;%ppopup_executable%
;rem del /q /f %ppopup_executable% >nul 2>&1
;pause
;endlocal
;exit /b 0
[Version]
Class=IEXPRESS
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=1
HideExtractAnimation=1
UseLongFileName=0
InsideCompressed=0
CAB_FixedSize=0
CAB_ResvCodeSigning=0
RebootMode=N
InstallPrompt=%InstallPrompt%
DisplayLicense=%DisplayLicense%
FinishMessage=%FinishMessage%
TargetName=%TargetName%
FriendlyName=%FriendlyName%
AppLaunched=%AppLaunched%
PostInstallCmd=%PostInstallCmd%
AdminQuietInstCmd=%AdminQuietInstCmd%
UserQuietInstCmd=%UserQuietInstCmd%
SourceFiles=SourceFiles
[SourceFiles]
SourceFiles0=C:\Windows\System32\
[SourceFiles0]
%FILE0%=
[Strings]
AppLaunched=subst.exe
PostInstallCmd=<None>
AdminQuietInstCmd=
UserQuietInstCmd=
FILE0="subst.exe"
DisplayLicense=
InstallPrompt=
2) Using MSHTA
. Also works on every windows machine from XP and above (despite the OP do not want "external" languages the JavaScript here is minimized). Should be saved as .bat
:
@if (true == false) @end /*!
@echo off
mshta "about:<script src='file://%~f0'></script><script>close()</script>" %*
goto :EOF */
alert("Hello, world!");
or in one line:
mshta "about:<script>alert('Hello, world!');close()</script>"
or
mshta "javascript:alert('message');close()"
or
mshta.exe vbscript:Execute("msgbox ""message"",0,""title"":close")
3) Here's parameterized .bat/jscript
hybrid (should be saved as bat
). It again uses JavaScript despite the OP request but as it is a bat it can be called as a bat file without worries. It uses POPUP which allows a little bit more control than the more popular MSGBOX. It uses WSH, but not MSHTA like in the example above.
@if (@x)==(@y) @end /***** jscript comment ******
@echo off
cscript //E:JScript //nologo "%~f0" "%~nx0" %*
exit /b 0
@if (@x)==(@y) @end ****** end comment *********/
var wshShell = WScript.CreateObject("WScript.Shell");
var args=WScript.Arguments;
var title=args.Item(0);
var timeout=-1;
var pressed_message="button pressed";
var timeout_message="timed out";
var message="";
function printHelp() {
WScript.Echo(title + "[-title Title] [-timeout m] [-tom \"Time-out message\"] [-pbm \"Pressed button message\"] [-message \"pop-up message\"]");
}
if (WScript.Arguments.Length==1){
runPopup();
WScript.Quit(0);
}
if (args.Item(1).toLowerCase() == "-help" || args.Item(1).toLowerCase() == "-h" ) {
printHelp();
WScript.Quit(0);
}
if (WScript.Arguments.Length % 2 == 0 ) {
WScript.Echo("Illegal arguments ");
printHelp();
WScript.Quit(1);
}
for (var arg = 1 ; arg<args.Length;arg=arg+2) {
if (args.Item(arg).toLowerCase() == "-title") {
title = args.Item(arg+1);
}
if (args.Item(arg).toLowerCase() == "-timeout") {
timeout = parseInt(args.Item(arg+1));
if (isNaN(timeout)) {
timeout=-1;
}
}
if (args.Item(arg).toLowerCase() == "-tom") {
timeout_message = args.Item(arg+1);
}
if (args.Item(arg).toLowerCase() == "-pbm") {
pressed_message = args.Item(arg+1);
}
if (args.Item(arg).toLowerCase() == "-message") {
message = args.Item(arg+1);
}
}
function runPopup(){
var btn = wshShell.Popup(message, timeout, title, 0x0 + 0x10);
switch(btn) {
// button pressed.
case 1:
WScript.Echo(pressed_message);
break;
// Timed out.
case -1:
WScript.Echo(timeout_message);
break;
}
}
runPopup();
4) and one jscript.net/.bat
hybrid (should be saved as .bat
) .This time it uses .NET
and compiles a small .exe
file that could be deleted:
@if (@X)==(@Y) @end /****** silent jscript comment ******
@echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
::if exist "%~n0.exe" goto :skip_compilation
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~f0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
::
::::::::::
"%~n0.exe" %*
::::::::
::
endlocal
exit /b 0
****** end of jscript comment ******/
import System;
import System.Windows;
import System.Windows.Forms
var arguments:String[] = Environment.GetCommandLineArgs();
MessageBox.Show(arguments[1],arguments[0]);
5) and at the end one single call to powershell that creates a pop-up (can be called from command line or from batch if powershell is installed):
powershell [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Hello World""", """My PopUp Message Box""")
6) And the dbenham's approach seen here
start "" cmd /c "echo(&echo(&echo Hello world! &echo(&pause>nul"
7) For a system tray notifications you can try this:
call SystemTrayNotification.bat -tooltip warning -time 3000 -title "Woow" -text "Boom" -icon question
Function GetSearchArray(strSearch)
Dim strResults As String
Dim SHT As Worksheet
Dim rFND As Range
Dim sFirstAddress
For Each SHT In ThisWorkbook.Worksheets
Set rFND = Nothing
With SHT.UsedRange
Set rFND = .Cells.Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rFND Is Nothing Then
sFirstAddress = rFND.Address
Do
If strResults = vbNullString Then
strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
Else
strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
End If
Set rFND = .FindNext(rFND)
Loop While Not rFND Is Nothing And rFND.Address <> sFirstAddress
End If
End With
Next
If strResults = vbNullString Then
GetSearchArray = Null
ElseIf InStr(1, strResults, "|", 1) = 0 Then
GetSearchArray = Array(strResults)
Else
GetSearchArray = Split(strResults, "|")
End If
End Function
Sub test2()
For Each X In GetSearchArray("1")
Debug.Print X
Next
End Sub
Careful when doing a Find Loop that you don't get yourself into an infinite loop... Reference the first found cell address and compare after each "FindNext" statement to make sure it hasn't returned back to the first initially found cell.
Just delete ~/.m2/repository...../actual_path where the invalid LOC is coming as it forces to re-download the deleted jar files. Dont delete the whole repository folder instead delete the specific folder from where the error is coming.
// forcibly remove and reinstall all package dependencies
ren package.json package.json-bak
echo {} > package.json
npm prune
del package.json
ren package.json-bak package.json
npm i
This essentially creates a fake, empty package.json, calls npm prune
to remove everything in node_modules, restores the original package.json and re-installs everything.
Some of the other solutions might be more elegant, but I suspect this is faster and exhaustive. On other threads I've seen people suggest just deleting the node_modules directory, but at least for windows, this causes npm to choke afterward because the bin directory goes missing. Maybe on linux it gets restored properly, but not windows.
More formats:
require 'date'
date = "01/07/2016 09:17AM"
DateTime.parse(date).strftime("%A, %b %d")
#=> Friday, Jul 01
DateTime.parse(date).strftime("%m/%d/%Y")
#=> 07/01/2016
DateTime.parse(date).strftime("%m-%e-%y %H:%M")
#=> 07- 1-16 09:17
DateTime.parse(date).strftime("%b %e")
#=> Jul 1
DateTime.parse(date).strftime("%l:%M %p")
#=> 9:17 AM
DateTime.parse(date).strftime("%B %Y")
#=> July 2016
DateTime.parse(date).strftime("%b %d, %Y")
#=> Jul 01, 2016
DateTime.parse(date).strftime("%a, %e %b %Y %H:%M:%S %z")
#=> Fri, 1 Jul 2016 09:17:00 +0200
DateTime.parse(date).strftime("%Y-%m-%dT%l:%M:%S%z")
#=> 2016-07-01T 9:17:00+0200
DateTime.parse(date).strftime("%I:%M:%S %p")
#=> 09:17:00 AM
DateTime.parse(date).strftime("%H:%M:%S")
#=> 09:17:00
DateTime.parse(date).strftime("%e %b %Y %H:%M:%S%p")
#=> 1 Jul 2016 09:17:00AM
DateTime.parse(date).strftime("%d.%m.%y")
#=> 01.07.16
DateTime.parse(date).strftime("%A, %d %b %Y %l:%M %p")
#=> Friday, 01 Jul 2016 9:17 AM
The Arrays
class has versions of sort()
and binarySearch()
which don't require a Comparator.
For example, you can use the version of Arrays.sort()
which just takes an array of objects. These methods call the compareTo()
method of the objects in the array.
Just leaving this here for future visitors:
In my case the /WEB-INF/classes directory was missing. If you are using Eclipse, make sure the .settings/org.eclipse.wst.common.component is correct (Deployment Assembly in the project settings).
In my case it was missing
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/resources"/>
This file is also a common source of errors as mentioned by Anuj (missing dependencies of other projects).
Otherwise, hopefully the other answers (or the "Problems" tab) will help you.
These questions are answering the question of "how should I?" without considering the question "should I?" A change in the value of a variable that takes positive and negative values is fairly meaning less, statistically speaking. The suggestion to "shift" might work well for some variables (e.g. temperature which can be shifted to a kelvin scale or something to take care of the problem) but very poorly for others, where negativity has a precise implication for direction. For example net income or losses. Operating at a loss (negative income) has a precise meaning in this context, and moving from -50 to 30 is not in any way the same for this context as moving from 110 to 190, as a previous post suggests. These percentage changes should most likely be reported as "NA".
Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance
f = open('{}.csv'.format(name), 'wb')
Another option - the f-string formatting (ref):
f = open(f"{name}.csv", 'wb')
Using
public String replaceAll(String regex, String replacement)
will work.
Usage would be str.replace("X", "");
.
Executing
"Xlakjsdf Xxx".replaceAll("X", "");
returns:
lakjsdf xx
Temporary redirect
rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;
Permanent redirect
rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;
In nginx configuration file for specific site:
server {
server_name www.example.com;
rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;
}
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
Sounds like you're looking for rbind
:
> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30 5
Similarly, cbind
stacks the matrices horizontally.
I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")
From Resetting SQL Server Identity Columns:
Retrieving the identity for the table Employees
:
DBCC checkident ('Employees')
Repairing the identity seed (if for some reason the database is inserting duplicate identities):
DBCC checkident ('Employees', reseed)
Changing the identity seed for the table Employees
to 1000:
DBCC checkident ('Employees', reseed, 1000)
The next row inserted will begin at 1001.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Center</title>
</head>
<body>
<div id="main_body">
some text
</div>
</body>
</html>
CSS
body
{
width: 100%;
Height: 100%;
}
#main_body
{
background: #ff3333;
width: 200px;
position: absolute;
}?
JS ( jQuery )
$(function(){
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var main = $("#main_body");
$("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});
See example here
You can use \begin{flalign}
, like the example bellow:
\begin{flalign}
&f(x) = -1.25x^{2} + 1.5x&
\end{flalign}
assuming you have a SQL table called mydata - you can load data from a csv file as follows:
COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;
For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html
Somehow select2Focus didn't work here with empty selection, couldn't figured out the issue, therefore I added manual control when after focus event auto open get's triggered.
Here is coffeescript:
$("#myid").select2()
.on 'select2-blur', ->
$(this).data('select2-auto-open', 'true')
.on 'select2-focus', ->
$(this).data('select2').open() if $(this).data('select2-auto-open') != 'false'
.on 'select2-selecting', ->
$(this).data('select2-auto-open', 'false')
Java has a method for this, "convertStringArrayToIntArray".
String numbers = sc.nextLine();
int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
Do you mean this?
def perform(fun, *args):
fun(*args)
def action1(args):
# something
def action2(args):
# something
perform(action1)
perform(action2, p)
perform(action3, p, r)
You can use this -
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.
Try the following code snippet:
sudo sh -c "echo 'something' >> /etc/privilegedfile"
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
With GNU's date
you can do:
date -d "@$TIMESTAMP"
# date -d @0
Wed Dec 31 19:00:00 EST 1969
(From: BASH: Convert Unix Timestamp to a Date)
On OS X, use date -r
.
date -r "$TIMESTAMP"
Alternatively, use strftime()
. It's not available directly from the shell, but you can access it via gawk. The %c
specifier displays the timestamp in a locale-dependent manner.
echo "$TIMESTAMP" | gawk '{print strftime("%c", $0)}'
# echo 0 | gawk '{print strftime("%c", $0)}'
Wed 31 Dec 1969 07:00:00 PM EST
One more directive
html
<btn-file-selector/>
code
.directive('btnFileSelector',[function(){
return {
restrict: 'AE',
template: '<div></div>',
link: function(s,e,a){
var el = angular.element(e);
var button = angular.element('<button type="button" class="btn btn-default btn-upload">Add File</button>');
var fileForm = angular.element('<input type="file" style="display:none;"/>');
fileForm.on('change', function(){
// Actions after the file is selected
console.log( fileForm[0].files[0].name );
});
button.bind('click',function(){
fileForm.click();
});
el.append(fileForm);
el.append(button);
}
}
}]);
Use table style Border-collapse at the table level
VS2019 > Tools > Options > Nuget Package Manager > General > Click on "Clear All Nuger Cache(s)"
If source code is on Github, you can use their comparing tool: https://help.github.com/articles/comparing-commits-across-time/
Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.
A better solution with ref to avoid findDOMNode that is discouraged.
...
onScroll() {
let offsetTop = this.instance.getBoundingClientRect().top;
}
...
render() {
...
<Component ref={(el) => this.instance = el } />
...
I have put something like this in my Controller class and it worked:
IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);
where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).
For those on Azure, follow these modified instructions from Virus:
The issue as others have stated more elegantly is that you either have a Cartesian product of the OneToMany columns or you're doing N+1 Selects. Either possible gigantic resultset or chatty with the database, respectively.
I'm surprised this isn't mentioned but this how I have gotten around this issue... I make a semi-temporary ids table. I also do this when you have the IN ()
clause limitation.
This doesn't work for all cases (probably not even a majority) but it works particularly well if you have a lot of child objects such that the Cartesian product will get out of hand (ie lots of OneToMany
columns the number of results will be a multiplication of the columns) and its more of a batch like job.
First you insert your parent object ids as batch into an ids table. This batch_id is something we generate in our app and hold onto.
INSERT INTO temp_ids
(product_id, batch_id)
(SELECT p.product_id, ?
FROM product p ORDER BY p.product_id
LIMIT ? OFFSET ?);
Now for each OneToMany
column you just do a SELECT
on the ids table INNER JOIN
ing the child table with a WHERE batch_id=
(or vice versa). You just want to make sure you order by the id column as it will make merging result columns easier (otherwise you will need a HashMap/Table for the entire result set which may not be that bad).
Then you just periodically clean the ids table.
This also works particularly well if the user selects say 100 or so distinct items for some sort of bulk processing. Put the 100 distinct ids in the temporary table.
Now the number of queries you are doing is by the number of OneToMany columns.
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
According to the Apache Tomcat docs, you can change the application by creating a ROOT.xml file. See this for more info:
http://tomcat.apache.org/tomcat-6.0-doc/config/context.html
"The default web application may be defined by using a file called ROOT.xml."
This is the Best of all methods i came across
Clone just the repository's .git folder (excluding files as they are already in existing-dir
) into an empty temporary directory
git clone --no-checkout repo-path-to-clone existing-dir/existing-dir.tmp
//might want --no-hardlinks for cloning local repoMove the .git folder to the directory with the files.
This makes existing-dir
a git repo.
mv existing-dir/existing-dir.tmp/.git existing-dir/
Delete the temporary directory
rmdir existing-dir/existing-dir.tmp
cd existing-dir
Git thinks all files are deleted, this reverts the state of the repo to HEAD.
WARNING: any local changes to the files will be lost.
git reset --mixed HEAD
Rebuilding the solution worked for me
Without using "var" variables can only define when set a value. In example:
my_var;
cannot work in global scope or any other scope. It should be with value like:
my_var = "value";
On the other hand you can define a vaiable like;
var my_var;
Its value is undefined
( Its value is not null
and it is not equal to null
interestingly.).
I would say store them as an big integer, as a phone number itself is just a number. This also gives you more flexibility in how you present your phone numbers later, depending on what situation you are in.
I have experienced similar problems with Visual Studio 2015 Update 3. In my case core issue was corrupted windows installer cache (C:\Windows\Installer)
Here is the line from msi installer log:
MSI (s) (4C:64) [10:40:10:059]: Warning: Local cached package 'C:\WINDOWS\Installer\3442502.msi' is missing.
You should check installation logs if installation cache is corrupted same way. If it is you should pray for sfc utility to recover system integrity or you would reinstall windows from scratch as corrupted windows installer cache is a complete disaster and a reason to perform clear windows installation immediately.
You can't. However, you CAN use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;
If you want to use justify align in Jupyter Notebook use the following syntax:
<p style='text-align: justify;'> Your Text </p>
For right alignment:
<p style='text-align: right;'> Your Text </p>
An old thread I know but still super relevant to anyone coming across this.
Array.map has been suggested here which is an awesome method that I use all the time. Array.reduce was also mentioned...
I would personally use an Array.reduce for this use case. Why? Despite the code being slightly less clean/clear. It is a much more efficient than piping the map function to a join.
The reason for this is because Array.map has to loop over each element to return a new array with all of the names of the object in the array. Array.join then loops over the contents of array to perform the join.
You can improve the readability of jackweirdys reduce answer by using template literals to get the code on to a single line. "Supported in all modern browsers too"
// a one line answer to this question using modern JavaScript
x.reduce((a, b) => `${a.name || a}, ${b.name}`);
This would work fine.
Push-Location $PSScriptRoot
Write-Host CurrentDirectory $CurDir
One possibility is when installed sql server data tools Bi, while sql server was already set up.
Solution:- 1.Just Repair the sql server with the set up instance
if solution does not work , than its worth your time meddling with services.msc
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
This should work, at least according to the Search Filter Syntax article on MSDN network.
The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.
You may also try separating the filter into two parts:
(|(displayName=*searchstring)(displayName=searchstring*))
If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.
So instead of:
select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009
You would use:
select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890
In these examples the innermost cast(1234567890 as float)
is used in place of selecting a value from the appropriate column.
I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?
select cast(0100884555 as float)
100884555
Whoops! We just stored an incorrect phone number...
On CentOS 6.6/Grep 2.6.3, I have to use it like this:
grep "term" -Hnir --include \*.php --exclude-dir "*excluded_dir*"
Notice the lack of equal signs "=" (otherwise --include
, --exclude
, include-dir
and --exclude-dir
are ignored)
All you have to do set a variable for x then just type this in before the return 0;
cout<<"\nPress any key and hit enter to end...";
cin>>x;
Those extensions aren't really new, they are old. :-)
When C++ was new, some people wanted to have a .c++ extension for the source files, but that didn't work on most file systems. So they tried something close to that, like .cxx, or .cpp instead.
Others thought about the language name, and "incrementing" .c to get .cc or even .C in some cases. Didn't catch on that much.
Some believed that if the source is .cpp, the headers ought to be .hpp to match. Moderately successful.
I had the same problem and I wondered why this condition below did not delete the orphans. The list of dishes were not deleted in Hibernate (5.0.3.Final) when I executed a named delete query:
@OneToMany(mappedBy = "menuPlan", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Dish> dishes = new ArrayList<>();
Then I remembered that I must not use a named delete query, but the EntityManager. As I used the EntityManager.find(...)
method to fetch the entity and then EntityManager.remove(...)
to delete it, the dishes were deleted as well.
The simplest way:
#file-input {_x000D_
display: none;_x000D_
}
_x000D_
<label for="file-input">_x000D_
<div>Click this div and select a file</div>_x000D_
</label>_x000D_
<input type="file" id="file-input"/>
_x000D_
What's important, usage of display: none
ensures that no place will be occupied by the hidden file input (what happens using opacity: 0
).
This is the XML optional preamble.
version="1.0"
means that this is the XML standard this file conforms toencoding="utf-8"
means that the file is encoded using the UTF-8 Unicode encodingCheck this key for 32 bits and 64 bits Windows machines.
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
and this for Windows 64 bits with 32 Bits JRE.
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
This will work for the oracle-sun JRE.
A simple regex should be efficent to check your textarea:
/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
Inside any controller action or view, you can invoke the console by calling the console method.
For example, in a controller:
class PostsController < ApplicationController
def new
console
@post = Post.new
end
end
Or in a view:
<% console %>
<h2>New Post</h2>
This will render a console inside your view. You don't need to care about the location of the console call; it won't be rendered on the spot of its invocation but next to your HTML content.
See: http://guides.rubyonrails.org/debugging_rails_applications.html
Select * From Master..SysUsers Where IsSqlUser = 1
That is the parent folder of bin which contains tomcat.exe file:
CATALINA_HOME='C:\Program Files\Apache Software Foundation\Tomcat 6.0'
CATALINA_BASE
is the same as CATALINA_HOME
.
I disagree with the popular answer, that having public implies that there are other options and so it shouldn't be there. The fact is that now with Java 9 and beyond there ARE other options.
I think instead Java should enforce/require 'public' to be specified. Why? Because the absence of a modifier means 'package' access everywhere else, and having this as a special case is what leads to the confusion. If you simply made it a compile error with a clear message (e.g. "Package access is not allowed in an interface.") we would get rid of the apparent ambiguity that having the option to leave out 'public' introduces.
Note the current wording at: https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
"A method in the body of an interface may be declared public or private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface."
See that 'private' IS allowed now. I think that last sentence should have been removed from the JLS. It is unfortunate that the "implicitly public" behaviour was ever allowed as it will now likely remain for backward compatibilty and lead to the confusion that the absence of the access modifier means 'public' in interfaces and 'package' elsewhere.
I had this issue, and solved by following:
Cause
There is a known bug with MySQL related to MyISAM, the UTF8 character set and indexes that you can check here.
Resolution
Make sure MySQL is configured with the InnoDB storage engine.
Change the storage engine used by default so that new tables will always be created appropriately:
set GLOBAL storage_engine='InnoDb';
For MySQL 5.6 and later, use the following:
SET GLOBAL default_storage_engine = 'InnoDB';
And finally make sure that you're following the instructions provided in Migrating to MySQL.
The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:
if let index = array.enumerated().filter( { $0.element === objectToRemove }).map({ $0.offset }).first {
array.remove(at: index)
}
This worked at least in matplotlib version 2.2.2:
plt.axis([None, None, 0, 100])
Probably this is a nice way to set up for example xmin and ymax only, etc.
If I imagined that you set android:configChanges
in manifest.xml and create several directory for several language such as: values-fr OR values-nl
, I could suggest this code(In Activity class):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// change language by onclick a button
Configuration newConfig = new Configuration();
newConfig.locale = Locale.FRENCH;
onConfigurationChanged(newConfig);
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
setContentView(R.layout.main);
setTitle(R.string.app_name);
// Checks the active language
if (newConfig.locale == Locale.ENGLISH) {
Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
} else if (newConfig.locale == Locale.FRENCH){
Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
}
}
I tested this code, It is correct.
If you are using windows, Change folder security settings by giving fully controlled to the current user. It's worked for me.
changing style with jquery
Try This
$('#selector_id').css('display','none');
You can also change multiple attribute in a single query
Try This
$('#replace-div').css({'padding-top': '5px' , 'margin' : '10px'});
Check out Utf8Checker it is simple class that does exactly this in pure managed code. http://utf8checker.codeplex.com
Notice: as already pointed out "determine encoding" makes sense only for byte streams. If you have a string it is already encoded from someone along the way who already knew or guessed the encoding to get the string in the first place.
TxtFarmerSize.Text = (int)reader[3];
This was my solution:
...
BEGIN
raiserror('Invalid database', 15, 10)
rollback transaction
return
END
> but I don't know how to retrieve the list members from the hash in alphabetical order.
Not really your main question, but for future reference Rod's answer using sorted
can be used for traversing a dict
's keys in sorted order:
for key in sorted(my_dict.keys()):
print key, my_dict[key]
...
and also because tuple
's are ordered by the first member of the tuple, you can do the same with items
:
for key, val in sorted(my_dict.items()):
print key, val
...
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
If you are the owner it is simple:
Settings
button.Collaborators
Then collaborator should visit this example repo link https://github.com/user/repo/invitations
Source: Github Docs.
You have to initialize the data directory by running the following command
mysqld --initialize
[with random root password]
mysqld --initialize-insecure
[with blank root password]
<style name="Mytext" parent="@android:style/TextAppearance.Medium">
<item name="android:textSize">20sp</item>
<item name="android:textColor">@color/white</item>
<item name="android:textStyle">bold</item>
<item name="android:typeface">sans</item>
</style>
try this one ...
Note that in case of Internet Explorer 7 and Internet Explorer 9 the if
statment will give true (for "onhashchange" in windows), but the window.onhashchange
will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
EDIT -
Since jQuery 1.9, $.browser.msie
is not supported. Source: http://api.jquery.com/jquery.browser/
Set the html and body tags height
to 100%
and remove the margin around the body:
html, body {
height: 100%;
margin: 0px; /* Remove the margin around the body */
}
Now set the position
of your div to fixed
:
#dimScreen
{
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0px;
left: 0px;
z-index: 1000; /* Now the div will be on top */
}
In my case I had to install the extension:
yum install php php-mysql httpd
and then restart apache:
service httpd restart
That solved the problem.
Disclaimer: The original question was about MySQL. The SQL Server answer is below.
In MySQL, the regex syntax is the following:
SELECT * FROM YourTable WHERE (`url` NOT REGEXP '^[-A-Za-z0-9/.]+$')
Use the REGEXP
clause instead of LIKE
. The latter is for pattern matching using %
and _
wildcards.
Since you made a typo, and you're using SQL Server (not MySQL), you'll have to create a user-defined CLR function to expose regex functionality.
Take a look at this article for more details.
In application.properties, please add this:
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false
and in your html form, you need an : enctype="multipart/form-data"
.
For example:
<form method="POST" enctype="multipart/form-data" action="/">
Hope this help!
If you love one liners, try:
d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')
Input FILE = Path to file, SEP = Key-Value separator character
Not the most elegant or efficient way of doing it, but quite interesting nonetheless :)
The default username is root. You can reset the root password if you do not know it: http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. You should not, however, use the root account from PHP, set up a limited permission user to do that: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
If MySql is running on the same computer as your webserver, you can just use "localhost" as the host
Veverke mentioned that it is possible to disable generation of binding redirects by setting AutoGEneratedBindingRedirects to false. Not sure if it's a new thing since this question was posted, but there is an "Skip applying binding redirects" option in Tools/Options/Nuget Packet Manager, which can be toggled. By default it is off, meaning the redirects will be applied. However if you do this, you will have to manage any necessary binding redirects manually.
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')
# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.
you should run standlone.bat or .sh with -c standalone-full.xml switch may be work.
$('<img src="'+ imgPath +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});
If you want to do for several images then:
function loadImage(path, width, height, target) {
$('<img src="'+ path +'">').load(function() {
$(this).width(width).height(height).appendTo(target);
});
}
Use:
loadImage(imgPath, 800, 800, '#some_target');
Answer by Robert Longson (@RobertLongson) with modifications:
<svg width="100%" height="100%">
<defs>
<filter x="0" y="0" width="1" height="1" id="solid">
<feFlood flood-color="yellow"/>
<feComposite in="SourceGraphic" operator="xor"/>
</filter>
</defs>
<text filter="url(#solid)" x="20" y="50" font-size="50"> solid background </text>
<text x="20" y="50" font-size="50">solid background</text>
</svg>
and we have no bluring and no heavy "getBBox" :) Padding is provided by white spaces in text-element with filter. It's worked for me
Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:
"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png
WorksheetFunction Transpose()
Instead of copying, pasting via PasteSpecial, and using the Transpose
option you can simply type a formula
=TRANSPOSE(Sheet1!A1:A5)
or if you prefer VBA:
Dim v
v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
Sheet2.Range("A1").Resize(1, UBound(v)) = v
Note: alternatively you could use late-bound Application.Transpose
instead.
MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.
Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365
Open terminal to create ssh keys:
cd ~ #Your home directory
ssh-keygen -t rsa #Press enter for all values
(Only works if the commit program is capable of using certificates/private & public ssh keys)
Here is a walkthrough on putty gen for the above steps
This step varies, depending on how your remote is set up.
If it is a GitHub repository and you have administrative privileges, go to settings and click 'add SSH key'. Copy the contents of your ~/.ssh/id_rsa.pub
into the field labeled 'Key'.
If your repository is administered by somebody else, give the administrator your id_rsa.pub
.
If your remote repository is administered by your, you can use this command for example:
scp ~/.ssh/id_rsa.pub YOUR_USER@YOUR_IP:~/.ssh/authorized_keys/id_rsa.pub
If you have done the steps above and are still getting the password prompt, make sure your repo URL is in the form
git+ssh://[email protected]/username/reponame.git
as opposed to
https://github.com/username/reponame.git
To see your repo URL, run:
git remote show origin
You can change the URL with:
git remote set-url origin git+ssh://[email protected]/username/reponame.git
[1] This section incorporates the answer from Eric P
Here is an example to get string/value
public enum Suit
{
Spades = 0x10,
Hearts = 0x11,
Clubs = 0x12,
Diamonds = 0x13
}
private void print_suit()
{
foreach (var _suit in Enum.GetValues(typeof(Suit)))
{
int suitValue = (byte)(Suit)Enum.Parse(typeof(Suit), _suit.ToString());
MessageBox.Show(_suit.ToString() + " value is 0x" + suitValue.ToString("X2"));
}
}
Result of Message Boxes
Spade value is 0x10
Hearts value is 0x11
Clubs value is 0x12
Diamonds value is 0x13
SQL Developer 3.1 fixes this issue. Its an early adopter release at the moment though.
The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.
See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.
But I still don't know why they wrote the spec so that the order matters.
You can use .sortBy
, it will always return an ascending list:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
But you can use the .reverse method to get it descending:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Or when dealing with numbers add a negative sign to the return to descend the list:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Under the hood .sortBy
uses the built in .sort([handler])
:
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]
// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
when you need in a timestamp in seconds, you can use the following:
var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
You have to click and hold until the other icon shows up, then slide the mouse down to the icon.
You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:
insert into batch(batchid, batchname)
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;
or, as a pl-sql script:
variable l_batchid number;
insert into batch(batchid, batchname)
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;
select :l_batchid from dual;
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content"></div>
</body>
</html>
The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
If you're using web components, then they have this as an example:
map.addEventListener('google-map-ready', function(e) {
alert('Map loaded!');
});
You can try with
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
have a try with Flex Paper http://flexpaper.devaldi.com/
it works like scribd
I know this post is older, but haven't seen a solution that provides the actual information, so I want to share what I use for SQL Server 2012 and above. the link below leads to the screenshot showing the information.
First (so no time is wasted):
SQL Server 2000:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')
SQL Server 2005+
The "SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')" is not in use anymore. You can see more details on MSFT documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql?view=sql-server-2017
SQL Server 2005 - 2008R2 you would have to:
Using PowerShell: https://www.ryadel.com/en/sql-server-retrieve-product-key-from-an-existing-installation/
Using TSQL (you would need to know the registry key path off hand): https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-server-registry-transact-sql?view=sql-server-2017
SQL Server 2012+
Now, you can extract SQL Server Licensing information from the SQL Server Error Log, granted it may not be formatted the way you want, but the information is there and can be parsed, along with more descriptive information that you probably didn't expect.
EXEC sp_readerrorlog @p1 = 0
,@p2 = 1
,@p3 = N'licensing'
NOTE: I tried pasting the image directly, but since I am new at stakoverflow we have to follow the link below.
I just thought I'd link this here as the article has most of the answer you're looking for and it's also very interesting
On Windows system I used drivername prefix as well, like:
>>> s = 'c:\\temp\\akarmi.txt'
>>> print(os.path.splitext(s)[0])
c:\temp\akarmi
So because I do not need drive letter or directory name, I use:
>>> print(os.path.splitext(os.path.basename(s))[0])
akarmi
I ran into this problem as well and the the problem with simply hacking the close-button is that I still need access to the standard bootstrap alert-close events.
My solution was to write a small, customisable, jquery plugin that injects a properly formed Bootstrap 3 alert (with or without close button as you need it) with a minimum of fuss and allows you to easily regenerate it after the box is closed.
See https://github.com/davesag/jquery-bs3Alert for usage, tests, and examples.
This is the echo server handling multiple clients... Runs fine and good using Threads
// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server_X_Client {
public static void main(String args[]){
Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try{
ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");
}
while(true){
try{
s= ss2.accept();
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread{
String line=null;
BufferedReader is = null;
PrintWriter os=null;
Socket s=null;
public ServerThread(Socket s){
this.s=s;
}
public void run() {
try{
is= new BufferedReader(new InputStreamReader(s.getInputStream()));
os=new PrintWriter(s.getOutputStream());
}catch(IOException e){
System.out.println("IO error in server thread");
}
try {
line=is.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
System.out.println("Response to Client : "+line);
line=is.readLine();
}
} catch (IOException e) {
line=this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
line=this.getName(); //reused String line for getting thread name
System.out.println("Client "+line+" Closed");
}
finally{
try{
System.out.println("Connection Closing..");
if (is!=null){
is.close();
System.out.println(" Socket Input Stream Closed");
}
if(os!=null){
os.close();
System.out.println("Socket Out Closed");
}
if (s!=null){
s.close();
System.out.println("Socket Closed");
}
}
catch(IOException ie){
System.out.println("Socket Close Error");
}
}//end finally
}
}
Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..
// A simple Client Server Protocol .. Client for Echo Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class NetworkClient {
public static void main(String args[]) throws IOException{
InetAddress address=InetAddress.getLocalHost();
Socket s1=null;
String line=null;
BufferedReader br=null;
BufferedReader is=null;
PrintWriter os=null;
try {
s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
br= new BufferedReader(new InputStreamReader(System.in));
is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
os= new PrintWriter(s1.getOutputStream());
}
catch (IOException e){
e.printStackTrace();
System.err.print("IO Exception");
}
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
String response=null;
try{
line=br.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
response=is.readLine();
System.out.println("Server Response : "+response);
line=br.readLine();
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket read Error");
}
finally{
is.close();os.close();br.close();s1.close();
System.out.println("Connection Closed");
}
}
}
You can do it with Linq, as mamoo showed, but the oldies are good too:
var filteredDataTable = dt.Select(@"EmpId > 2
AND (EmpName <> 'abc' OR EmpName <> 'xyz')
AND EmpName like '%il%'" );
You have to add the jar/war of the module B in the module A and add the classpath in your new spring-module file. Just add this line
spring-moduleA.xml - is a file in module A under the resource folder. By adding this line, it imports all the bean definition from module A to module B.
MODULE B/ spring-moduleB.xml
import resource="classpath:spring-moduleA.xml"/>
<bean id="helloBeanB" class="basic.HelloWorldB">
<property name="name" value="BMVNPrj" />
</bean>
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
I think that what you have to check is:
if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).
dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).
In basic terms synchronous requests wait for the response to be received from the request before it allows any code processing to continue. At first this may seem like a good thing to do, but it absolutely is not.
As mentioned, while the request is in process the browser will halt execution of all script and also rendering of the UI as the JS engine of the majority of browsers is (effectively) single-threaded. This means that to your users the browser will appear unresponsive and they may even see OS-level warnings that the program is not responding and to ask them if its process should be ended. It's for this reason that synchronous JS has been deprecated and you see warnings about its use in the devtools console.
The alternative of asynchronous requests is by far the better practice and should always be used where possible. This means that you need to know how to use callbacks and/or promises in order to handle the responses to your async requests when they complete, and also how to structure your JS to work with this pattern. There are many resources already available covering this, this, for example, so I won't go into it here.
There are very few occasions where a synchronous request is necessary. In fact the only one I can think of is when making a request within the beforeunload
event handler, and even then it's not guaranteed to work.
In summary. you should look to learn and employ the async pattern in all requests. Synchronous requests are now an anti-pattern which cause more issues than they generally solve.
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
If the finality of you code is to get the filtered user, I would invert the for
to evaluate the user
instead of reducing the result array during each iteration.
Here an (untested) example:
function filterUsers (users, filter) {
var result = [];
for (i=0;i<users.length;i++){
for (var prop in filter) {
if (users.hasOwnProperty(prop) && users[i][prop] === filter[prop]) {
result.push(users[i]);
}
}
}
return result;
}
The EclipsePasteAsJavaString plug-in allows you to insert text as a Java string by Ctrl + Shift + V
Paste as usual via Ctrl+V:
some text with tabs
and new
lines
Paste as Java string via Ctrl+Shift+V
"some text\twith tabs\r\n" +
"and new \r\n" +
"lines"
For PyCharm 2018.1 on Mac:
Preferences (?+,), then Editor -> Code Style
:
For PyCharm 2018.3 on Windows:
File -> Settings (Ctrl+Alt+S), then Editor -> Code Style
:
To follow PEP-8 set Hard wrap at
to 80.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
npm i webpack -g
installs webpack globally on your system, that makes it available in terminal window.
How are you generating your data?
See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)
look ?
Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float)
.
You can also call frame.astype(float)
For me, something like Abdelhak Mouaamou's answer works, tested on API level 16 and 27.
Instead of using popupWindow.getContentView().getParent()
and casting the result to View
(which crashes on API level 16 cause there it returns a ViewRootImpl
object which isn't an instance of View
) I just use .getRootView()
which returns a view already, so no casting required there.
Hope it helps someone :)
complete working example scrambled together from other stackoverflow posts, just copy-paste it, e.g., in the onClick listener of a button:
// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
if(inflater == null) {
return;
}
//View popupView = inflater.inflate(R.layout.my_popup_layout, null); // this version gives a warning cause it doesn't like null as argument for the viewRoot, c.f. https://stackoverflow.com/questions/24832497 and https://stackoverflow.com/questions/26404951
View popupView = View.inflate(MyParentActivity.this, R.layout.my_popup_layout, null);
// create the popup window
final PopupWindow popupWindow = new PopupWindow(popupView,
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
true // lets taps outside the popup also dismiss it
);
// do something with the stuff in your popup layout, e.g.:
//((TextView)popupView.findViewById(R.id.textview_popup_helloworld))
// .setText("hello stackoverflow");
// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
// show the popup window
// which view you pass in doesn't matter, it is only used for the window token
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
//popupWindow.setOutsideTouchable(false); // doesn't seem to change anything for me
View container = popupWindow.getContentView().getRootView();
if(container != null) {
WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams)container.getLayoutParams();
p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
if(wm != null) {
wm.updateViewLayout(container, p);
}
}
Two examples that work:
(Example ONE)
// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
for (var l = temp_products_images.length; l--;) {
// 'mark' is the checkbox field
if (temp_products_images[l].mark == true) {
store.state.c_products.products_images.splice(l,1); // THIS WORKS
// this.$delete(store.state.c_products.products_images,l); // THIS ALSO WORKS
}
}
}
(Example TWO)
// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
let l = temp_products_images.length
while (l--)
{
// 'mark' is the checkbox field
if (temp_products_images[l].mark == true) {
store.state.c_products.products_images.splice(l,1); // THIS WORKS
// this.$delete(store.state.c_products.products_images,l); // THIS ALSO WORKS
}
}
}
There is a library available through nuget for dealing with pretty much any well formed CSV (.net) - CsvHelper
Example to map to a class:
var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>();
Example to read individual fields:
var csv = new CsvReader( textReader );
while( csv.Read() )
{
var intField = csv.GetField<int>( 0 );
var stringField = csv.GetField<string>( 1 );
var boolField = csv.GetField<bool>( "HeaderName" );
}
Letting the client drive the file format:
,
is the standard field delimiter, "
is the standard value used to escape fields that contain a delimiter, quote, or line ending.
To use (for example) #
for fields and '
for escaping:
var csv = new CsvReader( textReader );
csv.Configuration.Delimiter = "#";
csv.Configuration.Quote = ''';
// read the file however meets your needs
Let consider that your data are in the file values.txt
and that you want to import them in the database table myTable
then the following query does the job
COPY myTable FROM 'value.txt' (DELIMITER('|'));
https://www.postgresql.org/docs/current/static/sql-copy.html
The argument to remove()
is a filter document, so passing in an empty document means 'remove all':
db.user.remove({})
However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove()
call vs the drop()
call.
More details in the docs.
Yes, of course :)
Take a look at these libraries which help you Never write shell scripts again (Plumbum's motto).
Also, if you want to replace awk, sed and grep with something Python based then I recommend pyp -
"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.
For line chart, I use the following codes.
First create custom style
.boxx{
position: relative;
width: 20px;
height: 20px;
border-radius: 3px;
}
Then add this on your line options
var lineOptions = {
legendTemplate : '<table>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<tr><td><div class=\"boxx\" style=\"background-color:<%=datasets[i].fillColor %>\"></div></td>'
+'<% if (datasets[i].label) { %><td><%= datasets[i].label %></td><% } %></tr><tr height="5"></tr>'
+'<% } %>'
+'</table>',
multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
document.getElementById('legendDiv').innerHTML = myNewChart.generateLegend();
Don't forget to add
<div id="legendDiv"></div>
on your html where do you want to place your legend. That's it!
I'm surprised that everyone in this question claims that std::cout
is way better than printf
, even if the question just asked for differences. Now, there is a difference - std::cout
is C++, and printf
is C (however, you can use it in C++, just like almost anything else from C). Now, I'll be honest here; both printf
and std::cout
have their advantages.
std::cout
is extensible. I know that people will say that printf
is extensible too, but such extension is not mentioned in the C standard (so you would have to use non-standard features - but not even common non-standard feature exists), and such extensions are one letter (so it's easy to conflict with an already-existing format).
Unlike printf
, std::cout
depends completely on operator overloading, so there is no issue with custom formats - all you do is define a subroutine taking std::ostream
as the first argument and your type as second. As such, there are no namespace problems - as long you have a class (which isn't limited to one character), you can have working std::ostream
overloading for it.
However, I doubt that many people would want to extend ostream
(to be honest, I rarely saw such extensions, even if they are easy to make). However, it's here if you need it.
As it could be easily noticed, both printf
and std::cout
use different syntax. printf
uses standard function syntax using pattern string and variable-length argument lists. Actually, printf
is a reason why C has them - printf
formats are too complex to be usable without them. However, std::cout
uses a different API - the operator <<
API that returns itself.
Generally, that means the C version will be shorter, but in most cases it won't matter. The difference is noticeable when you print many arguments. If you have to write something like Error 2: File not found.
, assuming error number, and its description is placeholder, the code would look like this. Both examples work identically (well, sort of, std::endl
actually flushes the buffer).
printf("Error %d: %s.\n", id, errors[id]);
std::cout << "Error " << id << ": " << errors[id] << "." << std::endl;
While this doesn't appear too crazy (it's just two times longer), things get more crazy when you actually format arguments, instead of just printing them. For example, printing of something like 0x0424
is just crazy. This is caused by std::cout
mixing state and actual values. I never saw a language where something like std::setfill
would be a type (other than C++, of course). printf
clearly separates arguments and actual type. I really would prefer to maintain the printf
version of it (even if it looks kind of cryptic) compared to iostream
version of it (as it contains too much noise).
printf("0x%04x\n", 0x424);
std::cout << "0x" << std::hex << std::setfill('0') << std::setw(4) << 0x424 << std::endl;
This is where the real advantage of printf
lies. The printf
format string is well... a string. That makes it really easy to translate, compared to operator <<
abuse of iostream
. Assuming that the gettext()
function translates, and you want to show Error 2: File not found.
, the code to get translation of the previously shown format string would look like this:
printf(gettext("Error %d: %s.\n"), id, errors[id]);
Now, let's assume that we translate to Fictionish, where the error number is after the description. The translated string would look like %2$s oru %1$d.\n
. Now, how to do it in C++? Well, I have no idea. I guess you can make fake iostream
which constructs printf
that you can pass to gettext
, or something, for purposes of translation. Of course, $
is not C standard, but it's so common that it's safe to use in my opinion.
C has lots of integer types, and so does C++. std::cout
handles all types for you, while printf
requires specific syntax depending on an integer type (there are non-integer types, but the only non-integer type you will use in practice with printf
is const char *
(C string, can be obtained using to_c
method of std::string
)). For instance, to print size_t
, you need to use %zd
, while int64_t
will require using %"PRId64"
. The tables are available at http://en.cppreference.com/w/cpp/io/c/fprintf and http://en.cppreference.com/w/cpp/types/integer.
\0
Because printf
uses C strings as opposed to C++ strings, it cannot print NUL byte without specific tricks. In certain cases it's possible to use %c
with '\0'
as an argument, although that's clearly a hack.
Update: It turns out that iostream
is so slow that it's usually slower than your hard drive (if you redirect your program to file). Disabling synchronization with stdio
may help, if you need to output lots of data. If the performance is a real concern (as opposed to writing several lines to STDOUT), just use printf
.
Everyone thinks that they care about performance, but nobody bothers to measure it. My answer is that I/O is bottleneck anyway, no matter if you use printf
or iostream
. I think that printf
could be faster from a quick look into assembly (compiled with clang using the -O3
compiler option). Assuming my error example, printf
example does way fewer calls than the cout
example. This is int main
with printf
:
main: @ @main
@ BB#0:
push {lr}
ldr r0, .LCPI0_0
ldr r2, .LCPI0_1
mov r1, #2
bl printf
mov r0, #0
pop {lr}
mov pc, lr
.align 2
@ BB#1:
You can easily notice that two strings, and 2
(number) are pushed as printf
arguments. That's about it; there is nothing else. For comparison, this is iostream
compiled to assembly. No, there is no inlining; every single operator <<
call means another call with another set of arguments.
main: @ @main
@ BB#0:
push {r4, r5, lr}
ldr r4, .LCPI0_0
ldr r1, .LCPI0_1
mov r2, #6
mov r3, #0
mov r0, r4
bl _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
mov r0, r4
mov r1, #2
bl _ZNSolsEi
ldr r1, .LCPI0_2
mov r2, #2
mov r3, #0
mov r4, r0
bl _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
ldr r1, .LCPI0_3
mov r0, r4
mov r2, #14
mov r3, #0
bl _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
ldr r1, .LCPI0_4
mov r0, r4
mov r2, #1
mov r3, #0
bl _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
ldr r0, [r4]
sub r0, r0, #24
ldr r0, [r0]
add r0, r0, r4
ldr r5, [r0, #240]
cmp r5, #0
beq .LBB0_5
@ BB#1: @ %_ZSt13__check_facetISt5ctypeIcEERKT_PS3_.exit
ldrb r0, [r5, #28]
cmp r0, #0
beq .LBB0_3
@ BB#2:
ldrb r0, [r5, #39]
b .LBB0_4
.LBB0_3:
mov r0, r5
bl _ZNKSt5ctypeIcE13_M_widen_initEv
ldr r0, [r5]
mov r1, #10
ldr r2, [r0, #24]
mov r0, r5
mov lr, pc
mov pc, r2
.LBB0_4: @ %_ZNKSt5ctypeIcE5widenEc.exit
lsl r0, r0, #24
asr r1, r0, #24
mov r0, r4
bl _ZNSo3putEc
bl _ZNSo5flushEv
mov r0, #0
pop {r4, r5, lr}
mov pc, lr
.LBB0_5:
bl _ZSt16__throw_bad_castv
.align 2
@ BB#6:
However, to be honest, this means nothing, as I/O is the bottleneck anyway. I just wanted to show that iostream
is not faster because it's "type safe". Most C implementations implement printf
formats using computed goto, so the printf
is as fast as it can be, even without compiler being aware of printf
(not that they aren't - some compilers can optimize printf
in certain cases - constant string ending with \n
is usually optimized to puts
).
I don't know why you would want to inherit ostream
, but I don't care. It's possible with FILE
too.
class MyFile : public FILE {}
True, variable length argument lists have no safety, but that doesn't matter, as popular C compilers can detect problems with printf
format string if you enable warnings. In fact, Clang can do that without enabling warnings.
$ cat safety.c
#include <stdio.h>
int main(void) {
printf("String: %s\n", 42);
return 0;
}
$ clang safety.c
safety.c:4:28: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
printf("String: %s\n", 42);
~~ ^~
%d
1 warning generated.
$ gcc -Wall safety.c
safety.c: In function ‘main’:
safety.c:4:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("String: %s\n", 42);
^
If you just setting up development env, then use pip freeze file, caz that makes the git repo clean.
Then if doing production deployment, then checkin the whole venv folder. That will make your deployment more reproducible, not need those libxxx-dev packages, and avoid the internet issues.
So there are two repos. One for your main source code, which includes a requirements.txt. And a env repo, which contains the whole venv folder.
If you Navbar code as like as follow:
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../navbar/">Default</a></li>
<li><a href="../navbar-static-top/">Static top</a></li>
<li class="active"><a href="./">Fixed top</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
Then just use the following CSS style to change hover color of your navbar-brand
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: white;
}
So your navbad-brand
hover color will be changed to white. I just tested it and it's working for me correctly.
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.
myString.split("\\D+");
That question solved a quite similar question for me and I thought I should share :
In raw python you can use sum()
to count True
values in a list
:
>>> sum([True,True,True,False,False])
3
But this won't work :
>>> sum([[False, False, True], [True, False, True]])
TypeError...
See type assertions here:
http://golang.org/ref/spec#Type_assertions
I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.
In the case you have classes with same property names, here is a small extension to Praveen's answer:
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation(
"Class: {0}, Property: {1}, Error: {2}",
validationErrors.Entry.Entity.GetType().FullName,
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
Recommended, without jQuery:
Give your <input>
an ID and refer to that. Also, remove the checked=""
part of the <input>
tag if you want the checkbox to start out unticked. Then it's:
document.getElementById("my-checkbox").checked = true;
Pure JavaScript, with no Element ID (#1):
var inputs = document.getElementsByTagName('input');
for(var i = 0; i<inputs.length; i++){
if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){
inputs[i].checked = true;
break;
}
}
Pure Javascript, with no Element ID (#2):
document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;
document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;
Note that the querySelectorAll
and querySelector
methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.
If the element may be missing, you should test for its existence, e.g.:
var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
if (!input) { return; }
With jQuery:
$('.text input[name="copyNewAddrToBilling"]').prop('checked', true);
I did something like that :
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setHeight(30);
textView.setMinimumHeight(30);
/*YOUR CHOICE OF COLOR*/
textView.setTextColor(Color.BLACK);
return view;
}
You must put the both fields textView.setHeight(30); textView.setMinimumHeight(30); or it won't change anything. For me it worked & i had the same problem.
I have successfully run our app, which requires Google Maps API 2, on an AndroVM virtual machine.
AndroVM does not come with Google Maps or Google Play installed, but provides a modified copy of the Cyanogen Gapps archive, which is a set of the proprietary Google apps installed on most Android devices.
The instructions, copied from the AndroVM FAQ:
How can I install Google Apps (including the Market/Play app) ?
- Download Google Apps : gapps-jb-20121011-androvm.tgz [basically the /system directory from the Cyanogen gapps archive without the GoogleTTS app which crashes on AndroVM]
- Untar the gapps…tgz file on your host – you’ll have a system directory created
- Get the management IP address of your AndroVM (“AndroVM Configuration” tool) and do “adb connect x.y.z.t”
- do “adb root”
- reconnect with “adn connect x.y.z.t”
- do “adb remount”
- do “adb push system/ /system/”
Your VM will reboot and you should have google apps including Market/Play.
You won’t have some Google Apps, like Maps, but they can be downloaded from the Market/Play.
So follow those instructions, then just install Google Maps using Google Play!
Some great side effects of using a VM rather than the emulator:
The only bump in the road so far has been lack of multi-touch gestures, which is a bummer for a mapping app! I plan to work around this with a hidden UI mechanism, so not such a huge problem.
You can also run ->select('DISTINCT `field`', FALSE)
and the second parameter tells CI
not to escape the first argument.
With the second parameter as false
, the output would be SELECT DISTINCT `field`
instead of without the second parameter, SELECT `DISTINCT` `field`
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
It evaluates at runtime, so you can switch the type like you can in JavaScript to whatever you want. This is legit:
dynamic i = 12;
i = "text";
And so you can change the type as you need. Use it as a last resort; it i s beneficial, but I heard a lot goes on under the scenes in terms of generated IL and that can come at a performance price.
As an alternative suggestion you may want to look at the ed
command.
man 1 ed
teststr='
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
'
# for in-place file editing use "ed -s file" and replace ",p" with "w"
# cf. http://wiki.bash-hackers.org/howto/edit-ed
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
H
/# *include/i
#include "newfile.h"
.
,p
q
EOF
It's frustrating that what works great in one browser doesn't work in others. The following works in Firefox, but not in Chrome or IE:
<table width="80%">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody style="height:50px; overflow:auto">
<tr>
<td>Cell A1</td>
<td>Cell B1</td>
<td>Cell C1</td>
</tr>
<tr>
<td>Cell A2</td>
<td>Cell B2</td>
<td>Cell C2</td>
</tr>
<tr>
<td>Cell A3</td>
<td>Cell B3</td>
<td>Cell C3</td>
</tr>
</tbody>
</table>
Create a table with column as type json
CREATE TABLE friends ( id serial primary key, data jsonb);
Now let's insert json data
INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');
Now let's make some queries to fetch data
select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;
You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])
name | work
------------+----------------------------
"Arya" | ["Improvements", "Office"]
"Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)
Now to retrieve only the values just use ->>
select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';
Note: if the name includes [
or ]
itself, add two backslashes in front of it, like:
<input name="array[child]" ...
document.querySelector("[name=array\\[child\\]]");
Although this question is quite old, and the accepted response is valid, I find it a bit unconfortable because the content of the HTTP response (HTML, XML, JSON, binary or whatever) becomes mixed with the headers.
I've found a different alternative. CURL provides an option (CURLOPT_HEADERFUNCTION
) to set a callback that will be called for each response header line. The function will receive the curl object and a string with the header line.
You can use a code like this (adapted from TML response):
$cookies = Array();
$ch = curl_init('http://www.google.com/');
// Ask for the callback.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$result = curl_exec($ch);
var_dump($cookies);
function curlResponseHeaderCallback($ch, $headerLine) {
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
$cookies[] = $cookie;
return strlen($headerLine); // Needed by curl
}
This solution has the drawback of using a global variable, but I guess this is not an issue for short scripts. And you can always use static methods and attributes if curl is being wrapped into a class.
Here is my function to rebuild parts of the REFERRER's query string.
If the calling page already had a query string in its own URL, and you must go back to that page and want to send back some, not all, of that $_GET
vars (e.g. a page number).
Example: Referrer's query string was ?foo=1&bar=2&baz=3
calling refererQueryString( 'foo' , 'baz' )
returns foo=1&baz=3"
:
function refererQueryString(/* var args */) {
//Return empty string if no referer or no $_GET vars in referer available:
if (!isset($_SERVER['HTTP_REFERER']) ||
empty( $_SERVER['HTTP_REFERER']) ||
empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) {
return '';
}
//Get URL query of referer (something like "threadID=7&page=8")
$refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY);
//Which values do you want to extract? (You passed their names as variables.)
$args = func_get_args();
//Get '[key=name]' strings out of referer's URL:
$pairs = explode('&',$refererQueryString);
//String you will return later:
$return = '';
//Analyze retrieved strings and look for the ones of interest:
foreach ($pairs as $pair) {
$keyVal = explode('=',$pair);
$key = &$keyVal[0];
$val = urlencode($keyVal[1]);
//If you passed the name as arg, attach current pair to return string:
if(in_array($key,$args)) {
$return .= '&'. $key . '=' .$val;
}
}
//Here are your returned 'key=value' pairs glued together with "&":
return ltrim($return,'&');
}
//If your referer was 'page.php?foo=1&bar=2&baz=3'
//and you want to header() back to 'page.php?foo=1&baz=3'
//(no 'bar', only foo and baz), then apply:
header('Location: page.php?'.refererQueryString('foo','baz'));
Goto windows+R and type %temp% and hit enter. delete the temp folder and files and then try opening the same
I would rather allow users report on bad images. Image recognition development can take too much efforts and time and won't be as much as accurate as human eyes. It's much cheaper to outsource that moderation job.
Take a look at: Amazon Mechanical Turk
"The Amazon Mechanical Turk (MTurk) is one of the suite of Amazon Web Services, a crowdsourcing marketplace that enables computer programs to co-ordinate the use of human intelligence to perform tasks which computers are unable to do."
Use JSON5. Don't use JSON.
With the newer Java versions (i.e., Java 9 and forwards) you can use :
Map.of(1, new Point2D.Double(50, 50), 2, new Point2D.Double(100, 50), ...)
generically:
Map.of(Key1, Value1, Key2, Value2, KeyN, ValueN)
Bear in mind however that Map.of
only works for at most 10
entries, if you have more than 10
entries that you can use :
Map.ofEntries(entry(1, new Point2D.Double(50, 50)), entry(2, new Point2D.Double(100, 50)), ...);
startdate = moment().subtract(1, 'days').startOf('day')
I have the same problem and I followed this Post, it solved my problem.
Follow the following 2 steps:
-O0
-ggdb
flag when compiling your programGood luck!
You need to git add my_project
to stage your new folder. Then git add my_project/*
to stage its contents. Then commit what you've staged using git commit
and finally push your changes back to the source using git push origin master
(I'm assuming you wish to push to the master branch).
import MySQLdb
class Database:
host = 'localhost'
user = 'root'
password = '123'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
The simplest way, based on @nosklo's comment and answer:
import tempfile
tmp = tempfile.mkdtemp()
But if you want to manually control the creation of the directories:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:
from shutil import rmtree
rmtree(tmp, ignore_errors=True)
This is similar to what applications like Google Chrome and Linux systemd
do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.
Use String#next
as the counter.
>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003
next
is relatively 'clever', meaning you can even go for
>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003
Just run this in a console.
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
cinst powershell
It installs the latest version using a Chocolatey repository.
Originally I was using command cinst powershell 3.0.20121027
, but it looks like it later stopped working. Since this question is related to PowerShell 3.0 this was the right way. At this moment (June 26, 2014) cinst powershell
refers to version 3.0 of PowerShell, and that may change in future.
See the Chocolatey PowerShell package page for details on what version will be installed.
Can also try this :
android{
.
.
// to avoid DexIndexOverflowException
dexOptions {
jumboMode true
}
}
Hope it helps someone. Thanks
//Variables
char END_OF_FILE = '#';
char singleCharacter;
//Get a character from the input file
inFile.get(singleCharacter);
//Read the file until it reaches #
//When read pointer reads the # it will exit loop
//This requires that you have a # sign as last character in your text file
while (singleCharacter != END_OF_FILE)
{
cout << singleCharacter;
inFile.get(singleCharacter);
}
//If you need to store each character, declare a variable and store it
//in the while loop.
Maybe I've late a bit, but you really should try to use json library from play framework. You could look at documentation. In current 2.1.1 release you could not separately use it without whole play 2, so dependency will looks like this:
val typesaferepo = "TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases"
val play2 = "play" %% "play" % "2.1.1"
It will bring you whole play framework with all stuff on board.
But as I know guys from Typesafe have a plan to separate it in 2.2 release. So, there is standalone play-json from 2.2-snapshot.
public static void GetSection()
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];
}
run:
mvn -U dependency:go-offline
It works for me.