I use setInterval
to wait for the content loaded. I hope this can help you to solve that problem.
var $audio = $('#audio');
var src = $audio.attr('src');
var a;
a = window.setInterval(function(){
src = $audio.attr('src');
if(src != undefined){
window.clearInterval(a);
$('audio').mediaelementplayer({
audioWidth: '100%'
});
}
}, 0);
Demo : http://jsfiddle.net/NbGBj/
$("document").ready(function(){
$("#upload").change(function() {
alert('changed!');
});
});
Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW
, and is used to define what happens when the user explicitly closes a window using the window manager.
You can use the protocol
method to install a handler for this protocol (the widget must be a Tk
or Toplevel
widget):
Here you have a concrete example:
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:
else if (e.getKeyCode()==38)
{
//Up arrow key code
}
else if (e.getKeyCode()==40)
{
//down arrow key code
}
I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:
public event EventHandler Foo;
If you need more complicated subscription/unsubscription logic, you can do that explicitly:
public event EventHandler Foo
{
add
{
// Subscription logic here
}
remove
{
// Unsubscription logic here
}
}
$("input#myId").bind('keyup', function (e) {
// Do Stuff
});
working in both IE and chrome
import { Component, ElementRef, HostListener, Input } from '@angular/core';
@Component({
selector: 'selector',
template: `
<div>
{{text}}
</div>
`
})
export class AnotherComponent {
public text: String;
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
this.text = "clicked inside";
} else {
this.text = "clicked outside";
}
}
constructor(private eRef: ElementRef) {
this.text = 'no clicks yet';
}
}
Without other external class you can create your personal hack code simply using
event.keyCode
Another help for all, I think is this test page for intercept the keyCode (simply copy and past in new file.html for testing your event).
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
td,th{border:2px solid #aaa;}
</style>
<script type="text/javascript">
var t_cel,tc_ln;
if(document.addEventListener){ //code for Moz
document.addEventListener("keydown",keyCapt,false);
document.addEventListener("keyup",keyCapt,false);
document.addEventListener("keypress",keyCapt,false);
}else{
document.attachEvent("onkeydown",keyCapt); //code for IE
document.attachEvent("onkeyup",keyCapt);
document.attachEvent("onkeypress",keyCapt);
}
function keyCapt(e){
if(typeof window.event!="undefined"){
e=window.event;//code for IE
}
if(e.type=="keydown"){
t_cel[0].innerHTML=e.keyCode;
t_cel[3].innerHTML=e.charCode;
}else if(e.type=="keyup"){
t_cel[1].innerHTML=e.keyCode;
t_cel[4].innerHTML=e.charCode;
}else if(e.type=="keypress"){
t_cel[2].innerHTML=e.keyCode;
t_cel[5].innerHTML=e.charCode;
}
}
window.onload=function(){
t_cel=document.getElementById("tblOne").getElementsByTagName("td");
tc_ln=t_cel.length;
}
</script>
</head>
<body>
<table id="tblOne">
<tr>
<th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
</tr>
<tr>
<th>keyCode</th><td> </td><td> </td><td> </td>
</tr>
<tr>
<th>charCode</th><td> </td><td> </td><td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">CLEAR</button>
</body>
</html>
Here is a working demo so you can try it right here:
var t_cel, tc_ln;_x000D_
if (document.addEventListener) { //code for Moz_x000D_
document.addEventListener("keydown", keyCapt, false);_x000D_
document.addEventListener("keyup", keyCapt, false);_x000D_
document.addEventListener("keypress", keyCapt, false);_x000D_
} else {_x000D_
document.attachEvent("onkeydown", keyCapt); //code for IE_x000D_
document.attachEvent("onkeyup", keyCapt);_x000D_
document.attachEvent("onkeypress", keyCapt);_x000D_
}_x000D_
_x000D_
function keyCapt(e) {_x000D_
if (typeof window.event != "undefined") {_x000D_
e = window.event; //code for IE_x000D_
}_x000D_
if (e.type == "keydown") {_x000D_
t_cel[0].innerHTML = e.keyCode;_x000D_
t_cel[3].innerHTML = e.charCode;_x000D_
} else if (e.type == "keyup") {_x000D_
t_cel[1].innerHTML = e.keyCode;_x000D_
t_cel[4].innerHTML = e.charCode;_x000D_
} else if (e.type == "keypress") {_x000D_
t_cel[2].innerHTML = e.keyCode;_x000D_
t_cel[5].innerHTML = e.charCode;_x000D_
}_x000D_
}_x000D_
window.onload = function() {_x000D_
t_cel = document.getElementById("tblOne").getElementsByTagName("td");_x000D_
tc_ln = t_cel.length;_x000D_
}
_x000D_
td,_x000D_
th {_x000D_
border: 2px solid #aaa;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Untitled</title>_x000D_
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<table id="tblOne">_x000D_
<tr>_x000D_
<th style="border:none;"></th>_x000D_
<th>onkeydown</th>_x000D_
<th>onkeyup</th>_x000D_
<th>onkeypress</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>keyCode</th>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>charCode</th>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
</table>_x000D_
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">CLEAR</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
For handling the event on overing, you can try something like this (it works for me):
In the Html template:
<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
<img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>
In the angular component:
onHovering(eventObject) {
console.log("AlertsBtnComponent.onHovering:");
var regExp = new RegExp(".svg" + "$");
var srcObj = eventObject.target.offsetParent.children["0"];
if (srcObj.tagName == "IMG") {
srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));
}
}
onUnovering(eventObject) {
console.log("AlertsBtnComponent.onUnovering:");
var regExp = new RegExp("_h.svg" + "$");
var srcObj = eventObject.target.offsetParent.children["0"];
if (srcObj.tagName == "IMG") {
srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
}
}
Try this:
var my_condition = true;
var lastSel = $("#my_select option:selected");
$("#my_select").change(function(){
if(my_condition)
{
lastSel.prop("selected", true);
}
});
$("#my_select").click(function(){
lastSel = $("#my_select option:selected");
});
It is an old question but a common one. So let me add this one here.
With arrow function syntax you can achieve it more succinct way since it is lexically binded and can be chained.
An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.
const event_handler = (event, arg) => console.log(event, arg);
el.addEventListener('click', (event) => event_handler(event, 'An argument'));
If you need to clean up the event listener:
// Let's use use good old function sytax
function event_handler(event, arg) {
console.log(event, arg);
}
// Assign the listener callback to a variable
var doClick = (event) => event_handler(event, 'An argument');
el.addEventListener('click', doClick);
// Do some work...
// Then later in the code, clean up
el.removeEventListener('click', doClick);
Here is crazy one-liner:
// You can replace console.log with some other callback function
el.addEventListener('click', (event) => ((arg) => console.log(event, arg))('An argument'));
More docile version: More appropriate for any sane work.
el.addEventListener('click', (event) => ((arg) => {
console.log(event, arg);
})('An argument'));
If you were to inspect the event.target
with firebug or chrome's developer tools you would see for a span element (e.g. the following properties) it will have whatever properties any element has. It depends what the target element is:
event.target: HTMLSpanElement
attributes: NamedNodeMap
baseURI: "file:///C:/Test.html"
childElementCount: 0
childNodes: NodeList[1]
children: HTMLCollection[0]
classList: DOMTokenList
className: ""
clientHeight: 36
clientLeft: 1
clientTop: 1
clientWidth: 1443
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
draggable: false
firstChild: Text
firstElementChild: null
hidden: false
id: ""
innerHTML: "click"
innerText: "click"
isContentEditable: false
lang: ""
lastChild: Text
lastElementChild: null
localName: "span"
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: null
nextSibling: null
nodeName: "SPAN"
nodeType: 1
nodeValue: null
offsetHeight: 38
offsetLeft: 26
offsetParent: HTMLBodyElement
offsetTop: 62
offsetWidth: 1445
onabort: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
onchange: null
onclick: null
oncontextmenu: null
oncopy: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onmousedown: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onreset: null
onscroll: null
onsearch: null
onselect: null
onselectstart: null
onsubmit: null
onwebkitfullscreenchange: null
outerHTML: "<span>click</span>"
outerText: "click"
ownerDocument: HTMLDocument
parentElement: HTMLElement
parentNode: HTMLElement
prefix: null
previousElementSibling: null
previousSibling: null
scrollHeight: 36
scrollLeft: 0
scrollTop: 0
scrollWidth: 1443
spellcheck: true
style: CSSStyleDeclaration
tabIndex: -1
tagName: "SPAN"
textContent: "click"
title: ""
webkitdropzone: ""
__proto__: HTMLSpanElement
Reason:
In jQuery, Click() event binds the element only if the particular element exist in the Html code(after page loads).
It won't consider the future elements which are created dynamically(Future element). Dynamic elements are created with the help of javascript or jquery(not in Html).
So the normal click event won't fire on the dynamic element.
Solution :
To overcome this we should use on() function. on() Can delegate the event for both current and future elements.
delegate(),live() and on() functions have the advantages over the DOM elements.
delegate() and live() are deprecated(Don't use these).
on can only trigger both the existing and future elements.
on can consider all the elements which are present on the whole page.
You should use on function to trigger the event on dynamically(future) created elements.
Remove the code from $(document).ready:
$(".test").click(function(){
alert();
});
Change into:
$(document).on('click','.test',function(){
alert('Clicked');
});
This might do the trick:
$(document).ready(function() {
$("input[type=text]").change(function() {
$(this).data("old", $(this).data("new") || "");
$(this).data("new", $(this).val());
console.log($(this).data("old"));
console.log($(this).data("new"));
});
});
var timeoutId = 0;
$('#myElement').on('mousedown', function() {
timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});
Edit: correction per AndyE...thanks!
Edit 2: using bind now for two events with same handler per gnarf
This will work, make sure your control Event is assigned to this code, it has probably been lost, I also noticed that Double click will only work if the cell is not empty. Try double clicking on a cell with content, don't mess with the designer
private void dgvReport_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//do something
}
Can you place the #ulId in the document prior to the ajax load (with css display: none;), or wrap it in a containing div (with css display: none;), then just load the inner html during ajax page load, that way the scroll event will be linked to the div that is already there prior to the ajax?
Then you can use:
$('#ulId').on('scroll',function(){ console.log('Event Fired'); })
obviously replacing ulId with whatever the actual id of the scrollable div is.
Then set css display: block; on the #ulId (or containing div) upon load?
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
$(".advanced ul li").live('click',function(e){
if(e.target != this) return;
//code
// this code will execute only when you click to li and not to a child
})
You can also get the text resize events, and the zoom factor by injecting a div containing at least a non-breakable space (possibly, hidden), and regularly checking its height. If the height changes, the text size has changed, (and you know how much - this also fires, incidentally, if the window gets zoomed in full-page mode, and you still will get the correct zoom factor, with the same height / height ratio).
DO Not Use EventEmitter for your service communication.
You should use one of the Observable types. I personally like BehaviorSubject.
Simple example:
You can pass initial state, here I passing null
let subject = new BehaviorSubject(null);
When you want to update the subject
subject.next(myObject)
Observe from any service or component and act when it gets new updates.
subject.subscribe(this.YOURMETHOD);
My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:
CREATE EVENT applog_clean_event
ON SCHEDULE
EVERY 1 DAY
STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO
The link provided in the accepted answer shows a nice way to implement the pub/sub system using jQuery, but I found the code somewhat difficult to read, so here is my simplified version of the code:
$(document).on('testEvent', function(e, eventInfo) {
subscribers = $('.subscribers-testEvent');
subscribers.trigger('testEventHandler', [eventInfo]);
});
$('#myButton').on('click', function() {
$(document).trigger('testEvent', [1011]);
});
$('#notifier1').on('testEventHandler', function(e, eventInfo) {
alert('(notifier1)The value of eventInfo is: ' + eventInfo);
});
$('#notifier2').on('testEventHandler', function(e, eventInfo) {
alert('(notifier2)The value of eventInfo is: ' + eventInfo);
});
Given that you are using jQuery, you should absolutely use .which. Yes different browsers set different properties, but jQuery will normalize them and set the .which value in each case. See documetation at http://api.jquery.com/keydown/ it states:
To determine which key was pressed, we can examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so we can reliably use it to retrieve the key code.
I made the following 'universal' cross thread call class for my own purpose, but I think it's worth to share it:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace CrossThreadCalls
{
public static class clsCrossThreadCalls
{
private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);
public static void SetAnyProperty(Control c, string Property, object Value)
{
if (c.GetType().GetProperty(Property) != null)
{
//The given property exists
if (c.InvokeRequired)
{
SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);
c.BeginInvoke(d, c, Property, Value);
}
else
{
c.GetType().GetProperty(Property).SetValue(c, Value, null);
}
}
}
private delegate void SetTextPropertyCallBack(Control c, string Value);
public static void SetTextProperty(Control c, string Value)
{
if (c.InvokeRequired)
{
SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);
c.BeginInvoke(d, c, Value);
}
else
{
c.Text = Value;
}
}
}
And you can simply use SetAnyProperty() from another thread:
CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, "Text", KvaserCanReader.GetSpeed.ToString());
In this example the above KvaserCanReader class runs its own thread and makes a call to set the text property of the lb_Speed label on the main form.
I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.
From http://api.jquery.com/live/
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.
So instead of...
$(".myclass").click( function() {
// do something
});
You can write...
$('body').on('click', 'a.myclass', function() {
// do something
});
This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.
The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:
$('ul').on('click', 'li', function() {
alert( $(this).text() );
});
As long as the ul tag exists this will work (no li elements need exist yet).
foreach (GridViewRow gvr in gvMyGridView.Rows)
{
string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}
You can use this code while doing an iteration with foreach
or for any GridView event like OnRowDataBound
.
Here you can input multiple values for DataKeyNames
by separating with comma ,
. For example, DataKeyNames="ProductID,ItemID,OrderID"
.
You can now access each of DataKeys
by providing its index like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();
You can also use Key Name instead of its index to get the values from DataKeyNames
collection like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();
I separate it, and then use an identity comparison to dictate what is does next.
$("#selectField").change(function(){
if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});
I had a similar problem as you. What I did is that I use something called jQuery. What you then do in the javascript code is this:
$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.
$("#myIframeId").load(function(){
callback($("#myIframeId").html());
$("#myIframeId").remove();
});
});
It seems as you delete you iFrame before you grab the html from it. Now, I do see a problem with that :p
Hope this helps :).
in IE you can get the event object by window.event
in other browsers with no 'use strict'
directive, it is possible to get by arguments.callee.caller.arguments[0]
.
function myFunc(p1, p2, p3) {
var evt = window.event || arguments.callee.caller.arguments[0];
}
If you need this feature for one case or very few cases (your whole application is not requiring this feature). I would rather leave jQuery as is (for many reasons, including being able to update to newer versions, CDN, etc.) and have the following workaround:
// For modern browsers
$(ele).trigger("click");
// Relying on Paul Irish's conditional class names,
// <https://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/>
// (via HTML5 Boilerplate, <https://html5boilerplate.com/>) where
// each Internet Explorer version gets a class of its version
$("html.ie7").length && (function(){
var eleOnClickattr = $(ele).attr("onclick")
eval(eleOnClickattr);
})()
Add a hidden reset button :
<input id="Reset1" type="reset" value="reset" class="hidden" />
Click the reset button to clear the input.
$("#Reset1").click();
I think there is little difference between the two events. To understand this, I created a simple example to manipulation:
XAML
<Window x:Class="LoadedAndContentRendered.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MyWindow"
Title="MainWindow" Height="1000" Width="525"
WindowStartupLocation="CenterScreen"
ContentRendered="Window_ContentRendered"
Loaded="Window_Loaded">
<Grid Name="RootGrid">
</Grid>
</Window>
Code behind
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered");
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded");
}
In this case the message Loaded
appears the first after the message ContentRendered
. This confirms the information in the documentation.
In general, in WPF the Loaded
event fires if the element:
is laid out, rendered, and ready for interaction.
Since in WPF the Window
is the same element, but it should be generally content that is arranged in a root panel (for example: Grid
). Therefore, to monitor the content of the Window
and created an ContentRendered
event. Remarks from MSDN:
If the window has no content, this event is not raised.
That is, if we create a Window
:
<Window x:Class="LoadedAndContentRendered.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MyWindow"
ContentRendered="Window_ContentRendered"
Loaded="Window_Loaded" />
It will only works Loaded
event.
With regard to access to the elements in the Window
, they work the same way. Let's create a Label
in the main Grid
of Window
. In both cases we have successfully received access to Width
:
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
}
As for the Styles
and Templates
, at this stage they are successfully applied, and in these events we will be able to access them.
For example, we want to add a Button
:
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
Button b1 = new Button();
b1.Content = "ContentRendered Button";
RootGrid.Children.Add(b1);
b1.Height = 25;
b1.Width = 200;
b1.HorizontalAlignment = HorizontalAlignment.Right;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
Button b1 = new Button();
b1.Content = "Loaded Button";
RootGrid.Children.Add(b1);
b1.Height = 25;
b1.Width = 200;
b1.HorizontalAlignment = HorizontalAlignment.Left;
}
In the case of Loaded
event, Button
to add to Grid
immediately at the appearance of the Window
. In the case of ContentRendered
event, Button
to add to Grid
after all its content will appear.
Therefore, if you want to add items or changes before load Window
you must use the Loaded
event. If you want to do the operations associated with the content of Window
such as taking screenshots you will need to use an event ContentRendered
.
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
You should now use the .on()
function to bind events.
function fireMouseEvent(obj, evtName) {
if (obj.dispatchEvent) {
//var event = new Event(evtName);
var event = document.createEvent("MouseEvents");
event.initMouseEvent(evtName, true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
obj.dispatchEvent(event);
} else if (obj.fireEvent) {
event = document.createEventObject();
event.button = 1;
obj.fireEvent("on" + evtName, event);
obj.fireEvent(evtName);
} else {
obj[evtName]();
}
}
var obj = document.getElementById("......");
fireMouseEvent(obj, "click");
The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)
Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.
Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!
This work for me
<input type="file" onchange="function();this.value=null;return false;">
You could try a combination of the waitfor and rasterize examples:
/**
* See https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js
*
* Wait until the test condition is true or a timeout occurs. Useful for waiting
* on a server response or for a ui change (fadeIn, etc.) to occur.
*
* @param testFx javascript condition that evaluates to a boolean,
* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
* as a callback function.
* @param onReady what to do when testFx condition is fulfilled,
* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
* as a callback function.
* @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
*/
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()), //< defensive code
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 250); //< repeat check every 250ms
};
var page = require('webpage').create(), system = require('system'), address, output, size;
if (system.args.length < 3 || system.args.length > 5) {
console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
size = system.args[3].split('*');
page.paperSize = size.length === 2 ? {
width : size[0],
height : size[1],
margin : '0px'
} : {
format : system.args[3],
orientation : 'portrait',
margin : {
left : "5mm",
top : "8mm",
right : "5mm",
bottom : "9mm"
}
};
}
if (system.args.length > 4) {
page.zoomFactor = system.args[4];
}
var resources = [];
page.onResourceRequested = function(request) {
resources[request.id] = request.stage;
};
page.onResourceReceived = function(response) {
resources[response.id] = response.stage;
};
page.open(address, function(status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
waitFor(function() {
// Check in the page if a specific element is now visible
for ( var i = 1; i < resources.length; ++i) {
if (resources[i] != 'end') {
return false;
}
}
return true;
}, function() {
page.render(output);
phantom.exit();
}, 10000);
}
});
}
Ben is completely correct in his answer - so keep what he says in mind. What I'm about to tell you isn't a full explanation, but it's a very easy way to remember how e.target
, e.currentTarget
work in relation to mouse events and the display list:
e.target
= The thing under the mouse (as ben says... the thing that triggers the event).
e.currentTarget
= The thing before the dot... (see below)
So if you have 10 buttons inside a clip with an instance name of "btns" and you do:
btns.addEventListener(MouseEvent.MOUSE_OVER, onOver);
// btns = the thing before the dot of an addEventListener call
function onOver(e:MouseEvent):void{
trace(e.target.name, e.currentTarget.name);
}
e.target
will be one of the 10 buttons and e.currentTarget
will always be the "btns" clip.
It's worth noting that if you changed the MouseEvent to a ROLL_OVER or set the property btns.mouseChildren
to false, e.target
and e.currentTarget
will both always be "btns".
I've used the following code a few times and it works sweet:
$("body").click(function(e){
// Check what has been clicked:
var target = $(e.target);
if(target.is("#target")){
// The target was clicked
// Do something...
}
});
I have sort of a hack to do this. Although there doesn't seem to be a way to detect when the soft keyboard has shown or hidden, you can in fact detect when it is about to be shown or hidden by setting an OnFocusChangeListener
on the EditText
that you're listening to.
EditText et = (EditText) findViewById(R.id.et);
et.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View view, boolean hasFocus)
{
//hasFocus tells us whether soft keyboard is about to show
}
});
NOTE: One thing to be aware of with this hack is that this callback is fired immediately when the EditText
gains or loses focus. This will actually fire right before the soft keyboard shows or hides. The best way I've found to do something after the keyboard shows or hides is to use a Handler
and delay something ~ 400ms, like so:
EditText et = (EditText) findViewById(R.id.et);
et.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View view, boolean hasFocus)
{
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
//do work here
}
}, 400);
}
});
cell1.innerHTML="<?php echo $customerDESC; ?>";
cell2.innerHTML="<?php echo $comm; ?>";
cell3.innerHTML="<?php echo $expressFEE; ?>";
cell4.innerHTML="<?php echo $totao_unit_price; ?>";
it is working like a charm, the javascript is inside a php while loop
I use the CellContentClick event, which makes sure the user clicked the checkbox. It DOES fire multiple times even if the user stays in the same cell. The one issue is that the Value does not get updated, and always returns "false" for unchecked. The trick is to use the .EditedFormattedValue property of the cell instead of the Value property. The EditedFormattedValue will track with the check mark and is what one wishes the Value had in it when the CellContentClick is fired.
No need for a timer, no need for any fancy stuff, just use CellContentClick event and inspect the EditedFormattedValue to tell what state the checkbox is going into / just went into. If EditedFormattedValue = true, the checkbox is getting checked.
First of all, this line
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click()
there.
If you read the JavaScript you've got there, document.getElementById('foo')
it's looking for an HTML element with an ID of foo
. You don't have one. Give your image that ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
Alternatively, you could throw the JS in a function and put an onclick in your HTML:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
I suggest you do some reading up on JavaScript and HTML though.
The others are right about needing to move the <img>
above the JS click binding too.
In case you do not want to write all the code you have once written in the function you called. Please use the following code, using jQuery:
$(element).on('click', function () { add_img(); });
Using the div
trick with tab_index="0"
or tabIndex="-1"
works, but any time the user is focusing a view that's not an element, you get an ugly focus-outline on the entire website. This can be fixed by setting the CSS for the div to use outline: none
in the focus.
Here's the implementation with styled components:
import styled from "styled-components"
const KeyReceiver = styled.div`
&:focus {
outline: none;
}
`
and in the App class:
render() {
return (
<KeyReceiver onKeyDown={this.handleKeyPress} tabIndex={-1}>
Display stuff...
</KeyReceiver>
)
Working demo : http://jsfiddle.net/YbLnj/
Documentation: http://jqueryui.com/demos/datepicker/
code
$("#dt").datepicker({
onSelect: function(dateText, inst) {
var date = $(this).val();
var time = $('#time').val();
alert('on select triggered');
$("#start").val(date + time.toString(' HH:mm').toString());
}
});
This is worked for me, anyone can try it
$("#myModal").on("hidden.bs.modal", function () {
for (instance in CKEDITOR.instances)
CKEDITOR.instances[instance].destroy();
$('#myModal .modal-body').html('');
});
you can open ckEditor in Modal window
Wrap code in
window.onload = function(){
// your code
};
The document
and window
are different objects and they have some different events. Using addEventListener()
on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.
For example, there is a "resize"
event on the window
object that is not on the document
object.
For example, the "DOMContentLoaded"
event is only on the document
object.
So basically, you need to know which object receives the event you are interested in and use .addEventListener()
on that particular object.
Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document
object before the window
object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document
over window
when either will work. But, I'd often move even closer to the source and use document.body
or even some closer common parent in the document (if possible).
You need to use named functions.
Also, the click
variable needs to be outside the handler to increment.
var click_count = 0;
function myClick(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', myClick);
}
}
// to add
canvas.addEventListener('click', myClick);
EDIT: You could close around the click_counter
variable like this:
var myClick = (function( click_count ) {
var handler = function(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', handler);
}
};
return handler;
})( 0 );
// to add
canvas.addEventListener('click', myClick);
This way you can increment the counter across several elements.
If you don't want that, and want each one to have its own counter, then do this:
var myClick = function( click_count ) {
var handler = function(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', handler);
}
};
return handler;
};
// to add
canvas.addEventListener('click', myClick( 0 ));
EDIT: I had forgotten to name the handler being returned in the last two versions. Fixed.
Like has been mentioned already the progress field needs the keyword event
public event EventHandler<Progress> progress;
But I don't think that's where you actually want your event. I think you actually want the event in TestClass
. How does the following look? (I've never actually tried setting up static events so I'm not sure if the following will compile or not, but I think this gives you an idea of the pattern you should be aiming for.)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TestClass.progress += SetStatus;
}
private void SetStatus(object sender, Progress e)
{
label1.Text = e.Status;
}
private void button1_Click_1(object sender, EventArgs e)
{
TestClass.Func();
}
}
public class TestClass
{
public static event EventHandler<Progress> progress;
public static void Func()
{
//time consuming code
OnProgress(new Progress("current status"));
// time consuming code
OnProgress(new Progress("some new status"));
}
private static void OnProgress(EventArgs e)
{
if (progress != null)
progress(this, e);
}
}
public class Progress : EventArgs
{
public string Status { get; private set; }
private Progress() {}
public Progress(string status)
{
Status = status;
}
}
I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?
this
is the key (vs evt.target). See example.
document.body.addEventListener("click", function (evt) {_x000D_
console.dir(this);_x000D_
//note evt.target can be a nested element, not the body element, resulting in misfires_x000D_
console.log(evt.target);_x000D_
alert("body clicked");_x000D_
});
_x000D_
<h4>This is a heading.</h4>_x000D_
<p>this is a paragraph.</p>
_x000D_
In my case:
$('#some_link').click(function(event){
event.preventDefault();
});
$('#some_link').unbind('click');
worked as the only method to restore the default action.
As seen over here: https://stackoverflow.com/a/1673570/211514
There are two events on client side as given below.
1. window.onbeforeunload (calls on Browser/tab Close & Page Load)
2. window.onload (calls on Page Load)
On server Side
public JsonResult TestAjax( string IsRefresh)
{
JsonResult result = new JsonResult();
return result = Json("Called", JsonRequestBehavior.AllowGet);
}
On Client Side
<script type="text/javascript">_x000D_
window.onbeforeunload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: { IsRefresh: 'Close' }_x000D_
});_x000D_
};_x000D_
_x000D_
window.onload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: {IsRefresh:'Load'}_x000D_
});_x000D_
};_x000D_
</script>
_x000D_
On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".
On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
window load will wait for all resources to be loaded.
document ready waits for the document to be initialized.
unload well, waits till the document is being unloaded.
the order is: document ready, window load, ... ... ... ... window unload.
always use document ready unless you need to wait for your images to load.
shorthand for document ready:
$(function(){
// yay!
});
I believe this should work for all browsers:
var event;
if (typeof (Event) === 'function') {
event = new Event('resize');
} else { /*IE*/
event = document.createEvent('Event');
event.initEvent('resize', true, true);
}
window.dispatchEvent(event);
$watch
first parameter can also be a function.
$scope.$watch(function watchBothItems() {
return itemsCombinedValue();
}, function whenItemsChange() {
//stuff
});
If your two combined values are simple, the first parameter is just an angular expression normally. For example, firstName and lastName:
$scope.$watch('firstName + lastName', function() {
//stuff
});
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
Call control.invalidate and the paint event will be raised.
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
check this out https://forum.jquery.com/topic/get-index-of-same-class-element-on-click then http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)
to pass the event
object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
Here's a reworking of your sample to get you started.
your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.
the sample below also uses the more standard naming OnXxx for the method that raises the event.
the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.
.
public enum MyEvents{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(MyEvents myEvents)
{
MyEvents = myEvents;
}
public MyEvents MyEvents { get; private set; }
}
public static class MyClass
{
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents myEvents)
{
OnMyEvent(new MyEventArgs(myEvents));
}
protected static void OnMyEvent(MyEventArgs e)
{
if (EventTriggered != null)
{
// Normally the first argument (sender) is "this" - but your example
// uses a static event, so I'm passing null instead.
// EventTriggered(this, e);
EventTriggered(null, e);
}
}
}
For anyone using Ember, this should work as expected:
<iframe onLoad={{action 'actionName'}} frameborder='0' src={{iframeSrc}} />
For Winforms
private void listBox1_DoubleClick(object sender, MouseEventArgs e)
{
int index = this.listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
MessageBox.Show(listBox1.SelectedItem.ToString());
}
}
and
public Form()
{
InitializeComponent();
listBox1.MouseDoubleClick += new MouseEventHandler(listBox1_DoubleClick);
}
that should also, prevent for the event firing if you select an item then click on a blank area.
In a modern browser with ECMAScript 5.1 / Array.prototype.map
, you can also use
jQuery._data(DOCUMENTELEMENT,'events')["EVENT_NAME"].map(function(elem){return elem.handler;});
in your browser console, which will print the source of the handlers, comma delimited. Useful for glancing at what all is running on a particular event.
The INotifyPropertyChanged
interface is implemented with events. The interface has just one member, PropertyChanged
, which is an event that consumers can subscribe to.
The version that Richard posted is not safe. Here is how to safely implement this interface:
public class MyClass : INotifyPropertyChanged
{
private string imageFullPath;
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, e);
}
protected void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
public string ImageFullPath
{
get { return imageFullPath; }
set
{
if (value != imageFullPath)
{
imageFullPath = value;
OnPropertyChanged("ImageFullPath");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Note that this does the following things:
Abstracts the property-change notification methods so you can easily apply this to other properties;
Makes a copy of the PropertyChanged
delegate before attempting to invoke it (failing to do this will create a race condition).
Correctly implements the INotifyPropertyChanged
interface.
If you want to additionally create a notification for a specific property being changed, you can add the following code:
protected void OnImageFullPathChanged(EventArgs e)
{
EventHandler handler = ImageFullPathChanged;
if (handler != null)
handler(this, e);
}
public event EventHandler ImageFullPathChanged;
Then add the line OnImageFullPathChanged(EventArgs.Empty)
after the line OnPropertyChanged("ImageFullPath")
.
Since we have .Net 4.5 there exists the CallerMemberAttribute
, which allows to get rid of the hard-coded string for the property name in the source code:
protected void OnPropertyChanged(
[System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
public string ImageFullPath
{
get { return imageFullPath; }
set
{
if (value != imageFullPath)
{
imageFullPath = value;
OnPropertyChanged();
}
}
}
/**********************Simple Example ***********************/
class Program
{
static void Main(string[] args)
{
Parent p = new Parent();
}
}
////////////////////////////////////////////
public delegate void DelegateName(string data);
class Child
{
public event DelegateName delegateName;
public void call()
{
delegateName("Narottam");
}
}
///////////////////////////////////////////
class Parent
{
public Parent()
{
Child c = new Child();
c.delegateName += new DelegateName(print);
//or like this
//c.delegateName += print;
c.call();
}
public void print(string name)
{
Console.WriteLine("yes we got the name : " + name);
}
}
I am also faced same issue in Dialog.. because I am using setOnKeyListener.. But I set default return true. After change like below code it working fine for me..
mDialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
mDialog.dismiss();
return true;
}
return false;//this line is important
}
});
Here is the focus listener example.
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
}
}
});
sender
refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
EventArgs
is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.
When you implement your own events, use an EventHandler
or EventHandler<T>
as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).
I found this answer and it almost fit my needs. Thanks to SwDevMan81 for the class. I have modified it to allow suppression and resumation of individual methods, and I thought I'd post it here.
// This class allows you to selectively suppress event handlers for controls. You instantiate
// the suppressor object with the control, and after that you can use it to suppress all events
// or a single event. If you try to suppress an event which has already been suppressed
// it will be ignored. Same with resuming; you can resume all events which were suppressed,
// or a single one. If you try to resume an un-suppressed event handler, it will be ignored.
//cEventSuppressor _supButton1 = null;
//private cEventSuppressor SupButton1 {
// get {
// if (_supButton1 == null) {
// _supButton1 = new cEventSuppressor(this.button1);
// }
// return _supButton1;
// }
//}
//private void button1_Click(object sender, EventArgs e) {
// MessageBox.Show("Clicked!");
//}
//private void button2_Click(object sender, EventArgs e) {
// SupButton1.Suppress("button1_Click");
//}
//private void button3_Click(object sender, EventArgs e) {
// SupButton1.Resume("button1_Click");
//}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using System.ComponentModel;
namespace Crystal.Utilities {
public class cEventSuppressor {
Control _source;
EventHandlerList _sourceEventHandlerList;
FieldInfo _headFI;
Dictionary<object, Delegate[]> suppressedHandlers = new Dictionary<object, Delegate[]>();
PropertyInfo _sourceEventsInfo;
Type _eventHandlerListType;
Type _sourceType;
public cEventSuppressor(Control control) {
if (control == null)
throw new ArgumentNullException("control", "An instance of a control must be provided.");
_source = control;
_sourceType = _source.GetType();
_sourceEventsInfo = _sourceType.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
_sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);
_eventHandlerListType = _sourceEventHandlerList.GetType();
_headFI = _eventHandlerListType.GetField("head", BindingFlags.Instance | BindingFlags.NonPublic);
}
private Dictionary<object, Delegate[]> BuildList() {
Dictionary<object, Delegate[]> retval = new Dictionary<object, Delegate[]>();
object head = _headFI.GetValue(_sourceEventHandlerList);
if (head != null) {
Type listEntryType = head.GetType();
FieldInfo delegateFI = listEntryType.GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic);
FieldInfo keyFI = listEntryType.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
FieldInfo nextFI = listEntryType.GetField("next", BindingFlags.Instance | BindingFlags.NonPublic);
retval = BuildListWalk(retval, head, delegateFI, keyFI, nextFI);
}
return retval;
}
private Dictionary<object, Delegate[]> BuildListWalk(Dictionary<object, Delegate[]> dict,
object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI) {
if (entry != null) {
Delegate dele = (Delegate)delegateFI.GetValue(entry);
object key = keyFI.GetValue(entry);
object next = nextFI.GetValue(entry);
if (dele != null) {
Delegate[] listeners = dele.GetInvocationList();
if (listeners != null && listeners.Length > 0) {
dict.Add(key, listeners);
}
}
if (next != null) {
dict = BuildListWalk(dict, next, delegateFI, keyFI, nextFI);
}
}
return dict;
}
public void Resume() {
}
public void Resume(string pMethodName) {
//if (_handlers == null)
// throw new ApplicationException("Events have not been suppressed.");
Dictionary<object, Delegate[]> toRemove = new Dictionary<object, Delegate[]>();
// goes through all handlers which have been suppressed. If we are resuming,
// all handlers, or if we find the matching handler, add it back to the
// control's event handlers
foreach (KeyValuePair<object, Delegate[]> pair in suppressedHandlers) {
for (int x = 0; x < pair.Value.Length; x++) {
string methodName = pair.Value[x].Method.Name;
if (pMethodName == null || methodName.Equals(pMethodName)) {
_sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);
toRemove.Add(pair.Key, pair.Value);
}
}
}
// remove all un-suppressed handlers from the list of suppressed handlers
foreach (KeyValuePair<object, Delegate[]> pair in toRemove) {
for (int x = 0; x < pair.Value.Length; x++) {
suppressedHandlers.Remove(pair.Key);
}
}
//_handlers = null;
}
public void Suppress() {
Suppress(null);
}
public void Suppress(string pMethodName) {
//if (_handlers != null)
// throw new ApplicationException("Events are already being suppressed.");
Dictionary<object, Delegate[]> dict = BuildList();
foreach (KeyValuePair<object, Delegate[]> pair in dict) {
for (int x = pair.Value.Length - 1; x >= 0; x--) {
//MethodInfo mi = pair.Value[x].Method;
//string s1 = mi.Name; // name of the method
//object o = pair.Value[x].Target;
// can use this to invoke method pair.Value[x].DynamicInvoke
string methodName = pair.Value[x].Method.Name;
if (pMethodName == null || methodName.Equals(pMethodName)) {
_sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);
suppressedHandlers.Add(pair.Key, pair.Value);
}
}
}
}
}
}
Five Ways to Wire Up an Event Listener is a great article overviewing the various ways to set up a single event listener. Let me expand that here for multiple listeners.
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//attach an instance of HandleClick to the Button
HandleClick handleClick = new HandleClick();
findViewById(R.id.button1).setOnClickListener(handleClick);
findViewById(R.id.button2).setOnClickListener(handleClick);
}
private class HandleClick implements OnClickListener{
public void onClick(View view) {
switch(view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
}
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(handleClick);
findViewById(R.id.button2).setOnClickListener(handleClick);
}
private OnClickListener handleClick = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
};
}
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff
}
});
}
}
public class main extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void HandleClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
And in xml:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="HandleClick" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="HandleClick" />
I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?
To cater for that possibility, I would do the following:
$(document).ready(function() {
$('#<%=myButton.ClientID %>').click(function() {
// Do client side button click stuff here.
});
});
It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.
If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.
I use zope.event. It's the most bare bones you can imagine. :-) In fact, here is the complete source code:
subscribers = []
def notify(event):
for subscriber in subscribers:
subscriber(event)
Note that you can't send messages between processes, for example. It's not a messaging system, just an event system, nothing more, nothing less.
$(document).on('click', '.selector', function() { /* do stuff */ });
EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.
When you click
on any element(s) matching .selector
, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation()
method -- which would top the bubbling of an event to parent elements.
Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.
This is smart for a few reasons, including performance and memory utilization (in large scale applications)
EDIT:
Obviously, the closest parent element you can listen on is better, and you can use any element in place of document
as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.
return false
in your listener should work in all browsers.
$('orderNowForm').addEvent('submit', function () {
// your code
return false;
}
Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.
The only working solution is How to capture the browser window close event?
From where would you get these values? If they're from the button itself, you could just do
commentbtn.click(function() {
alert(this.id);
});
If they're a variable in the binding scope, you can access them from without
var id = 1;
commentbtn.click(function() {
alert(id);
});
If they're a variable in the binding scope, that might change before the click is called, you'll need to create a new closure
for(var i = 0; i < 5; i++) {
$('#button'+i).click((function(id) {
return function() {
alert(id);
};
}(i)));
}
e= StringVar()
def fileDialog():
filename = filedialog.askopenfilename(initialdir = "/",title = "Select A
File",filetype = (("jpeg","*.jpg"),("png","*.png"),("All Files","*.*")))
e.set(filename)
la = Entry(self,textvariable = e,width = 30).place(x=230,y=330)
butt=Button(self,text="Browse",width=7,command=fileDialog).place(x=430,y=328)
You can actually simplify this by removing the v-on
directives:
<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">
And use the watch
method to listen for the change:
new Vue ({
el: "#app",
data: {
cases: [
{ name: 'case A', status: '1' },
{ name: 'case B', status: '0' },
{ name: 'case C', status: '1' }
],
activeCases: [],
srStatus: ''
},
watch: {
srStatus: function(val, oldVal) {
for (var i = 0; i < this.cases.length; i++) {
if (this.cases[i].status == val) {
this.activeCases.push(this.cases[i]);
alert("Fired! " + val);
}
}
}
}
});
Very easy, this is how I did it.
.directive('blockOnRender', function ($blockUI) {_x000D_
return {_x000D_
restrict: 'A',_x000D_
link: function (scope, element, attrs) {_x000D_
_x000D_
if (scope.$first) {_x000D_
$blockUI.blockElement($(element).parent());_x000D_
}_x000D_
if (scope.$last) {_x000D_
$blockUI.unblockElement($(element).parent());_x000D_
}_x000D_
}_x000D_
};_x000D_
})
_x000D_
Use this:
document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')
I find this shorter and cleaner. Besides, you can iterate through selected items if there are more than one;
$('select').on('change', function () {
var selectedValue = this.selectedOptions[0].value;
var selectedText = this.selectedOptions[0].text;
});
Kinda late, but you need to access the original event, not the jQuery massaged one. Also, since these are multi-touch events, other changes need to be made:
$('#box').live('touchstart', function(e) {
var xPos = e.originalEvent.touches[0].pageX;
});
If you want other fingers, you can find them in other indices of the touches list.
UPDATE FOR NEWER JQUERY:
$(document).on('touchstart', '#box', function(e) {
var xPos = e.originalEvent.touches[0].pageX;
});
Please note that in the jQuery universe this must be implemented differently as of version 1.8. The following release note is from the jQuery blog:
.data(“events”): jQuery stores its event-related data in a data object named (wait for it) events on each element. This is an internal data structure so in 1.8 this will be removed from the user data name space so it won’t conflict with items of the same name. jQuery’s event data can still be accessed via jQuery._data(element, "events")
We do have complete control of the order in which the handlers will execute in the jQuery universe. Ricoo points this out above. Doesn't look like his answer earned him a lot of love, but this technique is very handy. Consider, for example, any time you need to execute your own handler prior to some handler in a library widget, or you need to have the power to cancel the call to the widget's handler conditionally:
$("button").click(function(e){
if(bSomeConditional)
e.stopImmediatePropagation();//Don't execute the widget's handler
}).each(function () {
var aClickListeners = $._data(this, "events").click;
aClickListeners.reverse();
});
After research the issue is that webkit browsers does not fire change event on autocomplete. My solution was to get the autofill class that webkit adds and trigger change event by myself.
setTimeout(function() {
if($('input:-webkit-autofill').length > 0) {
//do some stuff
}
},300)
Here is a link for the issue in chromium. https://bugs.chromium.org/p/chromium/issues/detail?id=636425
1: Prototype.observe
uses Element.addEventListener (see the source code)
2: You can override Element.addEventListener
to remember the added listeners (handy property EventListenerList
was removed from DOM3 spec proposal). Run this code before any event is attached:
(function() {
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
this._addEventListener(a,b,c);
if(!this.eventListenerList) this.eventListenerList = {};
if(!this.eventListenerList[a]) this.eventListenerList[a] = [];
this.eventListenerList[a].push(b);
};
})();
Read all the events by:
var clicks = someElement.eventListenerList.click;
if(clicks) clicks.forEach(function(f) {
alert("I listen to this function: "+f.toString());
});
And don't forget to override Element.removeEventListener
to remove the event from the custom Element.eventListenerList
.
3: the Element.onclick
property needs special care here:
if(someElement.onclick)
alert("I also listen tho this: "+someElement.onclick.toString());
4: don't forget the Element.onclick
content attribute: these are two different things:
someElement.onclick = someHandler; // IDL attribute
someElement.setAttribute("onclick","otherHandler(event)"); // content attribute
So you need to handle it, too:
var click = someElement.getAttribute("onclick");
if(click) alert("I even listen to this: "+click);
The Visual Event bookmarklet (mentioned in the most popular answer) only steals the custom library handler cache:
It turns out that there is no standard method provided by the W3C recommended DOM interface to find out what event listeners are attached to a particular element. While this may appear to be an oversight, there was a proposal to include a property called eventListenerList to the level 3 DOM specification, but was unfortunately been removed in later drafts. As such we are forced to looked at the individual Javascript libraries, which typically maintain a cache of attached events (so they can later be removed and perform other useful abstractions).
As such, in order for Visual Event to show events, it must be able to parse the event information out of a Javascript library.
Element overriding may be questionable (i.e. because there are some DOM specific features like live collections, which can not be coded in JS), but it gives the eventListenerList support natively and it works in Chrome, Firefox and Opera (doesn't work in IE7).
class c1
{
event EventHandler someEvent;
ResetSubscriptions() => someEvent = delegate { };
}
It is better to use delegate { }
than null
to avoid the null ref exception.
I was having this issue when viewing my website on a phone. While I was trying to close the overlay, I was pretty much clicking on anything under the overlay. A solution that I found working for myself is to just add a
tag around the entire overlay
$('html').click(function() {
//Hide the menus if it is visible
});
$('#menu_container').click(function(event){
event.stopPropagation();
});
but you need to keep in mind these things as well. http://css-tricks.com/dangers-stopping-event-propagation/
Here is perhaps a different way for you to achieve this. Pass into the directive both the index and the item and let the directive setup the html in a template:
Demo: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview
html:
<ul id="thumbnails">
<li class="thumbnail" ng-repeat="item in items" options='#my-container' itemdata='item' index="$index">
</li>
</ul>
js directive:
app.directive('thumbnail', [function() {
return {
restrict: 'CA',
replace: false,
transclude: false,
scope: {
index: '=index',
item: '=itemdata'
},
template: '<a href="#"><img src="{{item.src}}" alt="{{item.alt}}" /></a>',
link: function(scope, elem, attrs) {
if (parseInt(scope.index) == 0) {
angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
}
elem.bind('click', function() {
var src = elem.find('img').attr('src');
// call your SmoothZoom here
angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
});
}
}
}]);
You probably would be better off adding a ng-click to the image as pointed out in another answer.
Update
The link for the demo was incorrect. It has been updated to: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview
You can add a helper function that clears event listener for example
function clearEventListener(element) {
const clonedElement = element.cloneNode(true);
element.replaceWith(clonedElement);
return clonedElement;
}
just pass in the element to the function and that's it...
publisher: where the events happen. Publisher should specify which delegate the class is using and generate necessary arguments, pass those arguments and itself to the delegate.
subscriber: where the response happen. Subscriber should specify methods to respond to events. These methods should take the same type of arguments as the delegate. Subscriber then add this method to publisher's delegate.
Therefore, when the event happen in publisher, delegate will receive some event arguments (data, etc), but publisher has no idea what will happen with all these data. Subscribers can create methods in their own class to respond to events in publisher's class, so that subscribers can respond to publisher's events.
Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:
e.cancelBubble = true
Or, you can use the W3C standard for FireFox:
e.stopPropagation();
If you want to get fancy, you can do this:
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}
Here's one way of achieving this. You need to add incremental attribute to your html or it won't work.
window.onload = function() {_x000D_
var tf = document.getElementById('textField');_x000D_
var button = document.getElementById('b');_x000D_
button.disabled = true;_x000D_
var onKeyChange = function textChange() {_x000D_
button.disabled = (tf.value === "") ? true : false;_x000D_
}_x000D_
tf.addEventListener('keyup', onKeyChange);_x000D_
tf.addEventListener('search', onKeyChange);_x000D_
_x000D_
}
_x000D_
<input id="textField" type="search" placeholder="search" incremental="incremental">_x000D_
<button id="b">Go!</button>
_x000D_
Here goes.. Cheers!
function getCookie(n) {
let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
return a ? a[1] : '';
}
Note that I made use of ES6's template strings to compose the regex expression.
I just had an issue where I needed to solve this properly.
Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.
the code I ended up with:
$.each(messages, function(idx, el){
window.setTimeout(function(){
doSomething(el);
},Math.floor(idx+1)*10000);
});
Basically, think of the timeouts as a "timeline" of your script.
This is what we WANT to code:
DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();
This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:
At Runtime 0 : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();
Hope this helps.
Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.
The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:
function foo(doBar)
{
function bar()
{
console.log( 'bar' );
}
function baz()
{
console.log( 'baz' );
}
window.baz = baz;
if ( doBar ) bar();
}
In this example, the baz function will be available for use after the foo
function has been run, as it's overridden window.baz
. The bar function will not be available to any context other than scopes contained within the foo
function.
as a different example:
function Fizz(qux)
{
this.buzz = function(){
console.log( qux );
};
}
The Fizz
function is designed as a constructor so that, when run, it assigns a buzz
function to the newly created object.
You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:
# app/config/parameters.yml
parameters:
ga_tracking: UA-xxxxx-x
# app/config/config.yml
twig:
globals:
ga_tracking: "%ga_tracking%"
Now, the variable ga_tracking is available in all Twig templates:
<p>The google tracking code is: {{ ga_tracking }}</p>
The parameter is also available inside the controllers:
$this->container->getParameter('ga_tracking');
You can also define a service as a global Twig variable (Symfony2.2+):
# app/config/config.yml
twig:
# ...
globals:
user_management: "@acme_user.user_management"
http://symfony.com/doc/current/templating/global_variables.html
If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.
I am almost always dealing with multiple threads and main thread is generally not doing much, so what is most interesting is to dump all the stacks (which is more like the Java's dump). Here is an implementation based on this blog:
import threading, sys, traceback
def dumpstacks(signal, frame):
id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""), threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print "\n".join(code)
import signal
signal.signal(signal.SIGQUIT, dumpstacks)
Yep I would say thirtydot has it, there is no way to do it unless you use a js method. You are talking about a complex set of rendering conditions that you will have to define. e.g. what happens when both cells are getting too big for their apartments you will have to decide who has priority or simply just give them a percentage of the area and if they are overfull they will both take up that area and only if one has whitespace will you stretch your legs in the other cell, either way there is no way to do it with css. Although there are some pretty funky things people do with css that I have not thought of. I really doubt you can do this though.
What's you've got there should be fine to work, but there is no actual "Is Mobile/Tablet" media query so you're always going to be stuck.
There are media queries for common breakpoints , but with the ever changing range of devices they're not guaranteed to work moving forwards.
The idea is that your site maintains the same brand across all sizes, so you should want the styles to cascade across the breakpoints and only update the widths and positioning to best suit that viewport.
To further the answer above, using Modernizr with a no-touch test will allow you to target touch devices which are most likely tablets and smart phones, however with the new releases of touch based screens that is not as good an option as it once was.
Outline: Create two elements: a slider/switch and a trough as a parent of the slider. To toggle the state, switch the slider element between an "on" and an "off" class. In the style for one class, set "left" to 0 and leave "right" the default; for the other class, do the opposite:
<style type="text/css">
.toggleSwitch {
width: ...;
height: ...;
/* add other styling as appropriate to position element */
position: relative;
}
.slider {
background-image: url(...);
position: absolute;
width: ...;
height: ...;
}
.slider.on {
right: 0;
}
.slider.off {
left: 0;
}
</style>
<script type="text/javascript">
function replaceClass(elt, oldClass, newClass) {
var oldRE = RegExp('\\b'+oldClass+'\\b');
elt.className = elt.className.replace(oldRE, newClass);
}
function toggle(elt, on, off) {
var onRE = RegExp('\\b'+on+'\\b');
if (onRE.test(elt.className)) {
elt.className = elt.className.replace(onRE, off);
} else {
replaceClass(elt, off, on);
}
}
</script>
...
<div class="toggleSwitch" onclick="toggle(this.firstChild, 'on', 'off');"><div class="slider off" /></div>
Alternatively, just set the background image for the "on" and "off" states, which is a much easier approach than mucking about with positioning.
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
Here is what I did and it worked perfectly for what I was looking to do:
Dim StatusDate As String
StatusDate = InputBox("What status date do you want to pull?", "Enter Status Date", " ")
If StatusDate = " " Then
MessageBox.Show("You must enter a Status date to continue.")
Exit Sub
ElseIf StatusDate = "" Then
Exit Sub
End If
This key was to set the default value of the input box to be an actual space, so a user pressing just the OK button would return a value of " " while pressing cancel returns ""
From a usability standpoint, the defaulted value in the input box starts highlighted and is cleared when a user types so the experience is no different than if the box had no value.
A very simple solution is to add the database name with your table name like if your DB name is DBMS
and table is info
then it will be DBMS.info
for any query.
If your query is
select * from STUDENTREC where ROLL_NO=1;
it might show an error but
select * from DBMS.STUDENTREC where ROLL_NO=1;
it doesn't because now actually your table is found.
What do I need to do to make this function wait for the result of the promise?
Use async/await
(NOT Part of ECMA6, but
available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN
async function waitForPromise() {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:
async function waitForPromise(): Promise<string> {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
I needed to make a ListView
with items of different colors. I modified Shardul's method a bit and result in this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, colorString) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
textView.setBackgroundColor(assignBackgroundColor(position));
textView.setTextColor(assignTextColor(position));
return textView;
}
};
colorList.setAdapter(adapter);
assignBackgroundColor()
and assignTextColor()
are methods that assign color you want. They can be replaced with int[]
arrays.
As Phil noted, the empty string is treated as a NULL, and NULL is not equal or unequal to anything. If you expect empty strings or NULLs, you'll need to handle those with NVL()
:
DECLARE
str1 varchar2(4000);
str2 varchar2(4000);
BEGIN
str1:='';
str2:='sdd';
-- Provide an alternate null value that does not exist in your data:
IF(NVL(str1,'X') != NVL(str2,'Y')) THEN
dbms_output.put_line('The two strings are not equal');
END IF;
END;
/
Concerning null comparisons:
According to the Oracle 12c documentation on NULLS, null comparisons using IS NULL
or IS NOT NULL
do evaluate to TRUE
or FALSE
. However, all other comparisons evaluate to UNKNOWN
, not FALSE
. The documentation further states:
A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN.
A reference table is provided by Oracle:
Condition Value of A Evaluation
----------------------------------------
a IS NULL 10 FALSE
a IS NOT NULL 10 TRUE
a IS NULL NULL TRUE
a IS NOT NULL NULL FALSE
a = NULL 10 UNKNOWN
a != NULL 10 UNKNOWN
a = NULL NULL UNKNOWN
a != NULL NULL UNKNOWN
a = 10 NULL UNKNOWN
a != 10 NULL UNKNOWN
I also learned that we should not write PL/SQL assuming empty strings will always evaluate as NULL:
Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.
I see you have added an answer to your question in SQL Server 2008 you can also do
SELECT 3 + CRYPT_GEN_RANDOM(1) % 4 /*Random number between 3 and 6*/
FROM ...
A couple of disadvantages of this method are
NEWID()
method but just thought I'd add it as another option.
A simple way is to put tabindex="-1" in the field(s) you don't want to be tabbed to. Eg
<input type="text" tabindex="-1" name="f1">
based on examples above and examples found on other sites, I created a generic procedure and some examples.
'Simple helper procedure to create a dropdown in a cell based on a list of values in a range
'ValueSheetName : the name of the sheet containing the value range
'ValueRangeString : the range on the sheet with name ValueSheetName containing the values for the dropdown
'CreateOnSheetName : the name of the sheet where the dropdown needs to be created
'CreateInRangeString : the range where the dropdown needs to be created
'FieldName As String : a name of the dropdown, will be used in the inputMessage and ErrorMessage
'See example below ExampleCreateDropDown
Public Sub CreateDropDown(ValueSheetName As String, ValueRangeString As String, CreateOnSheetName As String, CreateInRangeString As String, FieldName As String)
Dim ValueSheet As Worksheet
Set ValueSheet = Worksheets(ValueSheetName) 'The sheet containing the values
Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString) 'The range containing the values
Dim CreateOnSheet As Worksheet
Set CreateOnSheet = Worksheets(CreateOnSheetName) 'The sheet containing the values
Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
Dim InputTitle As String: InputTitle = "Please Select a Value"
Dim InputMessage As String: InputMessage = "for " & FieldName
Dim ErrorTitle As String: ErrorTitle = "Please Select a Value"
Dim ErrorMessage As String: ErrorMessage = "for " & FieldName
Dim ShowInput As Boolean: ShowInput = True 'Show input message on hover
Dim ShowError As Boolean: ShowError = True 'Show error message on error
Dim ValidationType As XlDVType: ValidationType = xlValidateList
Dim ValidationAlertStyle As XlDVAlertStyle: ValidationAlertStyle = xlValidAlertStop 'Stop on invalid value
Dim ValidationOperator As XlFormatConditionOperator: ValidationOperator = xlEqual 'Value must be equal to one of the Values from the ValidationFormula1
Dim ValidationFormula1 As Variant: ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address 'Formula referencing the values from the ValueRange
Dim ValidationFormula2 As Variant: ValidationFormula2 = ""
Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub
'An example using the ExampleCreateDropDown
Private Sub ExampleCreateDropDown()
Call CreateDropDown(ValueSheetName:="Test", ValueRangeString:="C1:C5", CreateOnSheetName:="Test", CreateInRangeString:="B1", FieldName:="test2")
End Sub
'The full option function if you need more configurable options
'To create a dropdown in a cell based on a list of values in a range
'Validation: https://msdn.microsoft.com/en-us/library/office/ff840078.aspx
'ValidationTypes: XlDVType https://msdn.microsoft.com/en-us/library/office/ff840715.aspx
'ValidationAlertStyle: XlDVAlertStyle https://msdn.microsoft.com/en-us/library/office/ff841223.aspx
'XlFormatConditionOperator https://msdn.microsoft.com/en-us/library/office/ff840923.aspx
'See example below ExampleCreateDropDownWithValidationInCell
Public Sub CreateDropDownWithValidationInCell(CreateInRange As Range, _
Optional InputTitle As String = "", _
Optional InputMessage As String = "", _
Optional ErrorTitle As String = "", _
Optional ErrorMessage As String = "", _
Optional ShowInput As Boolean = True, _
Optional ShowError As Boolean = True, _
Optional ValidationType As XlDVType = xlValidateList, _
Optional ValidationAlertStyle As XlDVAlertStyle = xlValidAlertStop, _
Optional ValidationOperator As XlFormatConditionOperator = xlEqual, _
Optional ValidationFormula1 As Variant = "", _
Optional ValidationFormula2 As Variant = "")
With CreateInRange.Validation
.Delete
.Add Type:=ValidationType, AlertStyle:=ValidationAlertStyle, Operator:=ValidationOperator, Formula1:=ValidationFormula1, Formula2:=ValidationFormula2
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = InputTitle
.ErrorTitle = ErrorTitle
.InputMessage = InputMessage
.ErrorMessage = ErrorMessage
.ShowInput = ShowInput
.ShowError = ShowError
End With
End Sub
'An example using the CreateDropDownWithValidationInCell
Private Sub ExampleCreateDropDownWithValidationInCell()
Dim ValueSheetName As String: ValueSheetName = "Hidden" 'The sheet containing the values
Dim ValueRangeString As String: ValueRangeString = "C7:C9" 'The range containing the values
Dim CreateOnSheetName As String: CreateOnSheetName = "Test" 'The sheet containing the dropdown
Dim CreateInRangeString As String: CreateInRangeString = "A1" 'The range containing the dropdown
Dim ValueSheet As Worksheet
Set ValueSheet = Worksheets(ValueSheetName)
Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString)
Dim CreateOnSheet As Worksheet
Set CreateOnSheet = Worksheets(CreateOnSheetName)
Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
Dim FieldName As String: FieldName = "Testing Dropdown"
Dim InputTitle As String: InputTitle = "Please Select a value"
Dim InputMessage As String: InputMessage = "for " & FieldName
Dim ErrorTitle As String: ErrorTitle = "Please Select a value"
Dim ErrorMessage As String: ErrorMessage = "for " & FieldName
Dim ShowInput As Boolean: ShowInput = True
Dim ShowError As Boolean: ShowError = True
Dim ValidationType As XlDVType: ValidationType = xlValidateList
Dim ValidationAlertStyle As XlDVAlertStyle: ValidationAlertStyle = xlValidAlertStop
Dim ValidationOperator As XlFormatConditionOperator: ValidationOperator = xlEqual
Dim ValidationFormula1 As Variant: ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address
Dim ValidationFormula2 As Variant: ValidationFormula2 = ""
Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub
I suggest you to use Message Properte from The Exception Object Like below code
try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
//use Console.Write(e.Message); from Console Application
//and use MessageBox.Show(e.Message); from WindowsForm and WPF Application
}
Your UITableViewDelegate
should implement tableView:heightForRowAtIndexPath:
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 20;
}
Swift 5
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.row * 20
}
You will probably want to use NSString
's sizeWithFont:constrainedToSize:lineBreakMode:
method to calculate your row height rather than just performing some silly math on the indexPath :)
I am using Retrofit 1.9 to obtain a XML.
public class ServicioConexionRetrofitXML {
public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
public static final long tiempoMaximoRespuestaSegundos = 60;
public static final long tiempoMaximoLecturaSegundos = 100;
public static final OkHttpClient clienteOkHttp = new OkHttpClient();
private static RestAdapter.Builder builder = new RestAdapter.Builder().
setEndpoint(API_BASE_URL).
setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());
public static <S> S createService(Class<S> serviceClass) {
clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}
If you are using Retrofit 1.9.0 and okhttp 2.6.0, add to your Gradle file.
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.6.0'
// Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
// en conflicto.
compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
exclude group: 'xpp3', module: 'xpp3'
exclude group: 'stax', module: 'stax-api'
exclude group: 'stax', module: 'stax'
}
Note: If you need to fetch a JSON, just remove from code above.
.setConverter(new SimpleXMLConverter())
In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db
The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!
Totally depends on your usage scenario I suppose.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
I have done HTTP Request Both methods GET & POST with JSON Parsing this way:
on viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()
makeGetRequest()
makePostRequest()
}
func makePostRequest(){
let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example-script/"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var stringPost="firstName=James&lastName=Bond" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 60
request.HTTPBody=data
request.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil) {
// Success
println(jsonResult)
let message = jsonResult["Message"] as! NSString
println(message)
}else {
// Failed
println("Failed")
}
})
}
func makeGetRequest(){
var url : String = "http://api.androidhive.info/contacts/"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
request.timeoutInterval = 60
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil) {
// Success
println(jsonResult)
let dataArray = jsonResult["contacts"] as! NSArray;
for item in dataArray { // loop through data items
let obj = item as! NSDictionary
for (key, value) in obj {
println("Key: \(key) - Value: \(value)")
let phone = obj["phone"] as! NSDictionary;
let mobile = phone["mobile"] as! NSString
println(mobile)
let home = phone["home"] as! NSString
println(home)
let office = phone["office"] as! NSString
println(office)
}
}
} else {
// Failed
println("Failed")
}
})
}
Done
I just ran the command with sudo:
sudo pip install numpy
Bear in mind that you will be asked for the user's password. This was tested on macOS High Sierra (10.13)
If you are trying to loop over a cell array and apply something to each element in the cell, check out cellfun
. There's also arrayfun
, bsxfun
, and structfun
which may simplify your program.
I found a very simple method which is more modern and elegant way.
const el = document.querySelector('.m-element');
// To toggle
['class1', 'class2'].map((e) => el.classList.toggle(e));
// To add
['class1', 'class2'].map((e) => el.classList.add(e));
// To remove
['class1', 'class2'].map((e) => el.classList.remove(e));
Good thing is you can extend the class array or use any coming from API easily.
From info gcc
(emphasis mine):
-ansi
In C mode, this is equivalent to
-std=c90
. In C++ mode, it is equivalent to-std=c++98
. This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as theasm
andtypeof
keywords, and predefined macros such as 'unix' and 'vax' that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style//
comments as well as theinline
keyword.
(It uses vax in the example instead of linux because when it was written maybe it was more popular ;-).
The basic idea is that GCC only tries to fully comply with the ISO standards when it is invoked with the -ansi
option.
I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.
In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.
I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:
$(window).bind("pageshow", function() {
var form = $('form');
// let the browser natively reset defaults
form[0].reset();
});
If you are not handling the input
events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change
event yourself (or whatever event you care to handle, including a custom one):
form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');
That must be added after the reset
to do any good.
Make sure that the following are taken care of:
Your import statement & its path
The tag name of your component you specified in the components {....} block
See here - http://my.opera.com/community/forums/topic.dml?id=1319992&t=1331393279&page=1#comment11751402
Essentially:
history.pushState('data', '', 'http://your-domain/path');
You can manipulate the history object to make this work.
It only works on the same domain, but since you're satisfied with using the hash tag approach, that shouldn't matter.
Obviously would need to be cross-browser tested, but since that was posted on the Opera forum I'm safe to assume it would work in Opera, and I just tested it in Chrome and it worked fine.
If you're using a form
you can disable all the autocompletes with,
<form id="Form1" runat="server" autocomplete="off">
This is not how you initialize an array, but for:
The first declaration:
char buf[10] = "";
is equivalent to
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
The second declaration:
char buf[10] = " ";
is equivalent to
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
The third declaration:
char buf[10] = "a";
is equivalent to
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0
. This the case even if the array is declared inside a function.
The error you're seeing means the data you receive from the remote end isn't valid JSON. JSON (according to the specifiation) is normally UTF-8, but can also be UTF-16 or UTF-32 (in either big- or little-endian.) The exact error you're seeing means some part of the data was not valid UTF-8 (and also wasn't UTF-16 or UTF-32, as those would produce different errors.)
Perhaps you should examine the actual response you receive from the remote end, instead of blindly passing the data to json.loads()
. Right now, you're reading all the data from the response into a string and assuming it's JSON. Instead, check the content type of the response. Make sure the webpage is actually claiming to give you JSON and not, for example, an error message that isn't JSON.
(Also, after checking the response use json.load()
by passing it the file-like object returned by opener.open()
, instead of reading all data into a string and passing that to json.loads()
.)
You can try using @RequestBodyParam
@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
...
}
\
is used for escape sequences in programming languages.
\n
prints a newline
\\
prints a backslash
\"
prints "
\t
prints a tabulator
\b
moves the cursor one back
private void buttonHook_Click(object sender, EventArgs e)
{
// Hooks only into specified Keys (here "A" and "B").
// (***) Use this constructor
_globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });
// Hooks into all keys.
// (***) Or this - not both
_globalKeyboardHook = new GlobalKeyboardHook();
_globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}
And then is working fine.
You can use these queries:
select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;
Each of these tables have a grantee
column, you can filter on that in the where criteria:
where grantee = 'A'
To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs
, it also has a table_schema
column.
If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs
, user_sys_privs
, user_role_privs
. They can be queried by a normal non-dba user.
The default in the php.ini for the session.gc_maxlifetime
directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:
http://www.php.net/manual/en/session.configuration.php
You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:
php_value session.gc_maxlifetime "3600"
Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation.
The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.
You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.
take a look at this object reference to learn more:
Hope that helps!
I had this happen in a worksheet today. Neither F9 nor turning on Iterative Calculation made the cells in question update, but double-clicking the cell and pressing Enter did. I searched the Excel Help and found this in the help article titled Change formula recalculation, iteration, or precision:
- CtrlAltF9:
- Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.
- CtrlShiftAltF9:
- Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.
So I tried CtrlShiftAltF9, and sure enough, all of my non-recalculating formulas finally recalculated!
Here is some SQL that actually make sense:
SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
Simple is always better.
This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.
import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]
reduce
is builtin in Python 2.x. In Python 3.x it has been moved to itertools
However the accepted the answer is better.
This has been answered below but answering if you have a list of items that needs to be joined.
My guess: Because Twitter sees the need to support legacy browsers, otherwise they would be using the :before
/ :after
pseudo-elements.
Legacy browsers don't support those pseudo-elements I mentioned, so they need to use an actual HTML element for the icons, and since icons don't have an 'exclusive' tag, they just went with the <i>
tag, and all browsers support that tag.
They could've certainly used a <span>
, just like you are (which is TOTALLY fine), but probably for the reason I mentioned above plus the ones mentioned by Quentin, is also why Bootstrap is using the <i>
tag.
It's a bad practice when you use extra markup for styling reasons, that's why pseudo-elements were invented, to separate content from style... but when you see the need to support legacy browsers, sometimes you're forced to do these kind of things.
PS. The fact that icons start with an 'i' and that there's an <i>
tag, is completely coincidental.
Create the Java code that can receive an argument as a command line argument.
class TestCode{
public static void main(String args[]){
System.out.println("first argument is: "+args[0]);
}
}
Run the program without arguments (press F6).
In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.
If the argument you need to pass is testArgument
, then here in this window pass the argument as application.args=testArgument
.
This will give the output as follows in the same Output window:
first argument is: testArgument
For Maven, the instructions are similar, but change the exec.args
property instead:
exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3
Note: Use single quotes for string parameters that contain spaces.
System.XML handles the encoding for you, so you don't need a method like this.
The "most C++" way to do this would be to use std::fill
.
std::fill(msg, msg + 65546, 0);
I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:
declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
I have found out that in recent versions of IntelliJ IDEA requires Java 1.8 but is not configured by default.
We can change the path or configure from Project Settings
> Project
> Project SDK
here we can edit or add the JDK´s path.
(in my case the path is located in C:\Program Files\Java\jdk1.8.0_102
)
Solutions with cross join and comma won't work if your query has GROUP BY
statement. For such cases you can use subselect:
SELECT (@row_number := @row_number + 1) AS rowNumber, res.*
FROM
(
SELECT SUM(r.amount)
FROM Results r
WHERE username = 1
GROUP BY r.amount
) res
CROSS JOIN (SELECT @row_number := 0) AS dummy
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
Because booleans have two values: true
or false
. Note that these are not strings, but actual boolean literals.
1 and 0 are integers, and there is no reason to confuse things by making them "alternative true" and "alternative false" (or the other way round for those used to Unix exit codes?). With strong typing in Java there should only ever be exactly two primitive boolean values.
EDIT: Note that you can easily write a conversion function if you want:
public static boolean intToBool(int input)
{
if (input < 0 || input > 1)
{
throw new IllegalArgumentException("input must be 0 or 1");
}
// Note we designate 1 as true and 0 as false though some may disagree
return input == 1;
}
Though I wouldn't recommend this. Note how you cannot guarantee that an int
variable really is 0 or 1; and there's no 100% obvious semantics of what one means true. On the other hand, a boolean
variable is always either true
or false
and it's obvious which one means true. :-)
So instead of the conversion function, get used to using boolean
variables for everything that represents a true/false concept. If you must use some kind of primitive text string (e.g. for storing in a flat file), "true" and "false" are much clearer in their meaning, and can be immediately turned into a boolean by the library method Boolean.valueOf.
The script package does exactly what you're looking for: https://atom.io/packages/script
The package's documentation also contains the key mappings, which you can easily customize.
Maybe this is not the answer you needed, but I encountered similar problem, so I decided to put it here.
I needed to convert 500 xml files to UTF8 via Notepad++. Why Notepad++? When I used the option "Encode in UTF8" (many other converters use the same logic) it messed up all special characters, so I had to use "Convert to UTF8" explicitly.
Here some simple steps to convert multiple files via Notepad++ without messing up with special characters (for ex. diacritical marks).
convertToUTF8.py
import os
import sys
from Npp import notepad # import it first!
filePathSrc="C:\\Users\\" # Path to the folder with files to convert
for root, dirs, files in os.walk(filePathSrc):
for fn in files:
if fn[-4:] == '.xml': # Specify type of the files
notepad.open(root + "\\" + fn)
notepad.runMenuCommand("Encoding", "Convert to UTF-8")
# notepad.save()
# if you try to save/replace the file, an annoying confirmation window would popup.
notepad.saveAs("{}{}".format(fn[:-4], '_utf8.xml'))
notepad.close()
After all, run the script
public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
.Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}
The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.
from pyspark.sql import functions as F
df=df.withColumn('new_column',
F.when(F.col('fruit1')==F.col('fruit2'), 1)
.otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
.otherwise(0))
Here is my answer:
Brief: I was using typeorm
as a ORM library. So, to set the query logging level I have used the following option instead of directly setting the logging option as false
.
Solution: File name - ormconfig.ts
{
'type': process.env.DB_DRIVER,
'host': process.env.DB_HOST,
'port': process.env.DB_PORT,
'username': process.env.DB_USER,
'password': process.env.DB_PASS,
'database': process.env.DB_NAME,
'migrations': [process.env.MIGRATIONS_ENTITIES],
'synchronize': false,
'logging': process.env.DB_QUERY_LEVEL,
'entities': [
process.env.ORM_ENTITIES
],
'cli': {
'migrationsDir': 'migrations'
}
}
And, in the envrionment variable set the DB_QUERY_LEVEL
as ["query", "error"].
Result: As a result it will log only when the query has error else it won't.
Ref link: typeorm db query logging doc
Hope this helps! Thanks.
Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0
(0
, 1
, ..., 9
). So in your second loop v[j]
is invalid, when j
is 10
.
This will fix the error:
for(int j = 9;j >= 0;--j)
{
cout << v[j];
}
In general it's better to think about indexes as 0
based, so I suggest you change also your first loop to this:
for(int i = 0;i < 10;++i)
{
v.push_back(i);
}
Also, to access the elements of a container, the idiomatic approach is to use iterators (in this case: a reverse iterator):
for (vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i)
{
std::cout << *i << std::endl;
}
Based on the doc
<div class="row">
<div class="span4 collapse-group">
<h2>Heading</h2>
<p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn" href="#">View details »</a></p>
</div>
</div>
$('.row .btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $collapse = $this.closest('.collapse-group').find('.collapse');
$collapse.collapse('toggle');
});
It may be in options. Here is the identical Java code.
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
WebDriver driver = new ChromeDriver(chromeOptions);
For what it's worth here are the step by step instructions for doing this in an Android device. Should be the same for iOS:
You should then be able to see the SSL files in Charles. If you want to intercept and change the values you can use the "Map Local" tool which is really awesome:
You need the sleep
method of the Thread
class.
public static void sleep (long time)
Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.
Parameters
time
The time to sleep in milliseconds.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ExampleActivity.super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
This should do the trick:
<table width="400" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50" height="40" valign="top" rowspan="3">
<img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
</td>
</tr>
<tr>
<td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
UPDATE: Adjusted code per the comments:
After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.
Here is an example that will NOT WORK:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="300" bgcolor="#252525">
</td>
<td width="300" bgcolor="#454545">
</td>
</tr>
</table>
Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:
<table width="600" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="200" bgcolor="#252525">
</td>
<td width="400" bgcolor="#454545">
</td>
</tr>
<tr>
<td width="600" colspan="2" bgcolor="#353535">
</td>
</tr>
</table>
Not a full tutorial, but I hope that helps steer you in the right direction in the future.
Here is the code you are after:
<table width="900" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="57" height="43" valign="top" rowspan="2">
<img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
<td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
</td>
</tr>
<tr>
<td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
</td>
</tr>
<tr>
<td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
</td>
</tr>
</table>
You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.
You have to understand that FormData::entries()
returns an instance of Iterator
.
Take this example form:
<form name="test" id="form-id">
<label for="name">Name</label>
<input name="name" id="name" type="text">
<label for="pass">Password</label>
<input name="pass" id="pass" type="text">
</form>
and this JS-loop:
<script>
var it = new FormData( document.getElementById('form-id') ).entries();
var current = {};
while ( ! current.done ) {
current = it.next();
console.info( current )
}
</script>
If you pass the -v
flag to the ansible-playbook command, then ansible will show the output on your terminal.
For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.
If you want to remove unique constraints from mysql database table, use alter table with drop index.
Example:
create table unique_constraints(unid int,activity_name varchar(100),CONSTRAINT activty_uqniue UNIQUE(activity_name),primary key (unid));
alter table unique_constraints drop index activty_uqniue;
Where activty_uqniue is UNIQUE constraint for activity_name column.
I've also been successful with this URL structure:
Base URL:
https://calendar.google.com/calendar/r/eventedit?
And let's say this is my event details:
Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)
I'd convert my details into these parameters (URL encoded):
text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York
Example link:
Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:
dates=20200222T150000Z/20200222T163000Z
Example link:
Another solution, similar to Gerbus' solution, but this also works with relative font sizing.
ul {
letter-spacing: -1em; /* Effectively collapses white-space */
}
ul li {
display: inline;
letter-spacing: normal; /* Reset letter-spacing to normal value */
}
Based on audiodude's answer, but simplified by using the built-in CSV library
require 'nokogiri'
require 'csv'
doc = Nokogiri::HTML(table_string)
csv = CSV.open("output.csv", 'w')
doc.xpath('//table//tr').each do |row|
tarray = [] #temporary array
row.xpath('td').each do |cell|
tarray << cell.text #Build array of that row of data.
end
csv << tarray #Write that row out to csv file
end
csv.close
I did wonder if there was any way to take the Nokogiri NodeSet (row.xpath('td')
) and write this out as an array to the csv file in one step. But I could only figure out doing it by iterating over each cell and building the temporary array of each cell's content.
Here it is some code:
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
See more examples in this article, you may need to take a look to impersonation.
Check all the references carefully
For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.
For anyone looking for an Azure solution
SET NOCOUNT ON
CREATE TABLE Numbers (n bigint PRIMARY KEY)
GO
DECLARE @numbers table(number int);
WITH numbers(number) as (
SELECT 1 AS number
UNION all
SELECT number+1 FROM numbers WHERE number<10000
)
INSERT INTO @numbers(number)
SELECT number FROM numbers OPTION(maxrecursion 10000)
INSERT INTO Numbers(n) SELECT number FROM @numbers
Sourced from the sql azure team blog http://azure.microsoft.com/blog/2010/09/16/create-a-numbers-table-in-sql-azure/
Above formula requires a minus sign in the first line: "=IF(A1<-999500000000"
=IF(A1<-999500000000,TEXT(A1,"#,##.#0,,,"" TB"""),
IF(A1<-9995000000,TEXT(A1,"#,##.#0,,,"" GB"""),
IF(A1<-9995000,TEXT(A1,"#,##0,,"" MB"""),
IF(A1<-9995,TEXT(A1,"#,##0,"" KB"""),
IF(A1<-1000,TEXT(A1,"#,##0"" B """),
IF(A1<0,TEXT(A1,"#,##0"" B """),
IF(A1<1000,TEXT(A1,"#,##0"" B """),
IF(A1<999500,TEXT(A1,"#,##0,"" KB"""),
IF(A1<999500000,TEXT(A1,"#,##0,,"" MB"""),
IF(A1<999500000000,TEXT(A1,"#,##.#0,,,"" GB"""),
TEXT(A1,"#,##.#0,,,,"" TB""")))))))))))
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag
wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> **$dte = Get-Date**
PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
PS C:\Windows\system32> **$PastDueDate**
Sunday, March 1, 2020 12:00:00 AM
PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
PS C:\Windows\system32> **$NewDateFormat 03012020**
There're few additional methods available as well e.g.: $dte.AddDays(-45).Day
Store Unique characters in list
Method 1:
uniue_char = list(set('aaabcabccd'))
#['a', 'b', 'c', 'd']
Method 2: By Loop ( Complex )
uniue_char = []
for c in 'aaabcabccd':
if not c in uniue_char:
uniue_char.append(c)
print(uniue_char)
#['a', 'b', 'c', 'd']
You can use the "cookies" npm module, which has a comprehensive set of features.
Documentation and examples at:
https://github.com/jed/cookies
What are native methods in Java and where should they be used?
Once you see a small example, it becomes clear:
Main.java:
public class Main {
public native int intMethod(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().intMethod(2));
}
}
Main.c:
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_intMethod(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and run:
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
Output:
4
Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.
So it is clear that it allows you to:
This could be used to:
with the tradeoff of lower portability.
It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?
Example on GitHub for you to play with.
Four methods using wget, urllib and request.
#!/usr/bin/python
import requests
from StringIO import StringIO
from PIL import Image
import profile as profile
import urllib
import wget
url = 'https://tinypng.com/images/social/website.jpg'
def testRequest():
image_name = 'test1.jpg'
r = requests.get(url, stream=True)
with open(image_name, 'wb') as f:
for chunk in r.iter_content():
f.write(chunk)
def testRequest2():
image_name = 'test2.jpg'
r = requests.get(url)
i = Image.open(StringIO(r.content))
i.save(image_name)
def testUrllib():
image_name = 'test3.jpg'
testfile = urllib.URLopener()
testfile.retrieve(url, image_name)
def testwget():
image_name = 'test4.jpg'
wget.download(url, image_name)
if __name__ == '__main__':
profile.run('testRequest()')
profile.run('testRequest2()')
profile.run('testUrllib()')
profile.run('testwget()')
testRequest - 4469882 function calls (4469842 primitive calls) in 20.236 seconds
testRequest2 - 8580 function calls (8574 primitive calls) in 0.072 seconds
testUrllib - 3810 function calls (3775 primitive calls) in 0.036 seconds
testwget - 3489 function calls in 0.020 seconds
Install Fiddler on your PC and use it as a proxy on your Android device.
Source: http://www.cantoni.org/2013/11/06/capture-android-web-traffic-fiddler
You can use +=
to concatenate your string, seems like no one answered that, which will be readable, and also neat... something like this
var hello = 'hello' +
'world' +
'blah';
can be also written as
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);
I encountered the same problem.
What caused it for me were a bunch of whitespaces (
) that I inserted.
After removing them, the problem was solved.
I believe you need to .f
file as a parameter, not as a command-single-string. same with the "--domain "+i
, which i would split in two elements of the list.
Assuming that:
FORTRAN
executable, ~/
is indeed the correct way for the FORTRAN
executableI would change this line:
subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])
to
subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])
If that doesn't work, you should do a os.path.exists()
for the .f
file, and check that you can launch the FORTRAN
executable without any path, and set the path or system path variable accordingly
[EDIT 6-Mar-2017]
As the exception, detailed in the original post, is a python exception from subprocess
; it is likely that the WinError 2
is because it cannot find FORTRAN
I highly suggest that you specify full path for your executable:
for i in input:
exe = r'c:\somedir\fortrandir\fortran.exe'
fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
subprocess.Popen([exe, fortran_script, "--domain", i])
if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:
for i in input:
exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[EDIT 7-Mar-2017]
The following line is incorrect:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'
I am not sure why you have ~/
as a prefix for every path, don't do that.
for i in input:
exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[2nd EDIT 7-Mar-2017]
I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:
subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)
You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess
command.
To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:
awk '$2 ~ /abc/'
... and if you want to print only a particular column:
awk '$2 ~ /abc/ { print $3 }'
... and for a particular line number:
awk '$2 ~ /abc/ && FNR == 5 { print $3 }'
I was having the same problem.
There is a difference between a Bar chart
and a Stacked Bar chart
As there is a difference between a Line chart
and a Stacked Line chart
.
The stacked one, will not ignore the 0 or blank values, but will show a cumulative value according with the other legends.
Simply right click the graph, click Change Chart Type
and pick a non-stacked chart.
What does res.render do and what does the html file look like?
res.render()
function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.
Answering Edit 2 part.
// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');
// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');
// here you render `orders` template
response.render("orders", {orders: orders_json});
So, the template path is views/
(first part) + orders
(second part) + .ejs
(third part) === views/orders.ejs
Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.
On a side note. If you are using @media queries (such as @media screen (max-width:500px
)) pay particular attention to applying @media query AFTER you are done with normal styles. Because @media query will be crossed out (even though it is more specific) if followed by css that manipulates the same elements. Example:
@media (max-width:750px){
#buy-box {width: 300px;}
}
#buy-box{
width:500px;
}
** width will be 500px and 300px will be crossed out in Developer Tools. **
#buy-box{
width:500px;
}
@media (max-width:750px){
#buy-box {width: 300px;}
}
** width will be 300px and 500px will be crossed out **
Where are you allocating memory for your buffer
? The line where you invoke bzero
invokes undefined behavior since buffer does not point to any valid region of memory.
char *buffer = new char[ BUFFER_SIZE ];
// do processing
// don't forget to release
delete[] buffer;
If you really need to transform a date to a LocalDateTime object, you could use the LocalDate.atStartOfDay(). This will give you a LocalDateTime object at the specified date, having the hour, minute and second fields set to 0:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
Although a bit
late in posting an answer, here is an alternative approach without using margins.
<style>
#divMain { width: 500px; }
#div1 { width: 100px; float: left; background-color: #fcc; }
#div2 { overflow:hidden; background-color: #cfc; }
#div3 { width: 100px; float: right; background-color: #ccf; }
</style>
<div id="divMain">
<div id="div1">
div 1
</div>
<div id="div3">
div 3
</div>
<div id="div2">
div 2<br />bit taller
</div>
</div>
This method works like magic, but here is an explanation :)\
How about this? Here you split the array using the length you want to have.
a = np.random.randint(0,10,[4,4])
a
Out[27]:
array([[1, 5, 8, 7],
[3, 2, 4, 0],
[7, 7, 6, 2],
[7, 4, 3, 0]])
a[0:2,:]
Out[28]:
array([[1, 5, 8, 7],
[3, 2, 4, 0]])
a[2:4,:]
Out[29]:
array([[7, 7, 6, 2],
[7, 4, 3, 0]])
The problem is caused by your #grid
having a width:1140px
.
You need to set a min-width:1140px
on the body
.
This will stop the body
from getting smaller than the #grid
. Remove width:100%
as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/
html, body{
margin:0;
padding:0;
min-width: 1140px; /* this is the important part*/
}
#grid-container{
background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
width:1140px;
margin:0px auto;
}
I found that the only option that worked for me was
font-size:0;
I was also using overflow
and white-space: nowrap;
float: left;
seems to mess things up
To go up a directory in a link, use ..
. This means "go up one directory", so your link will look something like this:
<a href="../index.html">Home</a>
If it's only about getting the number of records (rows) I'd suggest using:
SELECT TABLE_ROWS
FROM information_schema.tables
WHERE table_name='the_table_you_want' -- Can end here if only 1 DB
AND table_schema = DATABASE(); -- See comment below if > 1 DB
(at least for MySQL) instead.
Check the FIREWALL, to allow the connection at the server from your client. By allowing Domain network or create rule.
What worked for me was following : (eclipse 3.3.6 Subclipse 2.4)
encoding/json
packagejust for example:
package main
import (
"fmt"
"encoding/json"
)
type MyAddress struct {
House string
School string
}
type Student struct {
Id int64
Name string
Scores float32
Address MyAddress
Labels []string
}
func Test() {
dict := make(map[string]interface{})
dict["id"] = 201902181425 // int
dict["name"] = "jackytse" // string
dict["scores"] = 123.456 // float
dict["address"] = map[string]string{"house":"my house", "school":"my school"} // map
dict["labels"] = []string{"aries", "warmhearted", "frank"} // slice
jsonbody, err := json.Marshal(dict)
if err != nil {
// do error check
fmt.Println(err)
return
}
student := Student{}
if err := json.Unmarshal(jsonbody, &student); err != nil {
// do error check
fmt.Println(err)
return
}
fmt.Printf("%#v\n", student)
}
func main() {
Test()
}
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>
<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
$(document).ready(function()
{
$('.FOO').live("click", function (){alert("It Works!")});
var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
autoOpen: false,
tite: 'Basic Dialog'
});
$('#theButton').click(function()
{
$dialog.dialog('open');
return('false');
});
$('#CUSTOM').click(function(){
//$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
var button = document.createElement("input");
button.setAttribute('class','FOO');
button.setAttribute('type','button');
button.setAttribute('value','CLICKMEE');
$('#container').append(button);
});
/* $('#FOO').click(function(){
alert("It Works!");
}); */
});
</script>
</body>
</html>
CSS:
/**default page CSS:**/
::selection { background: #d1d0c3; color: #393729; }
*::-moz-selection { background: #d1d0c3; color: #393729; }
/**for readonly input**/
input[readonly='readonly']:focus { border-color: #ced4da; box-shadow: none; }
input[readonly='readonly']::selection { background: none; color: #000; }
input[readonly='readonly']::-moz-selection { background: none; color: #000; }
HTML:
<input type="text" value="12345" id="readCaptch" readonly="readonly" class="form-control" />
live Example: https://codepen.io/alpesh88ww/pen/mdyZBmV
also you can see why i was done!! (php captcha): https://codepen.io/alpesh88ww/pen/PoYeZVQ
Primary diagnosis: SQLite is unable to open that file for some reason.
Checking the obvious reasons why, and in approximate order that I recommend checking:
/tmp
full? (You're on Unix, so use df /tmp
to find out.)/tmp/cer
directory have “odd” permissions? (SQLite needs to be able to create additional files in it in order to handle things like the commit log.)/tmp
is virtually always on the right sort of FS so it's probably not that — but it's still not recommended.)If you're not on the same machine, it's quite possible that the production system doesn't have a /tmp/cer
directory. Obvious to fix that first. Similarly, if you're on the same machine but running as different users, you're likely to have permissions/ownership problems. Disk space is another serious gotcha, but less likely. I don't think it's the last three, but they're worth checking if the more obvious deployment problems are sorted. If it's none of the above, you've hit an exotic problem and will have to report much more info (it might even be a bug in SQLite, but knowing the developers of it, I believe that to be quite unlikely).
1) use for tommorow's date startDate: '+1d'
2) use for yesterday's date startDate: '-1d'
3) use for today's date startDate: new Date()
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
For the lazy, use git log --stat
.
This Bootstrap listener is to start up and shut down Spring's root WebApplicationContext. As a web application can have multiple dispatcher servlet and each having its own application context containing controllers, view resolver, handler mappings etc But you might want to have service beans, DAO beans in root application context and want to use in all child application context(application context created by dispatcher servlets).
2nd use of this listener is when you want to use spring security.
If Perl 5.10+ is not an option, here is a quick and dirty approximation. It's not exactly the same, since say has some magic when its first arg is a handle, but for printing to STDOUT:
sub say {print @_, "\n"}
say 'hello';
What I use (and it's been working great) is a "templates" directory and a "static" directory. I place all my .html files/Flask templates inside the templates directory, and static contains CSS/JS. render_template works fine for generic html files to my knowledge, regardless of the extent at which you used Flask's templating syntax. Below is a sample call in my views.py file.
@app.route('/projects')
def projects():
return render_template("projects.html", title = 'Projects')
Just make sure you use url_for() when you do want to reference some static file in the separate static directory. You'll probably end up doing this anyways in your CSS/JS file links in html. For instance...
<script src="{{ url_for('static', filename='styles/dist/js/bootstrap.js') }}"></script>
Here's a link to the "canonical" informal Flask tutorial - lots of great tips in here to help you hit the ground running.
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
Just saying: numpy
has this too. So no need to import math
if you already did import numpy as np
:
>>> np.exp(1)
2.718281828459045
Here's another extension, this time in Scala.
customerQuery.getSingleOrNone match {
case Some(c) => // ...
case None => // ...
}
With this pimp:
import javax.persistence.{NonUniqueResultException, TypedQuery}
import scala.collection.JavaConversions._
object Implicits {
class RichTypedQuery[T](q: TypedQuery[T]) {
def getSingleOrNone : Option[T] = {
val results = q.setMaxResults(2).getResultList
if (results.isEmpty)
None
else if (results.size == 1)
Some(results.head)
else
throw new NonUniqueResultException()
}
}
implicit def query2RichQuery[T](q: TypedQuery[T]) = new RichTypedQuery[T](q)
}
For me the following command just worked:
aws s3 mv s3://bucket/data s3://bucket/old_data --recursive
Doesn't look like you are using the correct overload of ActionLink. Try this:-
<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>
This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-
<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>
Make sure your current directory (at the time of crash -- server
may change directories) is writable. If the server calls setuid
, the directory has to be writable by that user.
Also check /proc/sys/kernel/core_pattern
. That may redirect core dumps to another directory, and that directory must be writable. More info here.
My workaround is to set the iframe the height/width well over any anticipated source page size in CSS & the background
property to transparent
.
In the iframe set allow-transparency
to true
and scrolling
to no
.
The only thing visible will be whatever source file you use. It works in IE8, Firefox 3, & Safari.
You could use Jquery indeed or plain good old javascript:
var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";
You put this in a function that you call on a setTimeout until the desired opacity is reached
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
Expanding on Chris and Migol`s answer with a code sample.
Using an array
Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");
Using a generic list. Under the hood the List<T> class uses an array for storage but does so in a fashion that allows it to grow effeciently.
List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];
UltimateSAML SSO is an OASIS SAML v1.x and v2.0 specifications compliant .NET toolkit. It offers an elegant and easy way to add support for Single Sign-On and Single-Logout SAML to your ASP.NET, ASP.NET MVC, ASP.NET Core, Desktop, and Service applications. The lightweight library helps you provide SSO access to cloud and intranet websites using a single credentials entry.
Map.keys()
returns a MapIterator
object which can be converted to Array
using Array.from
:
let keys = Array.from( myMap.keys() );
// ["a", "b"]
EDIT: you can also convert iterable object to array using spread syntax
let keys =[ ...myMap.keys() ];
// ["a", "b"]
If you are talking about actually compressing the text not just shortening then Deflate/gzip (wrapper around gzip), zip work well for smaller files and text. Other algorithms are highly efficient for larger files like bzip2 etc.
Wikipedia has a list of compression times. (look for comparison of efficiency)
Name | Text | Binaries | Raw images
-----------+--------------+---------------+-------------
7-zip | 19% in 18.8s | 27% in 59.6s | 50% in 36.4s
bzip2 | 20% in 4.7s | 37% in 32.8s | 51% in 20.0s
rar (2.01) | 23% in 30.0s | 36% in 275.4s | 58% in 52.7s
advzip | 24% in 21.1s | 37% in 70.6s | 57& in 41.6s
gzip | 25% in 4.2s | 39% in 23.1s | 60% in 5.4s
zip | 25% in 4.3s | 39% in 23.3s | 60% in 5.7s
element.style
comes from the markup.
<li style="display: none;">
Just remove the style
attribute from the HTML.
As already recommended, you can use tree
. But for using it together with restructured text some additional parameters were required.
The standard tree
output will not be printed if your're using pandoc
to produce pdf.
tree --dirsfirst --charset=ascii /path/to/directory
will produce a nice ASCII
tree that can be integrated into your document like this:
.. code::
.
|-- ContentStore
| |-- de-DE
| | |-- art.mshc
| | |-- artnoloc.mshc
| | |-- clientserver.mshc
| | |-- noarm.mshc
| | |-- resources.mshc
| | `-- windowsclient.mshc
| `-- en-US
| |-- art.mshc
| |-- artnoloc.mshc
| |-- clientserver.mshc
| |-- noarm.mshc
| |-- resources.mshc
| `-- windowsclient.mshc
`-- IndexStore
|-- de-DE
| |-- art.mshi
| |-- artnoloc.mshi
| |-- clientserver.mshi
| |-- noarm.mshi
| |-- resources.mshi
| `-- windowsclient.mshi
`-- en-US
|-- art.mshi
|-- artnoloc.mshi
|-- clientserver.mshi
|-- noarm.mshi
|-- resources.mshi
`-- windowsclient.mshi
JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,
<customer id="100">
<age>29</age>
<name>mkyong</name>
</customer>
Create necessary model class(es):
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
Try to unmarshal:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));
Check results, fix bugs!
This is my solution that adjusts the height automatically:
function growDiv() {_x000D_
var growDiv = document.getElementById('grow');_x000D_
if (growDiv.clientHeight) {_x000D_
growDiv.style.height = 0;_x000D_
} else {_x000D_
var wrapper = document.querySelector('.measuringWrapper');_x000D_
growDiv.style.height = wrapper.clientHeight + "px";_x000D_
}_x000D_
document.getElementById("more-button").value = document.getElementById("more-button").value == 'Read more' ? 'Read less' : 'Read more';_x000D_
}
_x000D_
#more-button {_x000D_
border-style: none;_x000D_
background: none;_x000D_
font: 16px Serif;_x000D_
color: blue;_x000D_
margin: 0 0 10px 0;_x000D_
}_x000D_
_x000D_
#grow input:checked {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
#more-button:hover {_x000D_
color: black;_x000D_
}_x000D_
_x000D_
#grow {_x000D_
-moz-transition: height .5s;_x000D_
-ms-transition: height .5s;_x000D_
-o-transition: height .5s;_x000D_
-webkit-transition: height .5s;_x000D_
transition: height .5s;_x000D_
height: 0;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<input type="button" onclick="growDiv()" value="Read more" id="more-button">_x000D_
_x000D_
<div id='grow'>_x000D_
<div class='measuringWrapper'>_x000D_
<div class="text">Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit_x000D_
amet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</div>_x000D_
</div>_x000D_
</div>
_x000D_
I used the workaround that r3bel posted: Can you use CSS3 to transition from height:0 to the variable height of content?
This helped me:
<p>Date/Time: <span id="datetime"></span></p><script>var dt = new Date();
document.getElementById("datetime").innerHTML=dt.toLocaleString();</script>
I look at this a few times at the end decided with EF implementation
A bit modified for SqlConnection
public static void ExecuteSqlScript(this SqlConnection sqlConnection, string sqlBatch)
{
// Handle backslash utility statement (see http://technet.microsoft.com/en-us/library/dd207007.aspx)
sqlBatch = Regex.Replace(sqlBatch, @"\\(\r\n|\r|\n)", string.Empty);
// Handle batch splitting utility statement (see http://technet.microsoft.com/en-us/library/ms188037.aspx)
var batches = Regex.Split(
sqlBatch,
string.Format(CultureInfo.InvariantCulture, @"^\s*({0}[ \t]+[0-9]+|{0})(?:\s+|$)", BatchTerminator),
RegexOptions.IgnoreCase | RegexOptions.Multiline);
for (int i = 0; i < batches.Length; ++i)
{
// Skip batches that merely contain the batch terminator
if (batches[i].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase) ||
(i == batches.Length - 1 && string.IsNullOrWhiteSpace(batches[i])))
{
continue;
}
// Include batch terminator if the next element is a batch terminator
if (batches.Length > i + 1 &&
batches[i + 1].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase))
{
int repeatCount = 1;
// Handle count parameter on the batch splitting utility statement
if (!string.Equals(batches[i + 1], BatchTerminator, StringComparison.OrdinalIgnoreCase))
{
repeatCount = int.Parse(Regex.Match(batches[i + 1], @"([0-9]+)").Value, CultureInfo.InvariantCulture);
}
for (int j = 0; j < repeatCount; ++j)
{
var command = sqlConnection.CreateCommand();
command.CommandText = batches[i];
command.ExecuteNonQuery();
}
}
else
{
var command = sqlConnection.CreateCommand();
command.CommandText = batches[i];
command.ExecuteNonQuery();
}
}
}
The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:
#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
static_cast<std::ostringstream&>( \
std::ostringstream().flush() << tokens \
).str() \
/**/
Now you can format strings like this:
int main() {
int i = 123;
std::string message = MAKE_STRING("i = " << i);
std::cout << message << std::endl; // prints: "i = 123"
}
function positive_number($number)
{
if ($number < 0) {
$number *= -1;
}
return $number;
}
You can do this by using JQuery.
For example ,
<a href="your URL" id="navigate"> click here </a>
Your JQuery
will be,
$(document).ready(function(){
$('a').on('mousedown', stopNavigate);
$('a').on('mouseleave', function () {
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
});
});
function stopNavigate(){
$(window).off('beforeunload');
}
And to get the Leave message alert will be,
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
$(window).on('unload', function(){
logout();
});
This solution works in all browsers and I have tested it.
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html
When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html
Each of these run in different security zones on IE.
If the backup wasn't created in the default location, you can use this T-SQL (run this in SSMS) to find the file path for the most recent backup for all DBs on your SQL Server instance:
SELECT DatabaseName = x.database_name,
LastBackupFileName = x.physical_device_name,
LastBackupDatetime = x.backup_start_date
FROM ( SELECT bs.database_name,
bs.backup_start_date,
bmf.physical_device_name,
Ordinal = ROW_NUMBER() OVER( PARTITION BY bs.database_name ORDER BY bs.backup_start_date DESC )
FROM msdb.dbo.backupmediafamily bmf
JOIN msdb.dbo.backupmediaset bms ON bmf.media_set_id = bms.media_set_id
JOIN msdb.dbo.backupset bs ON bms.media_set_id = bs.media_set_id
WHERE bs.[type] = 'D'
AND bs.is_copy_only = 0 ) x
WHERE x.Ordinal = 1
ORDER BY DatabaseName;
Is there a way to find how many values an array has?
Yes!
Try sizeof(array)/sizeof(array[0])
Detecting whether or not I've reached the end of an array would also work.
I dont see any way for this unless your array is an array of characters (i.e string).
P.S : In C++ always use std::vector
. There are several inbuilt functions and an extended functionality.
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
Simple answer is you can't update an interval of already created timer. (There is only two functions setInterval/setTimer
and clearInterval/clearTimer
, so having a timerId
you can only deactivate it.) But you can made some workarounds. Take a look at this github repo.
You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ----
to -----BEGIN RSA PUBLIC KEY-----
and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).
This article has a good explanation about both formats.
What you get in an RSA PUBLIC KEY
is closer to the content of a PUBLIC KEY
, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY
also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse
and -strparse 19
, as described in this answer.
EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY
structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER
:
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
265:d=1 hl=2 l= 3 prim: INTEGER :010001
To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:
The "ssh-rsa" key format has the following specific encoding: string "ssh-rsa" mpint e mpint n
For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61
. The first four bytes (00 00 00 07
) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61
=ssh-rsa
, followed by the exponent of length 1 (00 00 00 01 25
) and the modulus of length 256 (00 00 01 00 7f ...
).
If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table
, display:table-row
, and display:table-cell
.
There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.
Try this instead:
<style>
DIV.table
{
display:table;
}
FORM.tr, DIV.tr
{
display:table-row;
}
SPAN.td
{
display:table-cell;
}
</style>
...
<div class="table">
<form class="tr" method="post" action="blah.html">
<span class="td"><input type="text"/></span>
<span class="td"><input type="text"/></span>
</form>
<div class="tr">
<span class="td">(cell data)</span>
<span class="td">(cell data)</span>
</div>
...
</div>
The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.
The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.
Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.
Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group
, table-row-group
and table-footer-group
respectively.
NOTE: The only thing you cannot do with this method is colspan.
Check out this illustration: http://jsfiddle.net/ZRQPP/
Keep in mind that international users may be using a decimal separator other than .
in which case values can get mixed up or just become nil when using intValue
on a string.
For example, in the UK 1.23
is written 1,23
, so the number 1.777
would be input by user as 1,777
, which, as .intValue
, will be 1777
not 1
(truncated).
I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).
#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)
That depends on the nature of the information you want to return.
If it is a single integer value, you can use the return
statement
create proc myproc
as
begin
return 1
end
go
declare @i int
exec @i = myproc
If you have a non integer value, or a number of scalar values, you can use output parameters
create proc myproc
@a int output,
@b varchar(50) output
as
begin
select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output
If you want to return a dataset, you can use insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare @t table (name varchar(100))
insert @t (name)
exec myproc
You can even return a cursor but that's just horrid so I shan't give an example :)
The HTTP Content-Type for .ogg should be application/ogg (video/ogg for .ogv) and for .mp4 it should be video/mp4. You can check using the Web Sniffer.
Can't comment on Susam Pal's answer but if you're dealing with spaces, I'd surround with quotes:
for f in *.jpg; do mv "$f" "`echo $f | sed s/\ /\-/g`"; done;
I think this is what you want:
>>> def twoDigitHex( number ):
... return '%02x' % number
...
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'
What do you want to fade? The background
or color
attribute?
Currently you're changing the background color, but telling it to transition the color property. You can use all
to transition all properties.
.clicker {
-moz-transition: all .2s ease-in;
-o-transition: all .2s ease-in;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
background: #f5f5f5;
padding: 20px;
}
.clicker:hover {
background: #eee;
}
Otherwise just use transition: background .2s ease-in
.
In my project I use following code:
$('#attribute').select2();
$('#attribute').bind('change', function(){
var $options = $();
for (var i in data) {
$options = $options.add(
$('<option>').attr('value', data[i].id).html(data[i].text)
);
}
$('#value').html($options).trigger('change');
});
Try to comment out the select2 part. The rest of the code will still work.
You have to override CLLocationManager.didUpdateLocations
(part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last{
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
}
NOTE: If your target is iOS 8 or above, you must include the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
key in your Info.plist to get the location services to work.
You say that if int(splitLine[0]) > int(lastUnix):
is causing the trouble, but you don't actually show anything which suggests that.
I think this line is the problem instead:
print 'Pulled', + stock
Do you see why this line could cause that error message? You want either
>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA
or
>>> print 'Pulled ' + stock
Pulled AAAA
not
>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
File "<ipython-input-5-7c26bb268609>", line 1, in <module>
print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'
You're asking Python to apply the +
symbol to a string like +23
makes a positive 23, and she's objecting.
You forgot to set the width of the border! Change border: red;
to border:1px solid red;
Here the full code to get the circle:
.circle {_x000D_
background-color:#fff;_x000D_
border:1px solid red; _x000D_
height:100px;_x000D_
border-radius:50%;_x000D_
-moz-border-radius:50%;_x000D_
-webkit-border-radius:50%;_x000D_
width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
Sorting HashMap by Value:
As others have pointed out. HashMaps are for easy lookups if you change that or try to sort inside the map itself you will no longer have O(1) lookup.
The code for your sorting is as follows:
class Obj implements Comparable<Obj>{
String key;
ArrayList<Integer> val;
Obj(String key, ArrayList<Integer> val)
{
this.key=key;
this.val=val;
}
public int compareTo(Obj o)
{
/* Write your sorting logic here.
this.val compared to o.val*/
return 0;
}
}
public void sortByValue(Map<String, ArrayList<>> mp){
ArrayList<Obj> arr=new ArrayList<Obj>();
for(String z:mp.keySet())//Make an object and store your map into the arrayList
{
Obj o=new Obj(z,mp.get(z));
arr.add(o);
}
System.out.println(arr);//Unsorted
Collections.sort(arr);// This sorts based on the conditions you coded in the compareTo function.
System.out.println(arr);//Sorted
}
I've tried using Flexelint (the unix version of PC-Lint) and had somewhat mixed results. This is likely because I'm working on a very large and knotty code base. I recommend carefully examining each file that is reported as unused.
The main worry is false positives. Multiple includes of the same header are reported as an unneeded header. This is bad since Flexelint does not tell you what line the header is included on or where it was included before.
One of the ways automated tools can get this wrong:
In A.hpp:
class A {
// ...
};
In B.hpp:
#include "A.hpp
class B {
public:
A foo;
};
In C.cpp:
#include "C.hpp"
#include "B.hpp" // <-- Unneeded, but lint reports it as needed
#include "A.hpp" // <-- Needed, but lint reports it as unneeded
If you blindly follow the messages from Flexelint you'll muck up your #include dependencies. There are more pathological cases, but basically you're going to need to inspect the headers yourself for best results.
I highly recommend this article on Physical Structure and C++ from the blog Games from within. They recommend a comprehensive approach to cleaning up the #include mess:
Guidelines
Here’s a distilled set of guidelines from Lakos’ book that minimize the number of physical dependencies between files. I’ve been using them for years and I’ve always been really happy with the results.
- Every cpp file includes its own header file first. [snip]
- A header file must include all the header files necessary to parse it. [snip]
- A header file should have the bare minimum number of header files necessary to parse it. [snip]
str.replace()
does fixed replacements. Use re.sub()
instead.
Solved the problem by upgrading the dependency to below version
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
On a Mac, credentials are stored in Keychain Access. Look for Github and remove that credential. More info: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
With the recent update to melt.data.table
, we can now melt multiple columns. With that, we can do:
require(data.table) ## 1.9.5
melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"),
value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
# id time loop_number Q3.2 Q3.3
# 1: 1 2009-01-01 1 -0.433978480 0.41227209
# 2: 2 2009-01-02 1 -0.567995351 0.30701144
# 3: 3 2009-01-03 1 -0.092041353 -0.96024077
# 4: 4 2009-01-04 1 1.137433487 0.60603396
# 5: 5 2009-01-05 1 -1.071498263 -0.01655584
# 6: 6 2009-01-06 1 -0.048376809 0.55889996
# 7: 7 2009-01-07 1 -0.007312176 0.69872938
You can get the development version from here.
Setting the image using picture.ImageLocation()
works fine, but you are using a relative path. Check your path against the location of the .exe
after it is built.
For example, if your .exe
is located at:
<project folder>/bin/Debug/app.exe
The image would have to be at:
<project folder>/bin/Image/1.jpg
Of course, you could just set the image at design-time (the Image
property on the PictureBox
property sheet).
If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image
. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory
to Copy if newer
.
At this point the image file will be copied when you build the application and you can use
picture.ImageLocation = @"Image\1.jpg";
According to the problem you can try this...
// looping between date range
while (startDate <= endDate)
{
//here will be your code block...
startDate = startDate.AddDays(1);
}
thanks......
You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.
Here is the directive:
app.directive("ngScopeElement", function () {
var directiveDefinitionObject = {
restrict: "A",
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope[iAttrs.ngScopeElement] = iElement;
}
};
}
};
return directiveDefinitionObject;
});
Usage:
app.directive("myDirective", function() {
return {
template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
link: function(scope, element, attrs) {
scope.list[0] // scope.list is the jqlite element,
// scope.list[0] is the native dom element
}
}
});
Some remarks:
scope.list
from myDirective
s postLink-Function, which you are very likely using anywayngScopeElement
uses a preLink-function, so that directives nested within the element having ng-scope-element
can already access scope.list
mysql> SHOW ENGINE INNODB STATUS;
But in my case only this way could help:
1. Make backup of current DB
2. Drop DB (not all tables, but DB)
3. Create DB (check that you still have previleges)
4. Restore DB from backup
Demo : http://jsfiddle.net/xavi3r/D3prt/
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Original Answer: Resetting a multi-stage form with jQuery
Mike's suggestion (from the comments) to keep checkbox and selects intact!
Warning: If you're creating elements (so they're not in the dom), replace :hidden
with [type=hidden]
or all fields will be ignored!
$(':input','#myform')
.removeAttr('checked')
.removeAttr('selected')
.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
.val('');
For most software that isn't actually string-processing software, program logic ought not to depend on the content of string variables. Whenever I see something like this in a program:
if (s == "value")
I get a bad feeling. Why is there a string literal in this method? What's setting s
? Does it know that logic depends on the value of the string? Does it know that it has to be lower case to work? Should I be fixing this by changing it to use String.Compare
? Should I be creating an Enum
and parsing into it?
From this perspective, one gets to a philosophy of code that's pretty simple: you avoid examining a string's contents wherever possible. Comparing a string to String.Empty
is really just a special case of comparing it to a literal: it's something to avoid doing unless you really have to.
Knowing this, I don't blink when I see something like this in our code base:
string msg = Validate(item);
if (msg != null)
{
DisplayErrorMessage(msg);
return;
}
I know that Validate
would never return String.Empty
, because we write better code than that.
Of course, the rest of the world doesn't work like this. When your program is dealing with user input, databases, files, and so on, you have to account for other philosophies. There, it's the job of your code to impose order on chaos. Part of that order is knowing when an empty string should mean String.Empty
and when it should mean null
.
(Just to make sure I wasn't talking out of my ass, I just searched our codebase for `String.IsNullOrEmpty'. All 54 occurrences of it are in methods that process user input, return values from Python scripts, examine values retrieved from external APIs, etc.)
You know, in my website i created something like this:
$uri=$_SERVER['REQUEST_URI'];
$strpos=strpos($uri, '.php');
if ($strpos!==false){
$e404="The page requested by you: "".$_SERVER['REQUEST_URI']."", doesn't exists on this server.";
$maybe=str_replace('.php','',$uri);
$maybe=str_replace('/','',$maybe);
die("<center><h1>404</h1><hr><h3>$e404</h3><h3>Maybe try <a href=$maybe>www.leaveyortexthere.p.ht/$maybe</a>?</center>");
}
i hope it helps you.
In bash:
while read -r line ; do
[[ $line == all:* ]] && line+=" anotherthing"
echo "$line"
done < filename
You need to create a thread to handle the update loop and use it to update the textarea. The tricky part though is that only the main thread can actually modify the ui so the update loop thread needs to signal the main thread to do the update. This is done using a Handler.
Check out this link: http://developer.android.com/guide/topics/ui/dialogs.html# Click on the section titled "Example ProgressDialog with a second thread". It's an example of exactly what you need to do, except with a progress dialog instead of a textfield.
Just try below a simple solution:
JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);
whenever my JSON request is like:
{
"role": "RT",
"orders": [
{
"order_id": "ORDER201908aPq9Gs",
"cart_id": 164444,
"affiliate_id": 0,
"orm_order_status": 9,
"status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
"status_date": "2020-04-15",
}
]
}
Note: if you need to use sudo, do this:
sudo bash -c 'cat file2 >> file1'
The usual method of simply prepending sudo
to the command will fail, since the privilege escalation doesn't carry over into the output redirection.
Yes. Use stat()
. See the man page forstat(2)
.
stat()
will fail if the file doesn't exist, otherwise most likely succeed. If it does exist, but you have no read access to the directory where it exists, it will also fail, but in that case any method will fail (how can you inspect the content of a directory you may not see according to access rights? Simply, you can't).
Oh, as someone else mentioned, you can also use access()
. However I prefer stat()
, as if the file exists it will immediately get me lots of useful information (when was it last updated, how big is it, owner and/or group that owns the file, access permissions, and so on).
Better Approach:
<script type="text/javascript">
$('#btn').click(function() {
var id = $(this).attr('id');
alert(id);
});
</script>
<input id="btn" type="button" value="click" />
But, if you REALLY need to do the click handler inline, this will work:
<script type="text/javascript">
function display(el) {
var id = $(el).attr('id');
alert(id);
}
</script>
<input id="btn" type="button" value="click" OnClick="display(this);" />
You need to wrap all the html into one single element.
<template>
<div>
<div class="form-group">
<label for="avatar" class="control-label">Avatar</label>
<input type="file" v-on:change="fileChange" id="avatar">
<div class="help-block">
Help block here updated 4 ...
</div>
</div>
<div class="col-md-6">
<input type="hidden" name="avatar_id">
<img class="avatar" title="Current avatar">
</div>
</div>
</template>
<script>
export default{
methods: {
fileChange(){
console.log('Test of file input change')
}
}
}
</script>
DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1 )
UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1
Steps to manually configure DNS:
You can access Network and Sharing center by right clicking on the Network icon on the taskbar.
Now choose adapter settings from the side menu.
This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.
In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.
Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.
Select ‘use the following DNS address’ option. Now fill the following fields as given here.
Preferred DNS server: 208.67.222.222
Alternate DNS server : 208.67.220.220
This is an available Open DNS address. You may also use google DNS server addresses.
After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.
You have to add this DNS server address in the router configuration also (by referring the router manual for more information).
Refer : for above method & alternative
If none of this works, then open command prompt(Run as Administrator) and run these:
ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit
Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).
Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue
Why not try using an unbuffered file?
f = open('xyz.log', 'a', 0)
OR
sys.stdout = open('out.log', 'a', 0)
use in the script:
echo $(python python_script.py arg1 arg2) > /dev/null
or
python python_script.py "string arg" > /dev/null
The script will be executed without output.
The file is truncated, so you can call read()
(no exceptions raised, unlike when opened using 'w') but you'll get an empty string.
Just use Entry (as in java.util.Map.Entry) as the list type, and populate it using (java.util.AbstractMap’s) SimpleImmutableEntry:
List<Entry<Integer, String>> sections = new ArrayList<>();
sections.add(new SimpleImmutableEntry<>(anInteger, orString)):
I had the error after trying to select a subset of rows:
df = df.reindex(index=my_index)
Turns out that my_index
contained values that were not contained in df.index
, so the reindex function inserted some new rows and filled them with nan
.
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
you can try this simple code, Collections.swap(list, i, j) is what you looking for.
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
String toMoveUp = "3";
while (list.indexOf(toMoveUp) != 0) {
int i = list.indexOf(toMoveUp);
Collections.swap(list, i, i - 1);
}
System.out.println(list);
If you mean to change default directory for "Node.js command prompt", when you launch it, then (Windows case)
change the default path in the row which looks like
if "%CD%\"=="%~dp0" cd /d "%HOMEDRIVE%%HOMEPATH%"
with your path. It could be for example
if "%CD%\"=="%~dp0" cd /d "c://MyDirectory/"
if you mean to change directory once when you launched "Node.js command prompt", then execute the following command in the Node.js command prompt:
cd c:/MyDirectory/
Use pylint
it will give you a detailed report about how many spaces you need and where.
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
You can use either the language construct isset
, or the function array_key_exists
.
isset
should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL
.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on isset
:
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
The first one will get you (the element exists, and is not null) :
boolean true
While the second one will get you (the element exists, but is null) :
boolean false
And the last one will get you (the element doesn't exist) :
boolean false
On the other hand, using array_key_exists
like this :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'd get those outputs :
boolean true
boolean true
boolean false
Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.
For situations such as yours, I generally use isset
, considering I'm never in the second case... But choosing which one to use is now up to you ;-)
For instance, your code could become something like this :
if (!isset(self::$instances[$instanceKey])) {
$instances[$instanceKey] = $theInstance;
}
If you not use -
in id's names then you can do this
oldParent.id='xxx';_x000D_
newParent.id='oldParent';_x000D_
xxx.id='newParent';_x000D_
oldParent.parentNode.insertBefore(oldParent,newParent);
_x000D_
#newParent { color: red }
_x000D_
<div id="oldParent">_x000D_
<span>Foo</span>_x000D_
<b>Bar</b>_x000D_
Hello World_x000D_
</div>_x000D_
<div id="newParent"></div>
_x000D_
If you want to print the picture using imshow() you also execute plt.show()
So here is the brief summary for Bootstrap 4:
<div class="container-fluid px-0">
<div class="row no-gutters">
<div class="col-12"> //any cols you need
...
</div>
</div>
</div>
It works for me.
this error probably is occurred most of the time due to missing closing tag. and further you can the following dependency to resolve this issue while supporting legacy HTML formate.
as it your code charset="UTF-8"> here is no closing for meta tag.
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
You mean menu Project -> Generate Javadoc ?
For a direct scroll:
getListView().setSelection(21);
For a smooth scroll:
getListView().smoothScrollToPosition(21);
You can use hive library,for that you want to import hive Class from hive import ThriftHive
Try This example:
import sys
from hive import ThriftHive
from hive.ttypes import HiveServerException
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
transport = TSocket.TSocket('localhost', 10000)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = ThriftHive.Client(protocol)
transport.open()
client.execute("CREATE TABLE r(a STRING, b INT, c DOUBLE)")
client.execute("LOAD TABLE LOCAL INPATH '/path' INTO TABLE r")
client.execute("SELECT * FROM r")
while (1):
row = client.fetchOne()
if (row == None):
break
print row
client.execute("SELECT * FROM r")
print client.fetchAll()
transport.close()
except Thrift.TException, tx:
print '%s' % (tx.message)
A Pair class :
public class Pair<K, V> {
private final K element0;
private final V element1;
public static <K, V> Pair<K, V> createPair(K element0, V element1) {
return new Pair<K, V>(element0, element1);
}
public Pair(K element0, V element1) {
this.element0 = element0;
this.element1 = element1;
}
public K getElement0() {
return element0;
}
public V getElement1() {
return element1;
}
}
usage :
Pair<Integer, String> pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();
Immutable, only a pair !
I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).
I went with a list.Sort solution something like this.
var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
OrderId = o.id,
OrderDate = o.orderDate,
OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
});
data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));
env VAR=value myScript args ...
This might not work in all situations, but here is what I did: I extended the FilterInputStream class and do the required processing of the bytes as the external lib reads the data.
public class StreamBytesWithExtraProcessingInputStream extends FilterInputStream {
protected StreamBytesWithExtraProcessingInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
int readByte = super.read();
processByte(readByte);
return readByte;
}
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
int readBytes = super.read(buffer, offset, count);
processBytes(buffer, offset, readBytes);
return readBytes;
}
private void processBytes(byte[] buffer, int offset, int readBytes) {
for (int i = 0; i < readBytes; i++) {
processByte(buffer[i + offset]);
}
}
private void processByte(int readByte) {
// TODO do processing here
}
}
Then you simply pass an instance of StreamBytesWithExtraProcessingInputStream
where you would have passed in the input stream. With the original input stream as constructor parameter.
It should be noted that this works byte for byte, so don't use this if high performance is a requirement.
I prefer to use something like Lodash:
import { pickBy, identity } from 'lodash'
const cleanedObject = pickBy(originalObject, identity)
Note that the identity function is just x => x
and its result will be false for all falsy values. So this removes undefined, "", 0, null, ...
If you only want the undefined
values removed you can do this:
const cleanedObject = pickBy(originalObject, v => v !== undefined)
It gives you a new object, which is usually preferable over mutating the original object like some of the other answers suggest.
Not possible with vanilla CSS. However you can use something like:
Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
Or
Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.
Example:
#header {
color: red;
a {
font-weight: bold;
text-decoration: none;
}
}
This error will also occur if you call .ps1
file from a .bat
file and file path has spaces.
The fix is to make sure there are no spaces in the path of .ps1
file.
If using integers as targets, makes sure they aren't symmetrical at 0.
I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.
The command is gradle dependencies
, and its output is much improved in Gradle 1.2. (You can already try 1.2-rc-1 today.)
JavaScript is fired on client side and JSP is on server-side. So I can say that it is impossible.