Get correct y
coordinate and use window.scrollTo({top: y, behavior: 'smooth'})
const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;
window.scrollTo({top: y, behavior: 'smooth'});
scrollIntoView
is a good option too but it may not works perfectly in some cases. For example when you need additional offset. With scrollTo
you just need to add that offset like this:
const yOffset = -10;
window.scrollTo({top: y + yOffset, behavior: 'smooth'});
You could try this:
<style>
h1:target { padding-top: 50px; }
</style>
<a href="#bar">Go to bar</a>
<h1 id="bar">Bar</h1>
Set the top padding value to the actual height of your header. This will introduce a slight extra gap at the top of your header, but it will only be visible when the user jumps to the anchor and then scrolls up. I've made up that solution for my site right now, but it only shows a small fixed bar at the top of the page, nothing too high.
The <select>
tag creates a dropdown list. You can't put html links inside a dropdown.
However, there are JavaScript libraries that provide similar functionality. Here is one example: http://www.dynamicdrive.com/dynamicindex1/dropmenuindex.htm
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>
and
function runMyFunction() {
//code
return true;
}
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
You can simply use
<a href="directry/filename.html#section5" >click me</a>
to link to a section/id of another page by
<div class = "solTitle"> <a href = "#" id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>
<div class= "solTitle"> <a href = "#" id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>
$(document).ready(function(){
$('.solTitle a').click(function(e) {
e.preventDefault();
alert('here in');
var divId = 'summary' +$(this).attr('id');
document.getElementById(divId).className = ''; /* or $('#'+divid).removeAttr('class'); */
});
});
I changed few things:
It's as simple as return false;
ex.
jQuery("li a:eq(0)").click(function(){
return false;
})
or
jQuery("#menu a").click(function(){
return false;
})
a.hover:hover {
text-decoration:underline;
}
Get your scrolling feature easily. It also supports Animated/Smooth scrolling as an additional feature. Details for Angular Scroll library:
Github - https://github.com/oblador/angular-scroll
Bower: bower install --save angular-scroll
npm : npm install --save angular-scroll
Minfied version - only 9kb
Smooth Scrolling (animated scrolling) - yes
Scroll Spy - yes
Documentation - excellent
Demo - http://oblador.github.io/angular-scroll/
Hope this helps.
On bitbucket.org the voted solution wouldn't work. Instead, when using headers (with ##), it is possible to reference them as anchors by prefixing them as #markdown-header-my-header-name, where #markdown-header- is an implicit prefix generated by the renderer, and the rest is the lower-cased header title with dashes replacing spaces.
Example
## My paragraph title
will produce an implicit anchor like this
#markdown-header-my-paragraph-title
The whole URL before each anchor reference is optional, i.e.
[Some text](#markdown-header-my-paragraph-title)
is equivalent of
[Some text](https://bitbucket.org/some_project/some_page#markdown-header-my-paragraph-title)
provided that they are in the same page.
Source: https://bitbucket.org/tutorials/markdowndemo/overview (edit source of this .md file and look at how anchors are made).
Not enough rep for a comment.
The getElementById()
based method in the selected answer won't work if the anchor has name
but not id
set (which is not recommended, but does happen in the wild).
Something to bare in mind if you don't have control of the document markup (e.g. webextension).
The location
based method in the selected answer can also be simplified with location.replace
:
function jump(hash) { location.replace("#" + hash) }
JS:
<div onclick="location.href='url'">content</div>
jQuery:
$("div").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
Make sure to use cursor:pointer
for these DIVs
function getHash() {
if (window.location.hash) {
var hash = window.location.hash.substring(1);
if (hash.length === 0) {
return false;
} else {
return hash;
}
} else {
return false;
}
}
try this
.div
{
text-decoration:none;
font-size:16;
display:block;
padding:14px;
}
.div a:hover
{
background-color:#080808;
color:white;
}
lets say we have a anchor tag used in our code and class"div" is called in the main program. the a:hover will do the thing, it will give a vampire black color to the background and white color to the text when the mouse is moved over it that's what hover means.
If you would like to make the command once for your entire site, instead of having to do it after every link. Try this place within the Head of your web site and bingo.
<head>
<title>your text</title>
<base target="_blank" rel="noopener noreferrer">
</head>
hope this helps
I pulled in a variable because some values in my link will change depending on what record the user is coming from. This worked for testing :
<div onclick="location.href='page.html';" style="cursor:pointer;">...</div>
and this works too :
<div onclick="location.href='<%=Webpage%>';" style="cursor:pointer;">...</div>
While these answers are good, IMHO I don't think they fully address the question.
The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.
While target="_self"
is default by browser and the most common target is target="_blank"
which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent"
, "_top"
and framename
tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.
target="_self"
This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame
and frameset
tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.
target="_parent"
Will open the in the next level up of a frame if they were nested to inside one another
target="_top"
This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.
target="framename
This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name
was the proper method that method has been replaced with using the id
identifying tag.
<!--Example:-->
<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>
<a href="url4" target="B"></a>
</body>
</html>
i tried this clean easy method and seems to work in all browsers. Inside the svg file:
<svg>_x000D_
<a id="anchor" xlink:href="http://www.google.com" target="_top">_x000D_
_x000D_
<!--your graphic-->_x000D_
_x000D_
</a>_x000D_
</svg>_x000D_
_x000D_
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23. This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No Escape.
Discussion: This technique will of course also work with other special characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
Updated code
$('a','div.res').click(function(){
var currentAnchor = $(this);
alert(currentAnchor.text());
alert(currentAnchor.attr('href'));
});
In my case, I had a condition when the user click the "a" element. The condition was:
If other section had more than ten items, then the user should be not redirected to other page.
If other section had less than ten items, then the user should be redirected to other page.
The functionality of the "a" elements depends of the other component. The code within click event is the follow:
var elementsOtherSection = document.querySelectorAll("#vehicle-item").length;
if (elementsOtherSection> 10){
return true;
}else{
event.preventDefault();
return false;
}
You can use jQuery
to achieve this
Example:
$(function () {
$('.map').maphilight();
});
Go through this LINK to know more.
If the above one doesnt work then go through this link.
EDIT :
Give same class to each area
tag like class="mapping"
and try this below code
$('.mapping').mouseover(function() {
alert($(this).attr('id'));
}).mouseout(function(){
alert('Mouseout....');
});
Try this:
$('#myAnchor')[0].click();
It works for me.
Thanks Andy for the example, this was very helpful. I ended implementing a slightly different strategy since I am developing a single-page scroll and did not want Angular to refresh when using the hashbang URL. I also want to preserve the back/forward action of the browser.
Instead of using the directive and the hash, I am using a $scope.$watch on the $location.search, and obtaining the target from there. This gives a nice clean anchor tag
<a ng-href="#/?scroll=myElement">My element</a>
I chained the watch code to the my module declaration in app.js like so:
.run(function($location, $rootScope) {
$rootScope.$watch(function() { return $location.search() }, function(search) {
var scrollPos = 0;
if (search.hasOwnProperty('scroll')) {
var $target = $('#' + search.scroll);
scrollPos = $target.offset().top;
}
$("body,html").animate({scrollTop: scrollPos}, "slow");
});
})
The caveat with the code above is that if you access by URL directly from a different route, the DOM may not be loaded in time for jQuery's $target.offset() call. The solution is to nest this code within a $viewContentLoaded watcher. The final code looks something like this:
.run(function($location, $rootScope) {
$rootScope.$on('$viewContentLoaded', function() {
$rootScope.$watch(function() { return $location.search() }, function(search) {
var scrollPos = 0
if (search.hasOwnProperty('scroll')) {
var $target = $('#' + search.scroll);
var scrollPos = $target.offset().top;
}
$("body,html").animate({scrollTop: scrollPos}, "slow");
});
});
})
Tested with Chrome and FF
Short answer:
. is for current directory
.. is for upper directory as in cd ..
command on shell.
Simple yet tricky, I write this answer primarily for myself not to forget next time.
ademSite/
+-- index.html
+-- style.css
The link to CSS in index.html
:
<link rel="stylesheet" href="style.css">
or
<link rel="stylesheet" href="./style.css">
ademSite/
+-- index.html
+-- stylefiles
+-- style.css
This case it should be:
<link rel="stylesheet" href="stylefiles/style.css">
or <link rel="stylesheet" href="./stylefiles/style.css">
+-- html
¦ +-- index.html
+-- stylefiles
+-- style.css
In this case path must be:
<link rel="stylesheet" href="../stylefiles/style.css">
For current window, you can use this:
var hash = window.location.hash.substr(1);
To get the hash value of the main window, use this:
var hash = window.top.location.hash.substr(1);
If you have a string with an URL/hash, the easiest method is:
var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();
If you're using jQuery, use this:
var hash = $(location).attr('hash');
Did you tried JQuery's scrollTo
method? http://demos.flesler.com/jquery/scrollTo/
Or you can extend JQuery and add your custom mentod:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 400);
}});
Then you can call this method like:
$("#header").scrollToMe();
Janky at best
<a href="file://///server/folders/x/x/filename.ext">right click </a></td>
and then right click, select "copy location" option, and then paste into url.
The <a>
tag without the "href" can be handy when using multi-level menus and you need to expand the next level but don't want that menu label to be an active link. I have never had any issues using it that way.
In the app-routing.modules.ts
file:
{
path: 'hero/:id', component: HeroComponent
}
In the component.html
file:
target="_blank" [routerLink]="['/hero', '/sachin']"
You can also add an anchor with follow attr:
(text-indent:-99999px;)
visibility: hidden;
position:absolute;
top:-80px;
and give the parent container a position relative.
Works perfect for me.
I'm surprised to see all answers stating the use of alt
attribute in a
tag is not valid. This is absolutely wrong.
Html does not block you using any attributes:
<a your-custom-attribute="value">Any attribute can be used</a>
If you ask if it is semantically correct to use alt
attribute in a
then I will say:
NO. It is used to set image description <img alt="image description" />
.
It is a matter of what you'd do with the attributes. Here's an example:
a::after {_x000D_
content: attr(color); /* attr can be used as content */_x000D_
display: block;_x000D_
color: white;_x000D_
background-color: blue;_x000D_
background-color: attr(color); /* This won't work */_x000D_
display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
display: block;_x000D_
}_x000D_
[hidden] {_x000D_
display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
Again, if you ask if it is semantically correct to use custom attribute then I will say:
No. Use data-*
attributes for its semantic use.
Oops, question was asked in 2013.
Many of the above methods have been deprecated. It is now recommended to use the constructor found here
function clickAnchorTag() {
var event = document.createEvent('MouseEvent');
event = new CustomEvent('click');
var a = document.getElementById('nameOfID');
a.dispatchEvent(event);
}
This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.
There is a way simpler way. You put the href in a paragraph just created for that href. For example:
HREF name
Yes, it is valid to use the anchor tag without a href
attribute.
If the
a
element has nohref
attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.
Yes, you can use class
and other attributes, but you can not use target
, download
, rel
, hreflang
, and type
.
The
target
,download
,rel
,hreflang
, andtype
attributes must be omitted if the href attribute is not present.
As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a>
without href
. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.
Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link
).
Source: W3C HTML5 Recommendation
You can do it with anchor tags using css3 :target
pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example
Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.
I had to combine several of the answers to get a working solution.
This solution will:
Not navigate to http://mySite/#
<a href="#" (click)="!!functionToCall()">Link</a>
Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
$("#employeeLink").on("click",function(e) {
e.preventDefault(); // cancel the link itself
$.post(this.href,function(data) {
$("#someContainer").html(data);
});
});
});
If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>
and use (in plain JS)
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the link
document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
});
});
Without a form we need to make one
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the actual link
var myForm = document.createElement("form");
myForm.action=this.href;// the href of the link
myForm.target="myFrame";
myForm.method="POST";
myForm.submit();
});
});
Html a tag
Link in html
<a href="index1.php">page1</a>
<a href="page2.php">page2</a>
Html in php
echo ' <a href="index1.php">page1</a>';
echo '<a href="page2.php">page2</a>';
Simply add this in CSS
,
a {
color: inherit;
text-decoration: none;
}
that's it, done.
@Nicolas,following worked for me as yours didn't have type="button"
due to which it started behaving as submit type..since i already have one submit type.it didn't worked for me ....and now you can either add class to button or to <a>
to get required layout:
<a href="http://www.google.com/">
<button type="button">Click here</button>
</a>
$('a[href$="ABC"]')...
Selector documentation can be found at http://docs.jquery.com/Selectors
For attributes:
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
Ok simplest method is : -
Within the click function (Jquery) : -
$('html,body').animate({scrollTop: $("#resultsdiv").offset().top},'slow');
HTML
<div id="resultsdiv">Where I want to scroll to</div>
To link to an element, and then 'position' that element an arbitrary distance from the top of the page, using pure CSS, you'd have to use padding-top
, that way the element is still positioned at the top of the window, but it appears, visibly, to be positioned some distance from the top of the view-port, for example:
<a href="#link1">Link one</a>
<a href="#link2">Link two</a>
<div id="link1">
The first.
</div>
<div id="link2">
The second.
</div>
CSS:
div {
/* just to force height, and window-scrolling to get to the elements.
Irrelevant to the demo, really */
margin-top: 1000px;
height: 1000px;
}
#link2 {
/* places the contents of the element 100px from the top of the view-port */
padding-top: 100px;
}
To use a plain JavaScript approach:
function addMargin() {
window.scrollTo(0, window.pageYOffset - 100);
}
window.addEventListener('hashchange', addMargin);
In Angular, <a>
s are directives. As such, if you have an empty href
or no href
, Angular will call event.preventDefault
.
From the source:
element.on('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr(href)) {
event.preventDefault();
}
});
Here's a plnkr demonstrating the missing href
scenario.
There is the only better way is AJAX as everyone is suggest in their posts. The alternative is using IFrames like below:
<iframe name="f1" id="f1"> </iframe>
<a href='yourpage.php' target='f1'>Click </a>
Now you will get the output in IFrame (you can place IFrame wherever you need in the page or event hide it and the result from the script).
Hope for non Ajax solution this is better.
You don't have that kind of control with a bare a
tag. But you can hook up the tag's onclick
handler to call window.open(...)
with the right parameters. See here for examples:
https://developer.mozilla.org/En/DOM/Window.open
I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.
Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;
$('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});
The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.
The best way is to use the following code:
<a href="<?php echo base_url() ?>directory_name/filename.php">Link</a>
A more un-obtrusive way (assuming you use jQuery):
HTML:
<a id="my-link" href="page.html">page link</a>
Javascript:
$('#my-link').click(function(e)
{
e.preventDefault();
});
The advantage of this is the clean separation between logic and presentation. If one day you decide that this link would do something else, you don't have to mess with the markup, just the JS.
Use following code to show menu instead go to href addres
function show_more_menu(e) {_x000D_
if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
Use:
a:visited {
text-decoration: none;
}
But it will only affect links that haven't been clicked on yet.
Provided that any element has the id attribute on a webpage. One could simply link/jump to the element that is referenced by the tag.
Within the same page:
<div id="markOne"> ..... </div>
......
<a href="#markOne">Jump to markOne</a>
Other page:
<div id="http://randomwebsite.com/mypage.html#markOne">
Jumps to the markOne element in the mypage of the linked website
</div>
The targets don't necessarily have an anchor element.
You can go check this fiddle out.
jqyery this is another version with jquery a little less shorter.
assuming that the <a>
element is inside de <li>
element
$(li).click(function(){
$(this).children().click();
});
A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties.
For the creation date, you simply keep a java.util.Date property. Be sure, to always initialize it with new Date().
For the last update field, you can use a Timestamp property, you need to map it with @Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).
I have tried your code and found that if we put background-image: url(image.png);
in btn-pToolName
and change color:#000000
. it displays the image at background.
my test css:
.btn-pTool {
margin: 0;
padding: 0;
}
.btn-pToolName {
text-align: center;
width: 26px;
height: 190px;
display: block;
color: #000000;
text-decoration: none;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
line-height: 32px;
background-image: url(defalut.png);
background-repeat: no-repeat;
}
and test html:
<div class="pToolContainer">
<span class="btn-pTool"><a class="btn-pToolName" href="#">adad</a></span>
<div class="pToolSlidePanel"></div>
</div>
Hope this helps.
I had the same problem. Initially I had setup Eclipse CDT with Cygwing & was working smoothly. One day there happened a problem due to which I had to reset windows. After that when I opened Eclipse I started facing the issue described above. This is how I solved it.
First I searched that in the error the PATH variable value is same as the PATH variable of windows ( just by manual comparison of both two values ). I found that to be same. Now I realized that it is a PATH problem.
Then started looking for Cygwin whether it is there or not? It was there. I located & found that it exists in
C:\cygwin64\bin>
C:\cygwin64\bin>dir ma*
Volume in drive C is Windows8_OS
Volume Serial Number is 042E-11B5
Directory of C:\cygwin64\bin
16-05-2015 18:34 10,259 mag.exe
13-08-2013 04:57 384 mailmail
11-04-2015 02:56 4,252 make-emacs-shortcut
15-02-2015 23:25 194,579 make.exe
04-05-2015 21:36 40,979 makeconv.exe
29-07-2013 11:57 29,203 makedepend.exe
16-05-2015 18:34 79,891 makeindex.exe
16-05-2015 18:34 34,323 makejvf.exe
07-05-2015 03:04 310 mako-render
18-04-2015 02:07 92,179 man.exe
18-04-2015 02:07 113,683 mandb.exe
13-08-2013 04:57 286 manhole
18-04-2015 02:07 29,203 manpath.exe
24-10-2014 13:31 274,461 mate-terminal.exe
24-10-2014 13:31 1,366 mate-terminal.wrapper
15 File(s) 905,358 bytes
0 Dir(s) 373,012,271,104 bytes free
C:\cygwin64\bin>
Then I simply went ahead & updated the PATH variable to include this path & restarted eclipse.
The code compiles & debugging (GDB ) is working nicely.
Hope this helps.
On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL
could be "SM-G920F"
, "SM-G920I"
, or "SM-G920W8"
.
I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:
If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:
/** Returns the consumer friendly device name */
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
}
return capitalize(manufacturer) + " " + model;
}
private static String capitalize(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
char[] arr = str.toCharArray();
boolean capitalizeNext = true;
StringBuilder phrase = new StringBuilder();
for (char c : arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase.append(Character.toUpperCase(c));
capitalizeNext = false;
continue;
} else if (Character.isWhitespace(c)) {
capitalizeNext = true;
}
phrase.append(c);
}
return phrase.toString();
}
Example from my Verizon HTC One M8:
// using method from above
System.out.println(getDeviceName());
// Using https://github.com/jaredrummler/AndroidDeviceNames
System.out.println(DeviceName.getDeviceName());
Result:
HTC6525LVW
HTC One (M8)
As explained above, you can use the Firebase default push id.
If you want something numeric you can do something based on the timestamp to avoid collisions
f.e. something based on date,hour,second,ms, and some random int at the end
01612061353136799031
Which translates to:
016-12-06 13:53:13:679 9031
It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.
You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.
(https://firebase.google.com/docs/database/android/read-and-write)
If you're trying to find the first count
multiples of m
, something like this would work:
def multiples(m, count):
for i in range(count):
print(i*m)
Alternatively, you could do this with range:
def multiples(m, count):
for i in range(0,count*m,m):
print(i)
Note that both of these start the multiples at 0
- if you wanted to instead start at m
, you'd need to offset it by that much:
range(m,(count+1)*m,m)
While I was able to solve this problem in one computer following the other users solutions, the command netsh
didn't solve the issue in one of my machines and even though the current user had administrator rights I was still getting the "HTTP could not register URL.... Your process does not have access rights to this namespace". So I'm sharing my solution in case you still don't get it to work with the other solutions too.
After also trying to give write permissions to the user in the physical directory of my website and getting no success, I finally decided trying to change IIS settings.
As the images below show, I configured the Physical Path Credentials of my website to connect as an specifc user, which was an admin account with DOMAIN\username and password, and this was enough to make the error disapear.
Be careful, d
is the list.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}
Taken from NSString
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Parameters
target
The string to replace.
replacement
The string with which to replace target.
Return Value
A new string in which all occurrences of target in the receiver are replaced by replacement.
I resolved the problem.This is for EAServer Windows Service
Resolution is --> Open Regedit in Run prompt
Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\EAServer
In parameters, give SERVERNAME entry as EAServer.
[It is sometime overwritten with Envirnoment variable : Path value]
I had a similar issue where I wanted a banner across the top of the screen that had one image on the left and a repeating image on the right to the edge of the screen. I ended up resolving it like so:
CSS:
.banner_left {
position: absolute;
top: 0px;
left: 0px;
width: 131px;
height: 150px;
background-image: url("left_image.jpg");
background-repeat: no-repeat;
}
.banner_right {
position: absolute;
top: 0px;
left: 131px;
right: 0px;
height: 150px;
background-image: url("right_repeating_image.jpg");
background-repeat: repeat-x;
background-position: top left;
}
The key was the right tag. I'm basically specifying that I want it to repeat from 131px in from the left to 0px from the right.
In addition to the dropDuplicates
option there is the method named as we know it in pandas
drop_duplicates
:
drop_duplicates() is an alias for dropDuplicates().
Example
s_df = sqlContext.createDataFrame([("foo", 1),
("foo", 1),
("bar", 2),
("foo", 3)], ('k', 'v'))
s_df.show()
+---+---+
| k| v|
+---+---+
|foo| 1|
|foo| 1|
|bar| 2|
|foo| 3|
+---+---+
Drop by subset
s_df.drop_duplicates(subset = ['k']).show()
+---+---+
| k| v|
+---+---+
|bar| 2|
|foo| 1|
+---+---+
s_df.drop_duplicates().show()
+---+---+
| k| v|
+---+---+
|bar| 2|
|foo| 3|
|foo| 1|
+---+---+
Try this:
ALTER TABLE "table_name"
MODIFY "column_name" "New Data Type";
this.$el
- points to the root element of the componentthis.$refs.<ref name>
+ <div ref="<ref name>" ...
- points to nested element use
$el
/$refs
only aftermounted()
step of vue lifecycle
<template>
<div>
root element
<div ref="childElement">child element</div>
</div>
</template>
<script>
export default {
mounted() {
let rootElement = this.$el;
let childElement = this.$refs.childElement;
console.log(rootElement);
console.log(childElement);
}
}
</script>
<style scoped>
</style>
Use the php's OR (||)
logical operator for php isset()
with multiple operator
e.g
if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {
}
Use the onchange
event to pass the input file element to your function.
<input type="file" onchange="angular.element(this).scope().fileSelected(this)" />
So when a user selects a file, you have a reference to it without the user needing to click an "Add" or "Upload" button.
$scope.fileSelected = function (element) {
var myFileSelected = element.files[0];
};
You must use one of the following ways:
string s = @"loooooooooooooooooooooooong loooooong
long long long";
string s = "loooooooooong loooong" +
" long long" ;
Weirdness is highly subjective, I just suggest to follow the official recommendation:
Guide to naming conventions on groupId, artifactId and version
groupId
will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.eg.
org.apache.maven
,org.apache.commons
A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.
eg.
org.apache.maven
,org.apache.maven.plugins
,org.apache.maven.reporting
artifactId
is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.eg.
maven
,commons-math
version
if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.eg.
2.0
,2.0.1
,1.3.1
Code for dealing with scope variables should go in controller, and service calls go to the service.
You can inject $rootScope
for the purpose of using $rootScope.$broadcast
and $rootScope.$on
.
Otherwise avoid injecting $rootScope
. See
Instead of doing file_put_contents(***WebSiteURL***...)
you need to use the server path to /cache/lang/file.php
(e.g. /home/content/site/folders/filename.php
).
You cannot open a file over HTTP
and expect it to be written. Instead you need to open it using the local path.
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
Now, this seems to work:
$('#example').DataTable({
"info": false
});
it hides that div
, altogether
I write some test code:
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
struct sc {
int x;
string y;
int* z;
};
int main(int argc, char** argv)
{
int* r = new int[128];
for(int i = 0; i < 128; i++ ) {
r[i] = i+32;
}
cout << r[100] << endl;
delete r;
sc* a = new sc;
sc* aa = new sc[2];
sc* b = new sc();
sc* ba = new sc[2]();
cout << "az:" << a->z << endl;
cout << "bz:" << b->z << endl;
cout << "a:" << a->x << " y" << a->y << "end" << endl;
cout << "b:" << b->x << " y" << b->y << "end" <<endl;
cout << "aa:" << aa->x << " y" << aa->y << "end" <<endl;
cout << "ba:" << ba->x << " y" << ba->y << "end" <<endl;
}
g++ compile and run:
./a.out
132
az:0x2b0000002a
bz:0
a:854191480 yend
b:0 yend
aa:854190968 yend
ba:0 yend
Officially google provide an Android API for this.
The API is currently being tested with a handful of partners, and will become available to all developers soon.
Update API is available now - https://developer.android.com/guide/app-bundle/in-app-updates
import java.util.Stack;
class Demo
{
char c;
public boolean checkParan(String word)
{
Stack<Character> sta = new Stack<Character>();
for(int i=0;i<word.length();i++)
{
c=word.charAt(i);
if(c=='(')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c=='{')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c==')')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='(')
{
sta.pop();
System.out.println(" ) is poped from the Stack");
}
else if(sta.peek()=='(' && sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
}
else if(c=='}')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='{')
{
sta.pop();
System.out.println(" } is poped from the Stack");
}
}
else if(c=='(')
{
if(sta.empty())
{
System.out.println("Stack is empty only ( parenthesis in Stack ");
}
}
}
// System.out.print("The top element is : "+sta.peek());
return sta.empty();
}
}
public class ParaenthesisChehck {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Demo d1= new Demo();
// d1.checkParan(" ");
// d1.checkParan("{}");
//d1.checkParan("()");
//d1.checkParan("{()}");
// d1.checkParan("{123}");
d1.checkParan("{{{}}");
}
}
More concise than others:
def parseString(string):
try:
return int(string)
except ValueError:
return string
b = [[parseString(s) for s in clause.split(', ')] for clause in a]
Alternatively if your format is fixed as <string>, <int>, <int>
, you can be even more concise:
def parseClause(a,b,c):
return [a, int(b), int(c)]
b = [parseClause(*clause) for clause in a]
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
Try this:
Request request = chain.request();
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
String body = buffer.readUtf8();
After this, in the body
there is the JSON you are interested in.
Not a direct answer to this question but rather to the "issue" of $event.currentTarget
apparently be set to null.
This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.
You can check this for more information: Consecutive calls to console.log produce inconsistent results
The syntax to disable an HTML input is as follows:
<input type="text" id="input_id" DISABLED />
I believe putty has a maximum number of columns you can specify for the window.
For Windows I personally use Windows PowerShell and set the screen buffer width reasonably high. The column width remains fixed and you can use a horizontal scroll bar to see the data. I had the same problem you're having now.
edit: For remote hosts that you have to SSH into you would use something like plink + Windows PowerShell
You can use the Microsoft.VisualBasic namespace to find this helper function:
Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)
Stick this in your ~/.vimrc and be happy:
" enables :Paste to just do what you want
command Paste execute 'set noai | insert | set ai'
Edit: on reflection, :r !cat
is a far better approach since it's short, semantic, and requires no custom vimrc. Use that instead!
Solution for complete BST case :-
Node kSmallest(Node root, int k) {
int i = root.size(); // 2^height - 1, single node is height = 1;
Node result = root;
while (i - 1 > k) {
i = (i-1)/2; // size of left subtree
if (k < i) {
result = result.left;
} else {
result = result.right;
k -= i;
}
}
return i-1==k ? result: null;
}
It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.
Readability is also one of the reasons for enforced line indentation.
Just wanted to share my experience as well. My Build had crossed Processing Step(it was a mere 984kB app) but did not show up in "Versions" tab for more than 30 minutes. I also double checked my email but had not received anything from Apple. However, under versions tab I had 3 builds listed excluding the latest one. What worked for me was that I just clicked on the least recent one(click on the Build Number) and then clicked on Expire Build and voila buy recent Build was immediately available under the current Version.
I have not found any Apple Document which explains this anomaly.
Hope it Helps! Cheers
To set textarea value of encoded HTML (to show as HTML) you should use .html( the_var )
but as mentioned if you try and set it again it may (and probably) will not work.
You can fix this by emptying the textarea .empty()
and then setting it again with .html( the_var )
Here's a working JSFiddle: https://jsfiddle.net/w7b1thgw/2/
jQuery(function($){_x000D_
_x000D_
$('.load_html').click(function(){_x000D_
var my_var = $(this).data('my_html');_x000D_
$('#dynamic_html').html( my_var ); _x000D_
});_x000D_
_x000D_
$('#clear_html').click(function(){_x000D_
$('#dynamic_html').empty(); _x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<textarea id="dynamic_html"></textarea>_x000D_
<a id="google_html" class="load_html" href="#" data-my_html="<a href="google.com">google.com</a>">Google HTML</a>_x000D_
<a id="yahoo_html" class="load_html" href="#" data-my_html="<a href="yahoo.com">yahoo.com</a>">Yahoo HTML</a>_x000D_
<a id="clear_html" href="#">Clear HTML</a>
_x000D_
If you want a simple regex then it won't be accurate. https://www.freeformatter.com/java-regex-tester.html#ad-output offers a tool to test your Java regex. Also, at the bottom you can find some suggested regexes for validating a date.
ISO date format (yyyy-mm-dd):
^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$
ISO date format (yyyy-mm-dd) with separators '-' or '/' or '.' or ' '. Forces usage of same separator accross date.
^[0-9]{4}([- /.])(((0[13578]|(10|12))\1(0[1-9]|[1-2][0-9]|3[0-1]))|(02\1(0[1-9]|[1-2][0-9]))|((0[469]|11)\1(0[1-9]|[1-2][0-9]|30)))$
United States date format (mm/dd/yyyy)
^(((0[13578]|(10|12))/(0[1-9]|[1-2][0-9]|3[0-1]))|(02/(0[1-9]|[1-2][0-9]))|((0[469]|11)/(0[1-9]|[1-2][0-9]|30)))/[0-9]{4}$
Hours and minutes, 24 hours format (HH:MM):
^(20|21|22|23|[01]\d|\d)((:[0-5]\d){1,2})$
Good luck
A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here
e.g
<script>
//look no global needed:)
$(document).ready(function(){
// Get the initial value
var $el = $('#myInputElement');
$el.data('oldVal', $el.val() );
$el.change(function(){
//store new value
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
})
.focus(function(){
// Get the value when input gains focus
var oldValue = $(this).data('oldVal');
});
});
</script>
<input id="myInputElement" type="text">
Create a directive and put a watch on it.
app.directive("myApp", function(){
link:function(scope){
function:getTotal(){
..do your maths here
}
scope.$watch('one', getTotals());
scope.$watch('two', getTotals());
}
})
How about this solution?
// other onload attached earlier
window.onload=function() {
alert('test');
};
tmpPreviousFunction=window.onload ? window.onload : null;
// our onload function
window.onload=function() {
alert('another message');
// execute previous one
if (tmpPreviousFunction) tmpPreviousFunction();
};
JavaScript way - this worked for me.
<script>
$(document).ready(function() {
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
});
</script>
Reason:
$('#YourTableId').find('*')
-> this returns all the tags.
$('#YourTableId').find('*').each(function () { $(this).attr("disabled", true); });
iterates over all objects captured in this and disable input tags.
Analysis (Debugging):
form:radiobutton
is internally considered as an "input" tag.
Like in the above function(), if you try printing document.write(this.tagName);
Wherever, in tags it finds radio buttons, it returns an input tag.
So, above code line can be more optimized for radio button tags, by replacing * with input:
$('#YourTableId').find('input').each(function () { $(this).attr("disabled", true); });
My experience is the same as some others mentioned. The meta tag...
<meta name = "format-detection" content = "telephone=no">
...works when the website is running in Mobile Safari (i.e., with chrome) but stops working when run as a webapp (i.e., is saved to home screen and runs without chrome).
My less-than-ideal solution is to insert the values into input fields...
<input type="text" readonly="readonly" style="border:none;" value="3105551212">
It's less than ideal because, despite the border being set to none, iOS renders a multi-pixel gray bar above the field. But, it's better than seeing the number as a link.
**
unpacks dictionaries.
This
func(a=1, b=2, c=3)
is the same as
args = {'a': 1, 'b': 2, 'c':3}
func(**args)
It's useful if you have to construct parameters:
args = {'name': person.name}
if hasattr(person, "address"):
args["address"] = person.address
func(**args) # either expanded to func(name=person.name) or
# func(name=person.name, address=person.address)
def setstyle(**styles):
for key, value in styles.iteritems(): # styles is a regular dictionary
setattr(someobject, key, value)
This lets you use the function like this:
setstyle(color="red", bold=False)
Java's parseInt method is actally a bunch of code eating "false" hex : if you want to translate -32768, you should convert the absolute value into hex, then prepend the string with '-'.
There is a sample of Integer.java file :
public static int parseInt(String s, int radix)
The description is quite explicit :
* Parses the string argument as a signed integer in the radix
* specified by the second argument. The characters in the string
...
...
* parseInt("0", 10) returns 0
* parseInt("473", 10) returns 473
* parseInt("-0", 10) returns 0
* parseInt("-FF", 16) returns -255
Find:
^[#;].*
Replace with nothing. The ^
indicates the start of a line, the [#;]
is a character class to match either #
or ;
, and .*
matches anything else in the line.
In versions of Notepad++ before 6.0, you won't be able to actually remove the lines due to a limitation in its regex engine; the replacement results in blank lines for each line matched. In other words, this:
# foo ; bar statement;
Will turn into:
statement;
However, the replacement will work in Notepad++ 6.0 if you add \r
, \n
or \r\n
to the end of the pattern, depending on which line ending your file is using, resulting in:
statement;
put you $image
in img
tag of html
try this
echo '<img src="your_path_to_image/'.$image.'" />';
instead of
print $image;
your_path_to_image would be absolute path of your image folder like eg: /home/son/public_html/images/
or as your folder structure on server.
Update 2 :
if your image is resides in the same folder where this page file is exists
you can user this
echo '<img src="'.$image.'" />';
I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...
select a,b,rn
from (select a, b, row_number() over (partition by a,b order by a,b) as rn
from table)
where rn=1;
On my Linux I see an error with
adb shell "su -c '[your command goes here]'"
su: invalid uid/gid '-c'
The solution is on Linux
adb shell su 0 '[your command goes here]'
At least with Active Directory, I have been able to search by DistinguishedName by doing an LDAP query in this format (assuming that such a record exists with this distinguishedName):
"(distinguishedName=CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com)"
Vartec's answer doesn't read all lines, so I made a version that did:
def run_command(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return iter(p.stdout.readline, b'')
Usage is the same as the accepted answer:
command = 'mysqladmin create test -uroot -pmysqladmin12'.split()
for line in run_command(command):
print(line)
Currently, it is evaluating to True
because the variable has a value. There is a good example found here of what happens when you evaluate arbitrary types as a boolean.
In short, what you want to do is isolate the 'True'
or 'False'
string and run eval
on it.
>>> eval('True')
True
>>> eval('False')
False
String.contains()
which checks if the string contains a specified sequence of char valuesString.indexOf()
which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)Now Apple Inc. added a new device screen shots also over iTunesconnect that is iPad Pro. Here are all sizes of screen shots which iTunesconnects requires.
You are likely wanting placeholder
functionality:
<input name="Name" placeholder="Enter Your Name" />
This will not work in some older browsers, but polyfills exist (some require jQuery, others don't) to patch that functionality.
If you wanted to roll your own solution, you could use the onfocus
and onblur
events of your element to determine what its value should be:
<input name="Name" value="Enter Your Name"
onfocus="(this.value == 'Enter Your Name') && (this.value = '')"
onblur="(this.value == '') && (this.value = 'Enter Your Name')" />
You'll find that most of us aren't big fans of evaluating JavaScript from attributes like onblur
and onfocus
. Instead, it's more commonly encouraged to bind this logic up purely with JavaScript. Granted, it's a bit more verbose, but it keeps a nice separation between your logic and your markup:
var nameElement = document.forms.myForm.Name;
function nameFocus( e ) {
var element = e.target || window.event.srcElement;
if (element.value == "Enter Your Name") element.value = "";
}
function nameBlur( e ) {
var element = e.target || window.event.srcElement;
if (element.value == "") element.value = "Enter Your Name";
}
if ( nameElement.addEventListener ) {
nameElement.addEventListener("focus", nameFocus, false);
nameElement.addEventListener("blur", nameBlur, false);
} else if ( nameElement.attachEvent ) {
nameElement.attachEvent("onfocus", nameFocus);
nameElement.attachEvent("onblur", nameBlur);
}
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
If you want to filter only items that are less than 7 days old then you just use
Filter
Created
is greater than or equal to
[Today]-7
Note - the screenshot is incorrect.
[Today] is fully supported in view filters in 2007 and onwards (just keep the spaces out!) and you only need to muck around with calculated columns in 2003.
Just wrap it as a function, then call this function from your background thread.
public void debugMsg(String msg) {
final String str = msg;
runOnUiThread(new Runnable() {
@Override
public void run() {
mInfo.setText(str);
}
});
}
You can try running a simple web server based on Twisted
You have to hide the column at the grid view control rather than at the data source. Hiding it at the data source it will not render to the grid view at all, therefore you won't be able to access the value in the grid view. Doing it the way you're suggesting, you would have to access the column value through the data source as opposed to the grid view.
To hide the column on the grid view control, you can use code like this:
dataGridView1.Columns[0].Visible = false;
To access the column from the data source, you could try something like this:
object colValue = ((DataTable)dataGridView.DataSource).Rows[dataSetIndex]["ColumnName"];
For HP Ultra book with windows 7 enabling hyper-v through bios worked for intel haxm problem.
For enabling hyper-v:-
F10-> Bios advanced setting-> device configurations->enable Hyper-V then install.
It will work.
You have two references to the :lot_priprc binding variable -- while it should require you to only set the variable's value once and bind it in both places, I've had problems where this didn't work and had to treat each copy as a different variable. A pain, but it worked.
Right click on the terminal and select clear option (for ubuntu).
For mac just type clear
For some of you skipping library will works
project(":libABC") {
apply plugin: 'org.sonarqube'
sonarqube {
skipProject = true
}
}
Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.
You can set max connections using:
set global max_connections = '1 < your number > 100000';
This will set your number of mysql connection unti (Requires SUPER
privileges).
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)
class CheckMailer:
def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
self.f = FileWriter(filename)
self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
self.inbox = self.outlook.Folders(folderindex)
def check(self):
#===============================================================================
# for i in xrange(1,100): #Uncomment this section if index 3 does not work for you
# try:
# self.inbox = self.outlook.Folders(i) # "6" refers to the index of inbox for Default User Mailbox
# print "%i %s" % (i,self.inbox) # "3" refers to the index of inbox for Another user's mailbox
# except:
# print "%i does not work"%i
#===============================================================================
self.f.pl(time.strftime("%H:%M:%S"))
tot = 0
messages = self.inbox.Items
message = messages.GetFirst()
while message:
self.f.pl (message.Subject)
message = messages.GetNext()
tot += 1
self.f.pl("Total Messages found: %i" % tot)
self.f.pl("-" * 80)
self.f.flush()
if __name__ == "__main__":
mail = CheckMailer()
for i in xrange(320): # this is 10.6 hours approximately
mail.check()
time.sleep(120.00)
For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.
class FileWriter(object):
'''
convenient file wrapper for writing to files
'''
def __init__(self, filename):
'''
Constructor
'''
self.file = open(filename, "w")
def pl(self, a_string):
str_uni = a_string.encode('utf-8')
self.file.write(str_uni)
self.file.write("\n")
def flush(self):
self.file.flush()
You can not use tag to make group of more than one tag. If you want to make group of tag for any purpose like in ajax to change particular group or in CSS to change style of particular tag etc. then use
Ex.
<table>
<tbody id="foods">
<tr>
<td>Group 1</td>
</tr>
<tr>
<td>Group 1</td>
</tr>
</tbody>
<tbody id="drinks">
<tr>
<td>Group 2</td>
</tr>
<tr>
<td>Group 2</td>
</tr>
</tbody>
</table>
This code works for me:
public void Run()
{
Dog myDog = new Dog();
myDog.Name= "Foo";
myDog.Color = DogColor.Brown;
System.Console.WriteLine("{0}", myDog.ToString());
MemoryStream stream = SerializeToStream(myDog);
Dog newDog = (Dog)DeserializeFromStream(stream);
System.Console.WriteLine("{0}", newDog.ToString());
}
Where the types are like this:
[Serializable]
public enum DogColor
{
Brown,
Black,
Mottled
}
[Serializable]
public class Dog
{
public String Name
{
get; set;
}
public DogColor Color
{
get;set;
}
public override String ToString()
{
return String.Format("Dog: {0}/{1}", Name, Color);
}
}
and the utility methods are:
public static MemoryStream SerializeToStream(object o)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
public static object DeserializeFromStream(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
object o = formatter.Deserialize(stream);
return o;
}
The following is Peter Lyons' answer verbatim, ported over to vanilla JS from Coffeescript, as requested by several others. Peter's answer is very able, and anyone voting on my answer should vote on his as well.
Config
What you are doing is fine. I like to have my own config namespace set up in a top-level config.js
file with a nested namespace like this.
// Set the current environment to true in the env object
var currentEnv = process.env.NODE_ENV || 'development';
exports.appName = "MyApp";
exports.env = {
production: false,
staging: false,
test: false,
development: false
};
exports.env[currentEnv] = true;
exports.log = {
path: __dirname + "/var/log/app_#{currentEnv}.log"
};
exports.server = {
port: 9600,
// In staging and production, listen loopback. nginx listens on the network.
ip: '127.0.0.1'
};
if (currentEnv != 'production' && currentEnv != 'staging') {
exports.enableTests = true;
// Listen on all IPs in dev/test (for testing from other machines)
exports.server.ip = '0.0.0.0';
};
exports.db {
URL: "mongodb://localhost:27017/#{exports.appName.toLowerCase()}_#{currentEnv}"
};
This is friendly for sysadmin editing. Then when I need something, like the DB connection info, it`s
require('./config').db.URL
Routes/Controllers
I like to leave my routes with my controllers and organize them in an app/controllers
subdirectory. Then I can load them up and let them add whatever routes they need.
In my app/server.js
javascript file I do:
[
'api',
'authorization',
'authentication',
'domains',
'users',
'stylesheets',
'javascripts',
'tests',
'sales'
].map(function(controllerName){
var controller = require('./controllers/' + controllerName);
controller.setup(app);
});
So I have files like:
app/controllers/api.js
app/controllers/authorization.js
app/controllers/authentication.js
app/controllers/domains.js
And for example in my domains controller, I have a setup
function like this.
exports.setup = function(app) {
var controller = new exports.DomainController();
var route = '/domains';
app.post(route, controller.create);
app.put(route, api.needId);
app.delete(route, api.needId);
route = '/domains/:id';
app.put(route, controller.loadDomain, controller.update);
app.del(route, controller.loadDomain, function(req, res){
res.sendJSON(req.domain, status.OK);
});
}
Views
Putting views in app/views
is becoming the customary place. I lay it out like this.
app/views/layout.jade
app/views/about.jade
app/views/user/EditUser.jade
app/views/domain/EditDomain.jade
Static Files
Go in a public
subdirectory.
Github/Semver/NPM
Put a README.md markdown file at your git repo root for github.
Put a package.json file with a semantic version number in your git repo root for NPM.
This doesn't specifically answer your question, because I'm not sure in any clients exist in Mac OS X, but I generally just Remote Desktop into the server and work through that. Another option is VMware Fusion (which is much better than Parallels in my opinion) + Windows XP + SQL Server Management Studio.
One option would be to exclude all results that contain the directory name with grep. For example:
find . -name '*.js' | grep -v excludeddir
Using your radio button's ID, try rb.SelectedValue
.
Simply use CAST,
CAST(column_name AS UNSIGNED)
The type for the cast result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
@allain, @GateKiller your query selects users not logins
To select logins you can use this query:
SELECT name FROM master..sysxlogins WHERE sid IS NOT NULL
In MSSQL2005/2008 syslogins table is used insted of sysxlogins
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
You can use line-height
for that. Just set it up to the exact height of your p
tag.
p.event_desc {
line-height:35px;
}
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
There is a versioning scheme called "Vermongo" which addresses some aspects which haven't been dealt with in the other replies.
One of these issues is concurrent updates, another one is deleting documents.
Vermongo stores complete document copies in a shadow collection. For some use cases this might cause too much overhead, but I think it also simplifies many things.
another way it to use the millisecond timer:
var uniq = 'id' + (new Date()).getTime();
select FOUND_ROWS();
will return no. of records selected by select query.
If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,
you can downgrade your 'requests' version to 2.5.3:
pip install requests==2.5.3
android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."
checkout changes for Android Support Library, revision 22.1.0 (April 2015)
I was trying to fetch table meta data, but had the following error:
Using:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
DatabaseMetaData metaData = connection.getMetaData();
...
metaData.getColumns(...);
returned an empty ResultSet.
But using the following URL instead it worked properly:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";
There was a need to specify: DATABASE_TO_UPPER=false
Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan's answer which uses SpEL list {#isbn, #includeUsed}
which is the simplest way to create unique keys.
From Spring Documentation
The default key generation strategy changed with the release of Spring 4.0. Earlier versions of Spring used a key generation strategy that, for multiple key parameters, only considered the hashCode() of parameters and not equals(); this could cause unexpected key collisions (see SPR-10237 for background). The new 'SimpleKeyGenerator' uses a compound key for such scenarios.
Before Spring 4.0
I suggest you to concat the values of the parameters in Spel expression with something like key="#checkWarehouse.toString() + #isbn.toString()")
, I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don't have to provide an int
in your SPEL expression.
As for the hash code with a high collision probability - you can't use it as the key.
Someone in this thread has suggested to use T(java.util.Objects).hash(#p0,#p1, #p2)
but it WILL NOT WORK and this approach is easy to break, for example I've used the data from SPR-9377 :
System.out.println( Objects.hash("someisbn", new Integer(109), new Integer(434)));
System.out.println( Objects.hash("someisbn", new Integer(110), new Integer(403)));
Both lines print -636517714 on my environment.
P.S. Actually in the reference documentation we have
@Cacheable(value="books", key="T(someType).hash(#isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.
P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.
I'd like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.
You will need to use java.util.Scanner
for this issue.
Here is a good login program for the console:
import java.util.Scanner; // I use scanner because it's command line.
public class Login {
public void run() {
Scanner scan = new Scanner (new File("the\\dir\\myFile.extension"));
Scanner keyboard = new Scanner (System.in);
String user = scan.nextLine();
String pass = scan.nextLine(); // looks at selected file in scan
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine(); // gets input from user
if (inpUser.equals(user) && inpPass.equals(pass)) {
System.out.print("your login message");
} else {
System.out.print("your error message");
}
}
}
Of course, you will use Scanner scanner = new Scanner (File toScan);
but not for user input.
Happy coding!
As a last note, you are at least a decent programmer if you can make Swing components.
It depends on how do you want to create the thread and available .NET version:
.NET 2.0+:
A) You can create the Thread
object directly. In this case you could use "closure" - declare variable and capture it using lambda-expression:
object result = null;
Thread thread = new System.Threading.Thread(() => {
//Some work...
result = 42; });
thread.Start();
thread.Join();
Console.WriteLine(result);
B) You can use delegates and IAsyncResult
and return value from EndInvoke()
method:
delegate object MyFunc();
...
MyFunc x = new MyFunc(() => {
//Some work...
return 42; });
IAsyncResult asyncResult = x.BeginInvoke(null, null);
object result = x.EndInvoke(asyncResult);
C) You can use BackgroundWorker
class. In this case you could use captured variable (like with Thread
object) or handle RunWorkerCompleted
event:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) => {
//Some work...
e.Result = 42;
};
worker.RunWorkerCompleted += (s, e) => {
//e.Result "returned" from thread
Console.WriteLine(e.Result);
};
worker.RunWorkerAsync();
.NET 4.0+:
Starting with .NET 4.0 you could use Task Parallel Library and Task
class to start your threads. Generic class Task<TResult>
allows you to get return value from Result
property:
//Main thread will be blocked until task thread finishes
//(because of obtaining the value of the Result property)
int result = Task.Factory.StartNew(() => {
//Some work...
return 42;}).Result;
.NET 4.5+:
Starting with .NET 4.5 you could also use async
/await
keywords to return value from task directly instead of obtaining Result
property:
int result = await Task.Run(() => {
//Some work...
return 42; });
Note: method, which contains the code above shoud be marked with async
keyword.
For many reasons using of Task Parallel Library is preferable way of working with threads.
var settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Ignore;
//you can add multiple settings and then use it
var bodyAsJson = JsonConvert.SerializeObject(body, Formatting.Indented, settings);
Take a look at this , we can simply do this with outline-offset
property
Output image look like
.black_box {_x000D_
width:500px;_x000D_
height:200px;_x000D_
background:#000;_x000D_
float:left;_x000D_
border:2px solid #000;_x000D_
outline: 1px dashed #fff;_x000D_
outline-offset: -10px;_x000D_
}
_x000D_
<div class="black_box"></div>
_x000D_
Maybe you can try the followings $indent -kr -i8 *.c
Hope it's useful for you!
Note for anyone running Vagrant: this can be caused by a bug with their shared folders. Specify NFS for your shared folders in your Vagrantfile to avoid this happening.
Simply adding type: "nfs"
to the end will do the trick, like so:
config.vm.synced_folder ".", "/vagrant", type: "nfs"
The answer to this question lies in how C# Controls work
Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread. This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.
Effectively, what Invoke does is ensure that the code you are calling occurs on the thread that the control "lives on" effectively preventing cross threaded exceptions.
From a historical perspective, in .Net 1.1, this was actually allowed. What it meant is that you could try and execute code on the "GUI" thread from any background thread and this would mostly work. Sometimes it would just cause your app to exit because you were effectively interrupting the GUI thread while it was doing something else. This is the Cross Threaded Exception - imagine trying to update a TextBox while the GUI is painting something else.
Effectively, you are interrupting a queue, which can have lots of unforeseen consequences. Invoke is effectively the "polite" way of getting what you want to do into that queue, and this rule was enforced from .Net 2.0 onward via a thrown InvalidOperationException.
To understand what is actually going on behind the scenes, and what is meant by "GUI Thread", it's useful to understand what a Message Pump or Message Loop is.
This is actually already answered in the question "What is a Message Pump" and is recommended reading for understanding the actual mechanism that you are tying into when interacting with controls.
Other reading you may find useful includes:
One of the cardinal rules of Windows GUI programming is that only the thread that created a control can access and/or modify its contents (except for a few documented exceptions). Try doing it from any other thread and you'll get unpredictable behavior ranging from deadlock, to exceptions to a half updated UI. The right way then to update a control from another thread is to post an appropriate message to the application message queue. When the message pump gets around to executing that message, the control will get updated, on the same thread that created it (remember, the message pump runs on the main thread).
and, for a more code heavy overview with a representative sample:
Invalid Cross-thread Operations
// the canonical form (C# consumer)
public delegate void ControlStringConsumer(Control control, string text); // defines a delegate type
public void SetText(Control control, string text) {
if (control.InvokeRequired) {
control.Invoke(new ControlStringConsumer(SetText), new object[]{control, text}); // invoking itself
} else {
control.Text=text; // the "functional part", executing only on the main thread
}
}
Once you have an appreciation for InvokeRequired, you may wish to consider using an extension method for wrapping these calls up. This is ably covered in the Stack Overflow question Cleaning Up Code Littered with Invoke Required.
There is also a further write up of what happened historically that may be of interest.
I faced the same issue:
E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation
I resolved by using the following commands:
apt-get update
apt-get install gnupg
BUT imagine a large table with changing columns. You have to compare every column and if the database changes you have to adjust the trigger. AND it doesn't "feel" good to compare every row hardcoded :)
Yeah, but that's the way to proceed.
As a side note, it's also good practice to pre-emptively check before updating:
UPDATE foo SET b = 3 WHERE a=3 and b <> 3;
In your example this would make it update (and thus overwrite) two rows instead of three.
Basically the problem is with file path.
The forward slash in the beginning of the url makes it look for the file at the root. Removing that, it will be a path relative to this css file - like this:
background-image: url(img/debut_dark.png);
If you are using Atom, copying the project path of image sometimes includes forward slash in the copied path so be careful.
Set the user name as data-username
attribute to the button and also a class:
HTML
<input type="button" name="theButton" value="Detail" class="btn" data-username="{{result['username']}}" />
JS
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name != undefined && name != null) {
window.location = '/player_detail?username=' + name;
}
});?
EDIT:
Also, you can simply check for undefined
&& null
using:
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name) {
window.location = '/player_detail?username=' + name;
}
});?
As, mentioned in this answer
if (name) {
}
will evaluate to true if value is not:
The above list represents all possible falsy values in ECMA/Javascript.
Use whoami /priv
command to list all the user privileges.
Just a note for people having the same problem as me. I've been using OpenCV/cv2 to export numpy arrays into Tiffs but I had problems with opening these Tiffs with PIL Open Image and had the same error as in the title. The problem turned out to be that PIL Open Image could not open Tiffs which was created by exporting numpy float64 arrays. When I changed it to float32, PIL could open the Tiff again.
function getParent(event)
{
return event.target.parentNode;
}
Examples: 1.
document.body.addEventListener("click", getParent, false);
returns the parent element of the current element that you have clicked.
- If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){ var parentElement = getParent(event); }
Use CSS cursor: pointer
if I remember correctly.
Either in your CSS file:
.link_cursor
{
cursor: pointer;
}
Then just add the following HTML to any elements you want to have the link cursor: class="link_cursor"
(the preferred method.)
Or use inline CSS:
<a style="cursor: pointer;">
A simple query which works for me is:
select * from table where DATEADD(month, 1,DATEFIELD) >= getdate()
How to convert array to json String in swift 2.3
var yourString : String = ""
do
{
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(yourArray, options: NSJSONWritingOptions.PrettyPrinted)
{
yourString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
}
}
catch
{
print(error)
}
And now you can use yourSting as JSON string..
I got to problem this way:
-Created console application with C#
-This appliaction using createeventsource like this
if(!System.Diagnostics.EventLog.SourceExists(sourceName)) System.Diagnostics.EventLog.CreateEventSource(sourceName,logName);
-Build solution and get .exe file
-Run exe as administator.This create log file.
NOTE: Dont remember Event viewer must be refresh for see the log.
I hope this solution helps someone :)
A colleague of mine recommended Internet Explorer Collection. It appears to work without issues, but I'm far from a power user. It also supports installing IE 1 (!!) through 8.
Yes, Java SE is where to start. All the tasks you mention can be handled with it.
Java ME is the Mobile Edition, and EE is Enterprise Edition; these are specialized / extended versions of Standard Edition.
Since Python 3.5 you can use the typing module from the standard library for type related things:
from typing import Iterable
...
if isinstance(my_item, Iterable):
print(True)
Try this Code:
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//You create MediaPlayer variable ==> set the path and start the audio.
mplayer = MediaPlayer.create(this, R.raw.example);
mplayer.start();
//Find the seek bar by Id (which you have to create in layout)
// Set seekBar max with length of audio
// You need a Timer variable to set progress with position of audio
final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(mplayer.getDuration());
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
seekBar.setProgress(mplayer.getCurrentPosition());
}
}, 0, 1000);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Update the progress depending on seek bar
mplayer.seekTo(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
Just uncomment extension=php_openssl.dll Restart Apache Service and that should help.
What I did in the end was:
jenkins-target
, and got jenkins to track thatjenkins-target
jenkins-target
branchI'm not sure if this will work for everyone, my project was quite small, not too many tags and stuff, but it's dead easy to do, dont have to mess around with refspecs and parameters and stuff :-)
Replace
Python 2 xrange
to
Python 3 range
Rest all same.
This is useful in contexts where the encoding is not told per HTTP header or other meta data, e.g. the local file system.
Imagine the following stylesheet:
[rel="external"]::after
{
content: ' ?';
}
If a reader saves the file to a hard drive and you omit the @charset
rule, most browsers will read it in the OS’ locale encoding, e.g. Windows-1252, and insert ↗ instead of an arrow.
Unfortunately, you cannot rely on this mechanism as the support is rather … rare.
And remember that on the net an HTTP header will always override the @charset
rule.
The correct rules to determine the character set of a stylesheet are in order of priority:
@charset
rule.The last rule is the weakest, it will fail in some browsers.
The charset
attribute in <link rel='stylesheet' charset='utf-8'>
is obsolete in HTML 5.
Watch out for conflict between the different declarations. They are not easy to debug.
@charset
if more than one name is registered for the same encoding.@charset
. There is a support table. I do not trust this. :)It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:
public Omar(){};
public Omar(a){};
public Omar(a,b){};
public Omar(a,b,c){};
public Omar(a,b,c,d){};
...
You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e
SELECT SUM(No), HOUR(dateofissue)
FROM tablename
WHERE dateofissue>='2011-07-30'
GROUP BY HOUR(dateofissue)
It will give the hour by sum from a particular day!
It may be worth noting that auto-indent does not work if there are syntax errors in the document. Get rid of the red squigglies, and THEN try CTRL+K, CTRL+D, whatever...
This works for me
td::after {
content: '';
display: block;
width: 30px;
}
I always come to this question when I hit an error in the test environment and remember, "I've done this before, but I can do it straight in the web.config without having to modify code and re-deploy to the test environment, but it takes 2 changes... what was it again?"
For future reference
<system.web>
<customErrors mode="Off"></customErrors>
</system.web>
AND
<system.webServer>
<httpErrors errorMode="Detailed" existingResponse="PassThrough"></httpErrors>
</system.webServer>
Example for you to work from
HTML:
<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?
jQuery:
<script type="text/javascript">
$(function () {
$('#button').on('click', function () {
var text = $('#text');
text.val(text.val() + ' after clicking');
});
});
<script>
Javascript
<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
var text = document.getElementById('text');
text.value += ' after clicking';
});
</script>
Working jQuery example: http://jsfiddle.net/geMtZ/ ?
Yes you will have to escape all double quotes by a backslash.
I think the easiest way to do that is to use so called projection. It can map query results to interfaces. Using SqlResultSetMapping
is inconvienient and makes your code ugly :).
An example right from spring data JPA source code:
public interface UserRepository extends JpaRepository<User, Integer> {
@Query(value = "SELECT firstname, lastname FROM SD_User WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
public static interface NameOnly {
String getFirstname();
String getLastname();
}
}
You can also use this method to get a list of projections.
Check out this spring data JPA docs entry for more info about projections.
Note 1:
Remember to have your User
entity defined as normal - the fields from projected interface must match fields in this entity. Otherwise field mapping might be broken (getFirstname()
might return value of last name et cetera).
Note 2:
If you use SELECT table.column ...
notation always define aliases matching names from entity. For example this code won't work properly (projection will return nulls for each getter):
@Query(value = "SELECT user.firstname, user.lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
But this works fine:
@Query(value = "SELECT user.firstname AS firstname, user.lastname AS lastname FROM SD_User user WHERE id = ?1", nativeQuery = true)
NameOnly findByNativeQuery(Integer id);
In case of more complex queries I'd rather use JdbcTemplate
with custom repository instead.
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
Swift version of @onegray's answer
protocol RequestsNavigationPopVerification {
var confirmationTitle: String { get }
var confirmationMessage: String { get }
}
extension RequestsNavigationPopVerification where Self: UIViewController {
var confirmationTitle: String {
return "Go back?"
}
var confirmationMessage: String {
return "Are you sure?"
}
}
final class NavigationController: UINavigationController {
func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
guard let requestsPopConfirm = topViewController as? RequestsNavigationPopVerification else {
popViewControllerAnimated(true)
return true
}
let alertController = UIAlertController(title: requestsPopConfirm.confirmationTitle, message: requestsPopConfirm.confirmationMessage, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { _ in
dispatch_async(dispatch_get_main_queue(), {
let dimmed = navigationBar.subviews.flatMap { $0.alpha < 1 ? $0 : nil }
UIView.animateWithDuration(0.25) {
dimmed.forEach { $0.alpha = 1 }
}
})
return
})
alertController.addAction(UIAlertAction(title: "Go back", style: .Default) { _ in
dispatch_async(dispatch_get_main_queue(), {
self.popViewControllerAnimated(true)
})
})
presentViewController(alertController, animated: true, completion: nil)
return false
}
}
Now in any controller, just conform to RequestsNavigationPopVerification
and this behaviour is adopted by default.
You can resize and then use imagejpeg()
Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.
imagejpeg($tn, $save, 75);
For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also
// 24 = 192 bits
private const int SaltByteSize = 24;
private const int HashByteSize = 24;
private const int HasingIterationsCount = 10101;
public static string HashPassword(string password)
{
// http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(HashByteSize);
}
byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
return Convert.ToBase64String(dst);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] _passwordHashBytes;
int _arrayLen = (SaltByteSize + HashByteSize) + 1;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != _arrayLen) || (src[0] != 0))
{
return false;
}
byte[] _currentSaltBytes = new byte[SaltByteSize];
Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);
byte[] _currentHashBytes = new byte[HashByteSize];
Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
{
_passwordHashBytes = bytes.GetBytes(SaltByteSize);
}
return AreHashesEqual(_currentHashBytes, _passwordHashBytes);
}
private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
{
int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
var xor = firstHash.Length ^ secondHash.Length;
for (int i = 0; i < _minHashLength; i++)
xor |= firstHash[i] ^ secondHash[i];
return 0 == xor;
}
In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.
This will generate assembly code with the C code + line numbers interweaved, to more easily see which lines generate what code:
# create assembler code:
g++ -S -fverbose-asm -g -O2 test.cc -o test.s
# create asm interlaced with source lines:
as -alhnd test.s > test.lst
Found in Algorithms for programmers, page 3 (which is the overall 15th page of the PDF).
Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.
There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API
It includes an answer to your question here: Updates & creation should return a resource representation
It says:
To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.
Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.
I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.
Check out the PHP cURL functions. They should do what you want.
Or if you just want a simple URL GET then:
$lines = file('http://www.example.com/');
This works,
#!/usr/bin/Rscript
but I don't know what happens if you have more than 1 version of R installed on your machine.
If you do it like this
#!/usr/bin/env Rscript
it tells the interpreter to just use whatever R appears first on your path.
FINALLY THE BEST WAY WORKED PERFECTLY FOR ME
None of the solutions in this page worked for me EXCEPT THE FOLLOWING
Below the comment sections of the second answer, try the following :
Adding to my above comment, Task Manager does not display the filename.exe process but Resource Monitor does, so I'm able to kill it from there which solves the issue without having to reboot. – A__ Jun 19 '19 at 21:23
Just add Axios.defaults.withCredentials=true
instead of ({credentials: true}
) in client side,
and change app.use(cors())
to
app.use(cors(
{origin: ['your client side server'],
methods: ['GET', 'POST'],
credentials:true,
}
))
In MS Excel, first save your workbook as a Macro Enabled file then go to the Developper Tab and click on Visual Basic. Copy and paste this code in the "ThisWorkbook" Excel Objects. Replace the 2 values of G = and C= by the number of the column containing the values being referenced.
In your case, if the number of the column named "File No" is the first column (namely column 1), replace G=6
by G=1
and C=6
by C-1
. Finally click on Macro, Select and Run it. Voila! Works like a charm.
Sub color()
Dim g As Long
Dim c As Integer
Dim colorIt As Boolean
g = 6
c = 6
colorIt = True
Do While Cells(g, c) <> ""
test_value = Cells(g, c)
Do While Cells(g, c) = test_value
If colorIt Then
Cells(g, c).EntireRow.Select
Selection.Interior.ColorIndex = 15
Else
Cells(g, c).EntireRow.Select
Selection.Interior.ColorIndex = x1None
End If
g = g + 1
Loop
colorIt = Not (colorIt)
Loop
End Sub
Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than
customer_id INT( 4 ) NOT NULL ,
make it
customer_id INT( 10 ) NOT NULL ,
and make sure your int column in the customers table is int(10) also.
Problem:
Try running below(without solution) from Internet Explorer and see the result.
console.log("abcde".includes("cd"));
_x000D_
Solution:
Now run below solution and check the result
if (!String.prototype.includes) {//To check browser supports or not_x000D_
String.prototype.includes = function (str) {//If not supported, then define the method_x000D_
return this.indexOf(str) !== -1;_x000D_
}_x000D_
}_x000D_
console.log("abcde".includes("cd"));
_x000D_
You can use now()
like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
I solved the error by changing the port for the project.
I did the following steps:
Good luck!
For Laravel 8 you can also use
Route::redirect('/here', '/there');
//or
Route::permanentRedirect('/here', '/there');
This also works with external URLs
Floating point numbers are encoded using an exponential form, that is something like m * b ^ e
, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.
Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333
) which do not have a finite presentation in decimal but do have one in binary and vice versa.
Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1
yields value
, since value + 1
can not be encoded using m * b ^ e
, where m
, b
and e
are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.
Because of this there is no precision of exactly n
digits like with fixed point numbers, since not every number with n
decimal digits does have a IEEE encoding.
There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.
@{
string datein = Convert.ToDateTime(item.InDate).ToString("dd/MM/yyyy");
@datein
}
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
Hans Passant was correct, I added a handler for AppDomain.CurrentDomain.UnhandledException as described here http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx I was able to find the exception that was occurring and corrected it.
A summary.lm
object stores these values in a matrix
called 'coefficients'
. So the value you are after can be accessed with:
a2Pval <- summary(mg)$coefficients[2, 4]
Or, more generally/readably, coef(summary(mg))["a2","Pr(>|t|)"]
. See here for why this method is preferred.
Every input has a form
property which points to the form the input belongs to, so simply:
function doSomething(element) {
var form = element.form;
}
None of the above answers helped me. I was struggling to understand why code works in Java but not in Kotlin.
Then I figured it out from this thread.
You have to make class and member functions open
, otherwise NPE was being thrown.
After making function open
tests started to pass.
You might as well consider using compiler's "all-open" plugin:
Kotlin has classes and their members final by default, which makes it inconvenient to use frameworks and libraries such as Spring AOP that require classes to be open. The
all-open
compiler plugin adapts Kotlin to the requirements of those frameworks and makes classes annotated with a specific annotation and their members open without the explicit open keyword.
import { HttpModule } from '@angular/http';
package in your module.ts file and add it in your imports.
Just define a getter.
class MyClass
{
get MY_CONST () { return 'string'; }
constructor ()
{
console.log ("MyClass MY_CONST:", this.MY_CONST);
}
}
var obj = new MyClass();
_x000D_
You need to seed your PRNG so it starts with a different value each time.
A simple but low quality seed is to use the current time:
srand(time(0));
This will get you started but is considered low quality (i.e. for example, don't use that if you are trying to generate RSA keys).
Background. Pseudo-random number generators do not create true random number sequences but just simulate them. Given a starting point number, a PRNG will always return the same sequence of numbers. By default, they start with the same internal state so will return the same sequence.
To not get the same sequence, you change the internal state. The act of changing the internal state is called "seeding".
I had the same problem. My code below didn't work, but when I replaced the last "if" with "else", it works. The error was: may reach end of non-void function.
int shifted(char key_letter)
{
if(isupper(key_letter))
{
return key_letter - 'A';
}
if(islower(key_letter) //<----------- doesn't work, replace with else
{
return key_letter - 'a';
}
}
There is a simple method for deleting selected items, and all these people are going for a hard method:
lstYOURVARIABLE.Items.Remove(lstYOURVARIABLE.SelectedItem)
I used this in Visual Basic mode on Visual Studio.
Try this:
fname = "feed.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
Back to your code:
fname = "feed.txt"
fname = open('feed.txt', 'r')
what's the point of this? fname
is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.
for line in feed:
lines = line.split('\n')
line
is one line from the file. It does not make sense to split('\n')
it.
Here is another answer (and personally I think it's more appropriate)
var currentDate = new Date();
currentDate = JSON.stringify(currentDate);
// Now currentDate is in a different format... oh gosh what do we do...
currentDate = new Date(JSON.parse(currentDate));
// Now currentDate is back to its original form :)
I spent over 3 hours to find out solution. Actually port 80 was being used by "system" service so I tried to change port from 80 to 8080 in "httpd" file but same problem raised "port 80 is used by system". It had driven me mad for 3 hours as every thing was changed like port , localhost server etc pointing to 8080.
At last I found mistake that was server root. Basically "Server Root" in "httpd" should be pointing to apache foler of xampp. In my case that's was
ServerRoot "xampp/apache"
I just changed it as follows:
ServerRoot "C:/xampp/apache"
It has worked successfully and now everything is running with OK status.
You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).
Here's a more Windows-ish solution: Right click on the Windows shortcut that you use to launch git bash, and click Properties. Change the value of "Start In" to your desired workspace path.
Edit: Also check that the Target value does not include the --cd-to-home option as noted in the comments below.
I was searching for the option where I can define the line range and found the answer. For example I want to change host1 to host2 from line 36-57.
sed '36,57 s/host1/host2/g' myfile.txt > myfile1.txt
You can use gi option as well to ignore the character case.
sed '30,40 s/version/story/gi' myfile.txt > myfile1.txt
I know it is not Dictionary<TKey, TValue>
class, however you can avoid KeyNotFoundException
while incrementing a value like:
dictionary[key]++; // throws `KeyNotFoundException` if there is no such key
by using ConcurrentDictionary<TKey, TValue> and its really nice method AddOrUpdate()..
Let me show an example:
var str = "Hellooo!!!";
var characters = new ConcurrentDictionary<char, int>();
foreach (var ch in str)
characters.AddOrUpdate(ch, 1, (k, v) => v + 1);
Actually it is 256, see File System Functionality Comparison, Limits.
To repeat a post on http://fixunix.com/microsoft-windows/30758-windows-xp-file-name-length-limit.html
"Assuming we're talking about NTFS and not FAT32, the "255 characters for path+file" is a limitation of Explorer, not the filesystem itself. NTFS supports paths up to 32,000 Unicode characters long, with each component up to 255 characters.
Explorer -and the Windows API- limits you to 260 characters for the path, which include drive letter, colon, separating slashes and a terminating null character. It's possible to read a longer path in Windows if you start it with a
\\
"
If you read the above posts you'll see there is a 5th thing you can be certain of: Finding at least one obstinate computer user!
this is demo code but it will help
<!DOCTYPE html>
<html>
<head>
<title>APITABLE 3</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "https://reqres.in/api/users/",
data: '$format=json',
dataType: 'json',
success: function (data) {
$.each(data.data,function(d,results){
console.log(data);
$("#apiData").append(
"<tr>"
+"<td>"+results.first_name+"</td>"
+"<td>"+results.last_name+"</td>"
+"<td>"+results.id+"</td>"
+"<td>"+results.email+"</td>"
+"<td>"+results.bentrust+"</td>"
+"</tr>" )
})
}
});
});
</script>
</head>
<body>
<table id="apiTable">
<thead>
<tr>
<th>Id</th>
<br>
<th>Email</th>
<br>
<th>Firstname</th>
<br>
<th>Lastname</th>
</tr>
</thead>
<tbody id="apiData"></tbody>
</body>
</html>
cls
$exactadminfile = "C:\temp\files\admin" #First folder to check the file
$userfile = "C:\temp\files\user" #Second folder to check the file
$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
foreach ($filename in $filenames) {
if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
Write-Warning "$filename absent from both locations"
} else {
Write-Host " $filename File is there in one or both Locations" #if file exists there at both locations or at least in one location
}
}
The breakdown of your declaration and its members is somewhat littered:
Remove the typedef
The typedef
is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos
as-written, which is core to your current compilation failure.
Change this:
typedef struct {....} pos;
To this:
struct pos { ... };
Remove extraneous inlines
You're both declaring and defining your member operators within the class definition itself. The inline
keyword is not needed so long as your implementations remain in their current location (the class definition)
Return references to *this
where appropriate
This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:
a = b = c;
This assigns c
to b
, and the resulting value b
is then assigned to a
. This is not equivalent to the following code, contrary to what you may think:
a = c;
b = c;
Therefore, your assignment operator should be implemented as such:
pos& operator =(const pos& a)
{
x = a.x;
y = a.y;
return *this;
}
Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)
Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:
pos& operator=(pos a) // by-value param invokes class copy-ctor
{
this->swap(a);
return *this;
}
Then a swap method is implemented:
void pos::swap(pos& obj)
{
// TODO: swap object guts with obj
}
You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.
Pass objects by const reference when appropriate
All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:
Change this:
bool operator==(pos a) const{
if(a.x==x && a.y== y)return true;
else return false;
}
To this: (also simplified)
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
No copies of anything are made, resulting in more efficient code.
Finally, in answering your question, what is the difference between a member function or operator declared as const
and one that is not?
A const
member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const
member functions can be invoked against const
objects, or const
references and pointers. For example, your operator +()
does not modify your local object and thus should be declared as const
. Your operator =()
clearly modifies the local object, and therefore the operator should not be const
.
Summary
struct pos
{
int x;
int y;
// default + parameterized constructor
pos(int x=0, int y=0)
: x(x), y(y)
{
}
// assignment operator modifies object, therefore non-const
pos& operator=(const pos& a)
{
x=a.x;
y=a.y;
return *this;
}
// addop. doesn't modify object. therefore const.
pos operator+(const pos& a) const
{
return pos(a.x+x, a.y+y);
}
// equality comparison. doesn't modify object. therefore const.
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
};
EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:
a = b = c;
Is equivalent to this:
b = c;
a = b;
And that this does not always equate to this:
a = c;
b = c;
Sample code:
#include <iostream>
#include <string>
using namespace std;
struct obj
{
std::string name;
int value;
obj(const std::string& name, int value)
: name(name), value(value)
{
}
obj& operator =(const obj& o)
{
cout << name << " = " << o.name << endl;
value = (o.value+1); // note: our value is one more than the rhs.
return *this;
}
};
int main(int argc, char *argv[])
{
obj a("a", 1), b("b", 2), c("c", 3);
a = b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
a = c;
b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
return 0;
}
Output
b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3
You can use curly braces to control the number of occurrences. For example, this means 0 to 10:
/^[a-z]{0,10}$/
The options are:
See the regular expression reference.
Your expression had a + after the closing curly brace, hence the error.
Well, the error message says it all: NumPy arrays do not have an append()
method. There's a free function numpy.append()
however:
numpy.append(M, a)
This will create a new array instead of mutating M
in place. Note that using numpy.append()
involves copying both arrays. You will get better performing code if you use fixed-sized NumPy arrays.
By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.
Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.
You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.
Make sure to double the entry with an additional "www"-prefix. If you don't addresses like "www.acme.com" will not work!
Old question but I stumbled here so why not take a shot at it since the question is seeking various perspective and not a definitive answer.
w3c may have its recommendations - which I care a lot - but want to rethink since the question is here.
Why does w3c consider domain names be case insensitive and leaves anything afterwards case insensitive ?
I am thinking that the rationale is that the domain part of the URL is hand typed by a user. Everything after being hyper text will be resolved by the machine (browser and server in the back).
Machines can handle case insensitivity better than humans (not the technical kind:)).
But the question is just because the machines CAN handle that should it be done that way ?
I mean what are the benefits of naming and accessing a resource sitting at hereIsTheResource
vs hereistheresource
?
The lateral is very unreadable than the camel case one which is more readable. Readable to Humans (including the technical kind.)
So here are my points:-
Resource Path falls in the somewhere in the middle of programming structure and being close to an end user behind the browser sometimes.
Your URL (excluding the domain name) should be case insensitive if your users are expected to touch it or type it etc. You should develop your application to AVOID having users type the path as much as possible.
Your URL (excluding the domain name) should be case sensitive if your users would never type it by hand.
Conclusion
Path should be case sensitive. My points are weighing towards the case sensitive paths.
Is the
???
free to be defined by the user?
Yes.
or is it supplied by the HTML?
No. HTML has nothing to do with that. Read below.
Is it possible for me to define the
???
asabcdefg
?
Yes.
If you want to send the following data to the web server:
name = John
age = 12
using application/x-www-form-urlencoded
would be like this:
name=John&age=12
As you can see, the server knows that parameters are separated by an ampersand &
. If &
is required for a parameter value then it must be encoded.
So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data
?
Using the boundary, similar to &
.
For example:
--XXX
Content-Disposition: form-data; name="name"
John
--XXX
Content-Disposition: form-data; name="age"
12
--XXX--
In that case, the boundary value is XXX
. You specify it in the Content-Type
header so that the server knows how to split the data it receives.
So you need to:
Use a value that won't appear in the HTTP data sent to the server.
Be consistent and use the same value everywhere in the request message.
I know this thread is old but I just solved a similar problem with my Ubuntu server and thought I would add a note here to help others as this thread was first page in Google for the topic of PHP not displaying errors.
I tried several configuration settings for the error_reporting value in php.ini. From E_ALL | E_STRICT to E_ALL & E_NOTICE and none worked. I was not getting any syntax errors displayed in the browser (which is rather annoying on a development server). After changing the error_reporting setting to "E_ALL" it all started working. Not sure if it is an Ubuntu Oneric specific issue but after restarting Apache errors started showing in the HTML pages the server was serving. Seems the extra options confusing things and all error reporting stops. HTH somone else.
from __future__ import with_statement
try:
with open( "a.txt" ) as f :
print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
print 'oops'
If you want different handling for errors from the open call vs the working code you could do:
try:
f = open('foo.txt')
except IOError:
print('error')
else:
with f:
print f.readlines()
Use a seperate column to indicate the join condition
SELECT t.importid,
case
when t.importid = g.home
then 'home'
else 'away'
end as join_condition,
g.network,
g.date_start
FROM game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC
LIMIT 7
In addition to the above, you can do this (where "YourListObjectName" is the name of your table):
Dim LO As ListObject
Set LO = ActiveSheet.ListObjects("YourListObjectName")
But I think that only works if you want to reference a list object that's on the active sheet.
I found your question because I wanted to refer to a list object (a table) on one worksheet that a pivot table on a different worksheet refers to. Since list objects are part of the Worksheets collection, you have to know the name of the worksheet that list object is on in order to refer to it. So to get the name of the worksheet that the list object is on, I got the name of the pivot table's source list object (again, a table) and looped through the worksheets and their list objects until I found the worksheet that contained the list object I was looking for.
Public Sub GetListObjectWorksheet()
' Get the name of the worksheet that contains the data
' that is the pivot table's source data.
Dim WB As Workbook
Set WB = ActiveWorkbook
' Create a PivotTable object and set it to be
' the pivot table in the active cell:
Dim PT As PivotTable
Set PT = ActiveCell.PivotTable
Dim LO As ListObject
Dim LOWS As Worksheet
' Loop through the worksheets and each worksheet's list objects
' to find the name of the worksheet that contains the list object
' that the pivot table uses as its source data:
Dim WS As Worksheet
For Each WS In WB.Worksheets
' Loop through the ListObjects in each workshet:
For Each LO In WS.ListObjects
' If the ListObject's name is the name of the pivot table's soure data,
' set the LOWS to be the worksheet that contains the list object:
If LO.Name = PT.SourceData Then
Set LOWS = WB.Worksheets(LO.Parent.Name)
End If
Next LO
Next WS
Debug.Print LOWS.Name
End Sub
Maybe someone knows a more direct way.
You can also do like this-
std::map<char, int>::iterator it = m.find('c');
if (it != m.end())
(*it).second = 42;
If you are using Angular2+ following code will help
You can use following syntax to get attribute value from html element
//to retrieve html element
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p
//get attribute value from that element
const attributeValue = element.attributeName // like textContent/href
First stop the Server if its running. Go to "/Applications/MAMP/bin/", rename the PHP Version you don't need (MAMP is only allowed to use 2 PHP Versions), e.g. "_php5.2.17". Now MAMP will use the php versions that are left. Go to the MAMP Manager and then settings, then switch to the php version you need.
One problem with this solution I encountered was the httpd process (took me a while to figure that out xD). If you have the httpd process running in the background, then the php switch won't work, until you stop those processes (sometimes MAMP has an awkward problem to stop the server, thats why this process can be still alive). Start your Activity Monitor on your Mac (Shortcut: Press Command+Space and type in activity...), go to the Search Function and type in "httpd", close all those processes. Now you should be able to switch your PHP Version with the MAMP Manager.
For those looking for a solution from an Angular perspective, this worked for me:
$http.post(
'url',
{},
{responseType: 'arraybuffer'}
).then(function (response) {
var headers = response.headers();
var blob = new Blob([response.data],{type:headers['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Filename";
link.click();
});
Assuming that ids are unique and you'll only have to remove the one element splice
should do the trick:
var data = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
],
id = 88;
console.table(data);
$.each(data, function(i, el){
if (this.id == id){
data.splice(i, 1);
}
});
console.table(data);
You shouldn't need to let the users specify the margin on your website - Let them do it on their computer. Print dialogs usually (Adobe and Preview, at least) give you an option to scale and center the output on the printable area of the page:
Adobe
Preview
Of course, this assumes that you have computer literate users, which may or may not be the case.
if you want to create a new repository with the same project inside the github and the previous Remote is not allowing you to do that in that case First Delete That Repository on github then you simply need to delete the .git folder C:\Users\Shiva\AndroidStudioProjects\yourprojectname\.git delete that folder,(make sure you click on hidden file because this folder is hidden )
Also click on the minus(Remove button) from the android studio Setting->VersionControl click here for removing the Version control from android And then you will be able to create new Repository.
Alternatives to Nano (might make your life easier):
On Windows, use notepad. In command prompt type:
git config core.editor notepad
On Ubuntu / Linux, use text editor (gedit). In terminal window type:
git config core.editor gedit
To find the name of the current user within an Oracle session, use the USER
function.
Note that the owner of the constraint, the owner of the table containing the foreign key, and the owner of the referenced table may all be different. It sounds like it’s the table owner you’re interested in, in which case this should be close to what you want:
select Constraint_Name
from All_Constraints
where Table_Name = 'WHICHEVER_TABLE'
and Constraint_Type = 'R' and Owner = User;
Java 8
NOTE: All, but one, Date
's constructors are deprecated. Most of the Date
's methods are deprecated. REF: Date: Deprecated Methods. All, but Date::from(Instant)
, static methods are deprecated.
So, since java 8 consider using Instant
(immutable, thread-safe, leap-seconds aware) type rather than Date
. REF: Instant
static final LocalTime MARKETS_OPEN = LocalTime.of(07, 00);
static final LocalTime MARKETS_CLOSE = LocalTime.of(20, 00);
// Instant utcTime = testDate.toInstant();
var bigAppleTime = ZonedDateTime.ofInstant(utcTime, ZoneId.of("America/New_York"));
return !bigAppleTime.toLocalTime().isBefore(MARKETS_OPEN)
&& !bigAppleTime.toLocalTime().isAfter(MARKETS_CLOSE);
return bigAppleTime.toLocalTime().isAfter(MARKETS_OPEN)
&& bigAppleTime.toLocalTime().isBefore(MARKETS_CLOSE);
yes, if( (A) && (B) ) will fail on the first clause, if (A) evaluates false.
this applies to any language btw, not just C derivatives. For threaded and parallel processing this is a different story ;)
Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.
Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.
This example might help someone:
Note "origin
" is my alias for remote "What is on Github"
Note "mybranch
" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch
to show where the branch name parameter is used.
What exactly are my remote repos on github?
$ git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
Add the "other github repository of the same code" - we call this a fork:
$ git remote add someOtherRepo https://github.com/otherUser/Playground.git
$git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)
make sure our local repo is up to date:
$ git fetch
Change some stuff locally. let's say file ./foo/bar.py
$ git status
# On branch mybranch
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: foo/bar.py
Review my uncommitted changes
$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
Commit locally.
$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)
Now, I'm different than my remote (on github)
$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)
Diff this with remote - your fork:
(this is frequently done with git diff master origin
)
$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
(git push to apply these to remote)
How does my remote branch differ from the remote master branch?
$ git diff origin/mybranch origin/master
How does my local stuff differ from the remote master branch?
$ git diff origin/master
How does my stuff differ from someone else's fork, master branch of the same repo?
$git diff mybranch someOtherRepo/master
Doing maven update or reimporting the project did not help. @Sydney's answer is right; in addition I have to recreate the project in different workspace as said in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer
For IP address- adb shell ifconfig
under wlan0 Link encap:UNSPEC
you will have your ip address written
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
mail -r [email protected] -R [email protected]
-r = from-addr -R = reply-to addr
The author has indicated his version of mail doesn't support this flag. But if you have a version that does this works fine.
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
function readFromRegistry (strRegistryKey, strDefault )
Dim WSHShell, value
On Error Resume Next
Set WSHShell = CreateObject("WScript.Shell")
value = WSHShell.RegRead( strRegistryKey )
if err.number <> 0 then
readFromRegistry= strDefault
else
readFromRegistry=value
end if
set WSHShell = nothing
end function
Usage :
str = readfromRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Adobe\ESD\Install_Dir", "ha")
wscript.echo "returned " & str
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
studying the above answers almost worked for me ... but I still had a problem that I could 'fling' the view on 2.1 (seemed to be fixed with 2.2 & 2.3).
here is my final solution
public class MyWebView extends WebView
{
private boolean bAllowScroll = true;
@SuppressWarnings("unused") // it is used, just java is dumb
private long downtime;
public MyWebView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void setAllowScroll(int allowScroll)
{
bAllowScroll = allowScroll!=0;
if (!bAllowScroll)
super.scrollTo(0,0);
setHorizontalScrollBarEnabled(bAllowScroll);
setVerticalScrollBarEnabled(bAllowScroll);
}
@Override
public boolean onTouchEvent(MotionEvent ev)
{
switch (ev.getAction())
{
case MotionEvent.ACTION_DOWN:
if (!bAllowScroll)
downtime = ev.getEventTime();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!bAllowScroll)
{
try {
Field fmNumSamples = ev.getClass().getDeclaredField("mNumSamples");
fmNumSamples.setAccessible(true);
Field fmTimeSamples = ev.getClass().getDeclaredField("mTimeSamples");
fmTimeSamples.setAccessible(true);
long newTimeSamples[] = new long[fmNumSamples.getInt(ev)];
newTimeSamples[0] = ev.getEventTime()+250;
fmTimeSamples.set(ev,newTimeSamples);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
return super.onTouchEvent(ev);
}
@Override
public void flingScroll(int vx, int vy)
{
if (bAllowScroll)
super.flingScroll(vx,vy);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt)
{
if (bAllowScroll)
super.onScrollChanged(l, t, oldl, oldt);
else if (l!=0 || t!=0)
super.scrollTo(0,0);
}
@Override
public void scrollTo(int x, int y)
{
if (bAllowScroll)
super.scrollTo(x,y);
}
@Override
public void scrollBy(int x, int y)
{
if (bAllowScroll)
super.scrollBy(x,y);
}
}
You can type about:debug
in some of the mobile browsers to pull up a JavaScript console.
Not really an answer to the specific question, but if there are others, like me, who are getting this error in fastAPI and end up here:
It is probably because your route response has a value that can't be JSON serialised by jsonable_encoder
. For me it was WKBElement: https://github.com/tiangolo/fastapi/issues/2366
Like in the issue, I ended up just removing the value from the output.
Try using javascript:void(0)
as follows-
<a href="javascript:void(0)" onclick="...">Text</a>
Just change the version in Window-> Preferences-> Java -> Installed JREs. Check the installed JREs list. Then, Right-click on your project -> properties -> Java build path -> libraries. Change the "JRE System Library" to the version in "installed JREs".
The warning will be gone.
A vector
is functionally same as an array. But, to the language vector
is a type, and int
is also a type. To a function argument, an array of any type (including vector[]
) is treated as pointer. A vector<int>
is not same as int[]
(to the compiler). vector<int>
is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.
So, you must use vector<int>&
(preferably with const
, if function isn't modifying it) to pass it as a reference.
AMD:
CommonJS:
AMD
enforces.