CSS3 allows this sort of thing and it looks like this:
body {
background-image: url(images/bgtop.png), url(images/bg.png);
background-repeat: repeat-x, repeat;
}
The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:
<body>
<div id="bgTopDiv">
content here
</div>
</body>
body{
background-image: url(images/bg.png);
}
#bgTopDiv{
background-image: url(images/bgTop.png);
background-repeat: repeat-x;
}
I've gotten the following to work:
html {
background:
linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
url('bgimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
The above will produce a nice opaque blue overlay.
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
These three line all together worked for me.
background-image: url("pages/images/backImage.png");
background-size: 100%;
background-repeat: no-repeat;
I needed to do the same thing recently. Here's a simple implementation
#wrapper { width:100%; height:100%; position:relative; }_x000D_
#wrapper img { position:absolute; top:0; left:0; width:100%; height:auto; display:block; }_x000D_
#wrapper .top { animation:fadeOut 2s ease-in-out; animation-fill-mode:forwards; }_x000D_
@keyframes fadeOut {_x000D_
0% { opacity:1; }_x000D_
100% { opacity:0; }_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<img src="img1.jpg" class="top" style="z-index:2;">_x000D_
<img src="img2.jpg" style="z-index:1;">_x000D_
</div>
_x000D_
You should use like this:
body { background: url("img/debut_dark.png") repeat 0 0; } body { background: url("../img/debut_dark.png") repeat 0 0; } body { background-image: url("../img/debut_dark.png") repeat 0 0; }
or try Inspecting CSS Rules using Firefox Firebug tool.
html, body {
min-height: 100%;
}
Will do the trick.
By default, even html and body are only as big as the content they hold, but never more than the width/height of the windows. This can often lead to quite strange results.
You might also want to read http://css-tricks.com/perfect-full-page-background-image/
There are some great ways do achieve a very good and scalable full background image.
I created jquery.backgroundSize.js: a 1.5K jquery plugin that can be used as a IE8 fallback for "cover" and "contain" values. Have a look at the demo.
Solving your problem could be as simple as:
$("h2#news").css({backgroundSize: "cover"});
There are services like Filestack that will do this for you.
They take your image url and allow you to resize it using url parameters. It is pretty easy.
Your image would look like this after resizing to 200x100 but keeping the aspect ratio
The whole url looks like this
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
but the important part is just
resize=width:200/crop=d:[0,25,200,100]
You need to re-structure your HTML in order to do this. You have to blur the whole element in order to blur the background. So if you want to blur only the background, it has to be its own element.
Source location should be the URL (relative to the css file or full web location), not a file system full path, for example:
background: url("http://localhost/media/css/static/img/sprites/buttons-v3-10.png");
background: url("static/img/sprites/buttons-v3-10.png");
Alternatively, you can try to use file:///
protocol prefix.
Not sure that stretching a background image is possible. If you find that it's not possible, or not reliable in all of your target browsers, you could try using a stretched img tag with z-index set lower, and position set to absolute so that other content appears on top of it.
Let us know what you end up doing.
Edit: What I suggested is basically what's in gabriel's link. So try that :)
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.
@michi; define height
in your before
pseudo class
CSS:
#videos-part:before{
width: 16px;
content: " ";
background-image: url(/img/border-left3.png);
position: absolute;
left: -16px;
top: -6px;
height:20px;
}
I agree with yossi's example, stretch the image to fit the div but in a slightly different way (without background-image as this is a little inflexible in css 2.1). Show full image:
<div id="yourdiv">
<img id="theimage" src="image.jpg" alt="" />
</div>
#yourdiv img {
width:100%;
/*height will be automatic to remain aspect ratio*/
}
Show part of the image using background-position:
#yourdiv
{
background-image: url(image.jpg);
background-repeat: no-repeat;
background-position: 10px 25px;
}
Same as the first part of (1) the image will scale to the div so bigger or smaller will both work
Same as yossi's.
Instead of using background-image
you can use img
directly and to get the image to spread all the width of the viewport try using max-width:100%;
and please remember don't apply any padding or margin to your main container div as they will increase the total width of the container. Using this rule you can have a image width equal to the width of the browser and the height will also change according to the aspect ratio. Thanks.
Edit: Changing the image on different size of the window
$(window).resize(function(){_x000D_
var windowWidth = $(window).width();_x000D_
var imgSrc = $('#image');_x000D_
if(windowWidth <= 400){ _x000D_
imgSrc.attr('src','http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a');_x000D_
}_x000D_
else if(windowWidth > 400){_x000D_
imgSrc.attr('src','http://i.stack.imgur.com/oURrw.png');_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="image-container">_x000D_
<img id="image" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a" alt=""/>_x000D_
</div>
_x000D_
In this way you change your image in different size of the browser.
It seems you can provide just the local image name, assuming it is in the same folder...
It suffices like:
background-image: url("img1.png")
Using just one call to replace
(regex version):
var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');
Adaptive for square ratio with jQuery
var Height = $(window).height();
var Width = $(window).width();
var HW = Width/Height;
if(HW<1){
$(".background").css("background-size","auto 100%");
}
else if(HW>1){
$(".background").css("background-size","100% auto");
}
As shown in this example, you can apply a background to a canvas
element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL()
.
Here are the contents of the example, for Stack Overflow posterity:
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>Canvas Background through CSS</title>
<style type="text/css" media="screen">
canvas, img { display:block; margin:1em auto; border:1px solid black; }
canvas { background:url(lotsalasers.jpg) }
</style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#f00';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.strokeRect(140,60,40,40);
var img = document.getElementsByTagName('img')[0];
img.src = can.toDataURL();
</script>
</body></html>
u must specify the width and height also
<section class="bg-solid-light slideContainer strut-slide-0" style="background-image: url(https://accounts.icharts.net/stage/icharts-images/chartbook-images/Chart1457601371484.png); background-repeat: no-repeat;width: 100%;height: 100%;" >
CSS:
.reverse {
transform: rotate(180deg);
}
.rotate {
animation-duration: .5s;
animation-iteration-count: 1;
animation-name: yoyo;
animation-timing-function: linear;
}
@keyframes yoyo {
from { transform: rotate( 0deg); }
to { transform: rotate(360deg); }
}
Javascript:
$(buttonElement).click(function () {
$(".arrow").toggleClass("reverse")
return false
})
$(buttonElement).hover(function () {
$(".arrow").addClass("rotate")
}, function() {
$(".arrow").removeClass("rotate")
})
PS: I've found this somewhere else but don't remember the source
You can also use short trick to use image and color both like this :-
body {
background:#000 url('images/checked.png');
}
You can also use a linear gradient and an image: http://codepen.io/anon/pen/RPweox
.background{
background: linear-gradient(rgba(0,0,0,.5), rgba(0,0,0,.5)),
url('http://www.imageurl.com');
}
This is because the linear gradient function creates an Image which is added to the background stack. https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
background-position-x: center;
background-position-y: center;
In a bootstrap environment none of the top answers helped, but applying the following removed all borders:
.noBorder {
border:none !important;
}
Applied as:
<td class="noBorder">
HTML
<div class="thumb" data-image-src="img/image.png">
jQuery
$( ".thumb" ).each(function() {
var attr = $(this).attr('data-image-src');
if (typeof attr !== typeof undefined && attr !== false) {
$(this).css('background', 'url('+attr+')');
}
});
Demo on JSFiddle
You could do this also with JavaScript.
Add another div
or img
to your main div
and blur that instead. jsfiddle
.blur {
background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
background-size:cover;
-webkit-filter: blur(13px);
-moz-filter: blur(13px);
-o-filter: blur(13px);
-ms-filter: blur(13px);
filter: blur(13px);
position:absolute;
width:100%;
height:100%;
}
Like @ckpepper02 said, the body content:url option works well. I found however that if you modify it slightly you can just use it to add a header image of sorts using the :before pseudo element as follows.
@media print {
body:before { content: url(img/printlogo.png);}
}
That will slip the image at the top of the page, and from my limited testing, it works in Chrome and the IE9
-hanz
background-image
takes multiple values.
so a combination of just 1 color linear-gradient and css blend modes
will do the trick.
.testclass {
background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
background-blend-mode: overlay;
}
note that there is no support on IE/Edge for CSS blend-modes at all.
This answer is out of date and shouldn't be used.
1) Average latency is much faster on mobile in 2017. https://opensignal.com/reports/2016/02/usa/state-of-the-mobile-network
2) HTTP2 multiplexes https://http2.github.io/faq/#why-is-http2-multiplexed
"Data URIs" should definitely be considered for mobile sites. HTTP access over cellular networks comes with higher latency per request/response. So there are some use cases where jamming your images as data into CSS or HTML templates could be beneficial on mobile web apps. You should measure usage on a case-by-case basis -- I'm not advocating that data URIs should be used everywhere in a mobile web app.
Note that mobile browsers have limitations on total size of files that can be cached. Limits for iOS 3.2 were pretty low (25K per file), but are getting larger (100K) for newer versions of Mobile Safari. So be sure to keep an eye on your total file size when including data URIs.
http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/
<!DOCTYPE html>
<html>
<head></head>
<body>
<div style=" background-color: #00000088"> Hi there </div>
<!-- #00 would be r, 00 would be g, 00 would be b, 88 would be a. -->
</body>
</html>
including 4 sets of numbers would make it rgba, not cmyk, but either way would work (rgba= 00000088, cmyk= 0%, 0%, 0%, 50%)
I've figured out a solution that worked for me...
If you have a list item (or div) containing only the link, and let's say this is for social links on your page to facebook, twitter, ect. and you're using a sprite image you can do this:
<li id="facebook"><a href="facebook.com"></a></li>
Make the "li"s background your button image
#facebook {
width:30px;
height:30px;
background:url(images/social) no-repeat 0px 0px;
}
Then make the link's background image the hover state of the button. Also add the opacity attribute to this and set it to 0.
#facebook a {
display:inline-block;
background:url(images/social) no-repeat 0px -30px;
opacity:0;
}
Now all you need is "opacity" under "a:hover" and set this to 1.
#facebook a:hover {
opacity:1;
}
Add the opacity transition attributes for each browser to "a" and "a:hover" so the the final css will look something like this:
#facebook {
width:30px;
height:30px;
background:url(images/social) no-repeat 0px 0px;
}
#facebook a {
display:inline-block;
background:url(images/social) no-repeat 0px -30px;
opacity:0;
-webkit-transition: opacity 200ms linear;
-moz-transition: opacity 200ms linear;
-o-transition: opacity 200ms linear;
-ms-transition: opacity 200ms linear;
transition: opacity 200ms linear;
}
#facebook a:hover {
opacity:1;
-webkit-transition: opacity 200ms linear;
-moz-transition: opacity 200ms linear;
-o-transition: opacity 200ms linear;
-ms-transition: opacity 200ms linear;
transition: opacity 200ms linear;
}
If I explained it correctly that should let you have a fading background image button, hope it helps at least!
I also tried this style for ionic hybrid app background. this is also having style for background blur effect.
.bg-image {
position: absolute;
background: url(../img/bglogin.jpg) no-repeat;
height: 100%;
width: 100%;
background-size: cover;
bottom: 0px;
margin: 0 auto;
background-position: 50%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
Use: background-size: 100% 100%; To make background image to fit the div size.
Multiple backgrounds!
body {_x000D_
background: #eb01a5;_x000D_
background-image: url("IMAGE_URL"); /* fallback */_x000D_
background-image: url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531); /* W3C */_x000D_
}
_x000D_
These 2 lines are the fallback for any browser that doesn't do gradients. See notes for stacking images only IE < 9 below.
The final line sets a background image and gradient for browsers that can handle them.
Nearly all current browsers have support for multiple background images and css backgrounds. See http://caniuse.com/#feat=css-gradients for browser support. For a good post on why you don't need multiple browser prefixes, see http://codepen.io/thebabydino/full/pjxVWp/
Layer Stack
It should be noted that the first defined image will be topmost in the stack. In this case, the image is on TOP of the gradient.
For more information about background layering see http://www.w3.org/TR/css3-background/#layering.
Stacking images ONLY (no gradients in the declaration) For IE < 9
IE9 and up can stack images this same way. You could use this to create a gradient image for ie9, though personally, I wouldn't. However to be noted when using only images, ie < 9 will ignore the fallback statement and not show any image. This does not happen when a gradient is included. To use a single fallback image in this case I suggest using Paul Irish's wonderful Conditional HTML element along with your fallback code:
.lte9 #target{ background-image: url("IMAGE_URL"); }
Background position, sizing etc.
Other properties that would apply to a single image may also be comma separated. If only 1 value is supplied, that will be applied to all stacked images including the gradient. background-size: 40px;
will constrain both the image and the gradient to 40px height and width. However using background-size: 40px, cover;
will make the image 40px and the gradient will cover the element. To only apply a setting to one image, set the default for the other: background-position: 50%, 0 0;
or for browsers that support it use initial
: background-position: 50%, initial;
You may also use the background shorthand, however this removes the fallback color and image.
body{
background: url("IMAGE_URL") no-repeat left top, linear-gradient(#eb01a5, #d13531);
}
The same applies to background-position, background-repeat, etc.
Responding to an earlier comment, you can change the background by variable in the "container" example if the CSS is in your php page and not in the css style sheet.
$bgimage = '[some image url];
background-image: url('<?php echo $bgimage; ?>');
Add height & width properties to your .css file.
How about making the <div id="mainWrapperDivWithBGImage">
as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:
#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}
Then
HTML:
<div id="mainWrapperDivWithBGImage">
<div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
<div id="middle">
<div id="another_div"><img src="foo.gif" /></div>
<div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>
You may have to do position:relative; and such.
i just place one image in " d drive-->Data-->IMG". The image name is x.jpg
:
And on c# code type
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));
(please put double slash in between path)
this.Background = myBrush;
finally i got the background..
This is all you need:
background-repeat: no-repeat;
Just a small one to add, you should use the img tag if you want users to be able to 'right click' and 'save-image'/'save-picture', so if you intend to provide the image as a resource for others.
Using background image will (as far as I'm aware on most browsers) disable the option to save the image directly.
Try this:
body {
background-image:url(img/background.jpg);
background-repeat: no-repeat;
min-height: 679px;
background-size: cover;
}
I tried to do the same as you, but apparently the backgroundImage doesn't work with encoded data. As an alternative, I suggest to use CSS classes and the change between those classes.
If you are generating the data "on the fly" you can load the CSS files dynamically.
CSS:
.backgroundA {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDUxRjY0ODgyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDUxRjY0ODkyQTkxMTFFMjk0RkU5NjI5MEVDQTI2QzUiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpENTFGNjQ4NjJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpENTFGNjQ4NzJBOTExMUUyOTRGRTk2MjkwRUNBMjZDNSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuT868wAAABESURBVHja7M4xEQAwDAOxuPw5uwi6ZeigB/CntJ2lkmytznwZFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYW1qsrwABYuwNkimqm3gAAAABJRU5ErkJggg==");
}
.backgroundB {
background-image:url("data:image/gif;base64,R0lGODlhUAAPAKIAAAsLav///88PD9WqsYmApmZmZtZfYmdakyH5BAQUAP8ALAAAAABQAA8AAAPbWLrc/jDKSVe4OOvNu/9gqARDSRBHegyGMahqO4R0bQcjIQ8E4BMCQc930JluyGRmdAAcdiigMLVrApTYWy5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=");
}
HTML:
<div id="test" height="20px" class="backgroundA">
div test 1
</div>
<div id="test2" name="test2" height="20px" class="backgroundB">
div test2
</div>
<input type="button" id="btn" />
Javascript:
function change() {
if (document.getElementById("test").className =="backgroundA") {
document.getElementById("test").className="backgroundB";
document.getElementById("test2").className="backgroundA";
} else {
document.getElementById("test").className="backgroundA";
document.getElementById("test2").className="backgroundB";
}
}
btn.onclick= change;
I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/
There is actually a native solution to this, using the four-values to background-position
.CssClass {background-position: right 10px top 20px;}
This means 10px from right and 20px from top. you can also use three values the fourth value will be count as 0.
Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.
<div class="featured-image" style="height:300px">
<img id="thumbnail" src="01.jpg"/>
</div>
<div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
<img src='01.jpg'>
<img src='02.jpg'>
<img src='03.jpg'>
<img src='04.jpg'>
</div>
<script type="text/javascript">
function changeThumbnail()
{
$("#thumbnail").fadeOut(200);
var path=$("#thumbnail").attr('src');
var arr= new Array(); var i=0;
$("#thumblist img").each(function(index, element) {
arr[i]=$(this).attr('src');
i++;
});
var index= arr.indexOf(path);
if(index==(arr.length-1))
path=arr[0];
else
path=arr[index+1];
$("#thumbnail").attr('src',path).fadeIn(200);
setTimeout(changeThumbnail, 5000);
}
setTimeout(changeThumbnail, 5000);
</script>
You can use .toggle()
function instead of .click()
....
You can also use the java.util.Scanner class.
private static void readFileWithScanner() {
File file = new File("path/to/your/file/file.txt");
Scanner scan = null;
try {
scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] lineArray = line.split(",");
// do something with lineArray, such as instantiate an object
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scan.close();
}
}
Second Thomas David Kehoe, with the following caveat --
If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.
So ~/.nvm/versions/node/{version}/lib/node_modules/
.
In my case, I was getting verify error with below stack trace
jasperreports-server-cp-6.4.0-bin\buildomatic\build.xml:61: The following error occurred while executing this line:
TIB_js-jrs-cp_6.4.0_bin\jasperreports-server-cp-6.4.0-bin\buildomatic\bin\setup.xml:320: java.lang.VerifyError: (class: org/apache/commons/codec/binary/Base64OutputStream, method: <init> signature: (Ljava/io/OutputStream;ZI[B)V) Incompatible argument to function
at com.jaspersoft.jasperserver.crypto.KeystoreManager.createKeystore(KeystoreManager.java:257)
at com.jaspersoft.jasperserver.crypto.KeystoreManager.init(KeystoreManager.java:224)
at com.jaspersoft.buildomatic.crypto.KeystoreTask.execute(KeystoreTask.java:64)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:435)
at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:169)
at org.apache.tools.ant.taskdefs.ImportTask.importResource(ImportTask.java:222)
at org.apache.tools.ant.taskdefs.ImportTask.execute(ImportTask.java:163)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:435)
at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:180)
at org.apache.tools.ant.ProjectHelper.configureProject(ProjectHelper.java:93)
at org.apache.tools.ant.Main.runBuild(Main.java:826)
at org.apache.tools.ant.Main.startAnt(Main.java:235)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
I got it resolved by removing classpath entry for commons-codec-1.3.jar, there was a mismatch in version of this jar with the one comes with Jasper.
I was facing this problem even with use Illuminate\Http\Request;
line at the top of my controller. Kept pulling my hair till I realized that I was doing $request::ip()
instead of $request->ip()
. Can happen to you if you didn't sleep all night and are looking at the code at 6am with half-opened eyes.
Hope this helps someone down the road.
For a fully transparent background use:
background: transparent;
Otherwise for a semi-transparent color fill use:
background: rgba(255,255,255,0.5); // or hsla(0, 0%, 100%, 0.5)
where the values are:
background: rgba(red,green,blue,opacity); // or hsla(hue, saturation, lightness, opacity)
You can also use rgba values for gradient backgrounds.
To get transparency on an image background simply reduce the opacity of the image in an image editor of you choice beforehand.
AFAIK from Eclipse 3.5 M4 on the formatter has an option "Never Join Lines" which preserves user lines breaks. Maybe that does what you want.
Else there is this ugly hack
String query = //
"SELECT FOO, BAR, BAZ" + //
" FROM ABC" + //
" WHERE BAR > 4";
eplawless's own answer simply and effectively solves his specific problem: it replaces all "
instances in the entire argument list with \"
, which is how Bash requires double-quotes inside a double-quoted string to be represented.
To generally answer the question of how to escape double-quotes inside a double-quoted string using cmd.exe
, the Windows command-line interpreter (whether on the command line - often still mistakenly called the "DOS prompt" - or in a batch file):See bottom for a look at PowerShell.
tl;dr:
You must use ""
when passing a string to a(nother) batch file and you may use ""
with applications created with Microsoft's C/C++/.NET compilers (which also accept \"
), which on Windows includes Python and Node.js:
Example: foo.bat "We had 3"" of rain."
The following applies to batch files only:
""
is the only way to get the command interpreter (cmd.exe
) to treat the whole double-quoted string as a single argument.
Sadly, however, not only are the enclosing double-quotes retained (as usual), but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument, %1
:
set "str=%~1"
removes the enclosing double-quotes; set "str=%str:""="%"
then converts the doubled double-quotes to single ones.
Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.
\"
is required - as the only option - by many other programs, (e.g., Ruby, Perl, and even Microsoft's own Windows PowerShell(!)), but ITS USE IS NOT SAFE:
\"
is what many executables and interpreters either require - including Windows PowerShell - when passed strings from the outside - or, in the case of Microsoft's compilers, support as an alternative to ""
- ultimately, though, it's up to the target program to parse the argument list.
foo.exe "We had 3\" of rain."
\"
CAN RESULT IN UNWANTED, ARBITRARY EXECUTION OF COMMANDS and/or INPUT/OUTPUT REDIRECTIONS:
& | < >
ver
command; see further below for an explanation and the next bullet point for a workaround:
foo.exe "3\" of snow" "& ver."
\""
and "^""
are robust, but limited alternatives (see section "Calling PowerShell's CLI ..." below).If you must use \"
, there are only 3 safe approaches, which are, however quite cumbersome: Tip of the hat to T S for his help.
Using (possibly selective) delayed variable expansion in your batch file, you can store literal \"
in a variable and reference that variable inside a "..."
string using !var!
syntax - see T S's helpful answer.
Only with LITERAL strings - ones NOT involving VARIABLES - do you get a similarly methodical approach: categorically ^
-escape all cmd.exe
metacharacters: " & | < >
and - if you also want to suppress variable expansion - %
:
foo.exe ^"3\^" of snow^" ^"^& ver.^"
Otherwise, you must formulate your string based on recognizing which portions of the string cmd.exe
considers unquoted due to misinterpreting \"
as closing delimiters:
in literal portions containing shell metacharacters: ^
-escape them; using the example above, it is &
that must be ^
-escaped:
foo.exe "3\" of snow" "^& ver."
in portions with %...%
-style variable references: ensure that cmd.exe
considers them part of a "..."
string and that that the variable values do not themselves have embedded, unbalanced quotes - which is not even always possible.
For background information, read on.
Note: This is based on my own experiments. Do let me know if I'm wrong.
POSIX-like shells such as Bash on Unix-like systems tokenize the argument list (string) before passing arguments individually to the target program: among other expansions, they split the argument list into individual words (word splitting) and remove quoting characters from the resulting words (quote removal). The target program is handed an array of individual arguments, with syntactic quotes removed.
By contrast, the Windows command interpreter apparently does not tokenize the argument list and simply passes the single string comprising all arguments - including quoting chars. - to the target program.
However, some preprocessing takes place before the single string is passed to the target program: ^
escape chars. outside of double-quoted strings are removed (they escape the following char.), and variable references (e.g., %USERNAME%
) are interpolated first.
Thus, unlike in Unix, it is the target program's responsibility to parse to parse the arguments string and break it down into individual arguments with quotes removed. Thus, different programs can hypothetically require differing escaping methods and there's no single escaping mechanism that is guaranteed to work with all programs - https://stackoverflow.com/a/4094897/45375 contains excellent background on the anarchy that is Windows command-line parsing.
In practice, \"
is very common, but NOT SAFE, as mentioned above:
Since cmd.exe
itself doesn't recognize \"
as an escaped double-quote, it can misconstrue later tokens on the command line as unquoted and potentially interpret them as commands and/or input/output redirections.
In a nutshell: the problem surfaces, if any of the following characters follow an opening or unbalanced \"
: & | < >
; for example:
foo.exe "3\" of snow" "& ver."
cmd.exe
sees the following tokens, resulting from misinterpreting \"
as a regular double-quote:
"3\"
of
snow" "
& ver.
Since cmd.exe
thinks that & ver.
is unquoted, it interprets it as &
(the command-sequencing operator), followed by the name of a command to execute (ver.
- the .
is ignored; ver
reports cmd.exe
's version information).
The overall effect is:
foo.exe
is invoked with the first 3 tokens only.ver
is executed.Even in cases where the accidental command does no harm, your overall command won't work as designed, given that not all arguments are passed to it.
Many compilers / interpreters recognize ONLY \"
- e.g., the GNU C/C++ compiler, Python, Perl, Ruby, even Microsoft's own Windows PowerShell when invoked from cmd.exe
- and, except (with limitations) for Windows PowerShell with \""
, for them there is no simple solution to this problem.
Essentially, you'd have to know in advance which portions of your command line are misinterpreted as unquoted, and selectively ^
-escape all instances of & | < >
in those portions.
By contrast, use of ""
is SAFE, but is regrettably only supported by Microsoft-compiler-based executables and batch files (in the case of batch files, with the quirks discussed above), which notable excludes PowerShell - see next section.
cmd.exe
or POSIX-like shells:Note: See the bottom section for how quoting is handled inside PowerShell.
When invoked from the outside - e.g., from cmd.exe
, whether from the command line or a batch file:
PowerShell [Core] v6+ now properly recognizes ""
(in addition to \"
), which is both safe to use and whitespace-preserving.
pwsh -c " ""a & c"".length "
doesn't break and correctly yields 6
Windows PowerShell (the legacy edition whose last version is 5.1) recognizes only \"
and, on Windows also """
and the more robust \""
/ "^""
(even though internally PowerShell uses `
as the escape character in double-quoted strings and also accepts ""
- see bottom section):
Calling Windows PowerShell from cmd.exe
/ a batch file:
""
breaks, because it is fundamentally unsupported:
powershell -c " ""ab c"".length "
-> error "The string is missing the terminator"\"
and """
work in principle, but aren't safe:
powershell -c " \"ab c\".length "
works as intended: it outputs 5
(note the 2 spaces)cmd.exe
metacharacters break the command, unless escaped:powershell -c " \"a& c\".length "
breaks, due to the &
, which would have to be escaped as ^&
\""
is safe, but normalize interior whitespace, which can be undesired:
powershell -c " \""a& c\"".length "
outputs 4
(!), because the 2 spaces are normalized to 1."^""
is the best choice for Windows PowerShell specifically, where it is both safe and whitespace-preserving, but with PowerShell Core (on Windows) it is the same as \""
, i.e, whitespace-normalizing. Credit goes to Venryx for discovering this approach.
powershell -c " "^""a& c"^"".length "
works: doesn't break - despite &
- and outputs 5
, i.e., correctly preserved whitespace.
PowerShell Core: pwsh -c " "^""a& c"^"".length "
works, but outputs 4
, i.e. normalizes whitespace, as \""
does.
On Unix-like platforms (Linux, macOS), when calling PowerShell [Core]'s CLI, pwsh
, from a POSIX-like shell such as bash
:
You must use \"
, which, however is both safe and whitespace-preserving:
$ pwsh -c " \"a& c|\".length" # OK: 5
^
can only be used as the escape character in unquoted strings - inside double-quoted strings, ^
is not special and treated as a literal.
^
in parameters passed to the call
statement is broken (this applies to both uses of call
: invoking another batch file or binary, and calling a subroutine in the same batch file):
^
instances in double-quoted values are inexplicably doubled, altering the value being passed: e.g., if variable %v%
contains literal value a^b
, call :foo "%v%"
assigns "a^^b"
(!) to %1
(the first parameter) in subroutine :foo
.^
with call
is broken altogether in that ^
can no longer be used to escape special characters: e.g., call foo.cmd a^&b
quietly breaks (instead of passing literal a&b
too foo.cmd
, as would be the case without call
) - foo.cmd
is never even invoked(!), at least on Windows 7.Escaping a literal %
is a special case, unfortunately, which requires distinct syntax depending on whether a string is specified on the command line vs. inside a batch file; see https://stackoverflow.com/a/31420292/45375
%%
. On the command line, %
cannot be escaped, but if you place a ^
at the start, end, or inside a variable name in an unquoted string (e.g., echo %^foo%
), you can prevent variable expansion (interpolation); %
instances on the command line that are not part of a variable reference are treated as literals (e.g, 100%
).Generally, to safely work with variable values that may contain spaces and special characters:
set "v=a & b"
assigns literal value a & b
to variable %v%
(by contrast, set v="a & b"
would make the double-quotes part of the value). Escape literal %
instances as %%
(works only in batch files - see above).echo "%v%"
does not subject the value of %v%
to interpolation and prints "a & b"
(but note that the double-quotes are invariably printed too). By contrast, echo %v%
passes literal a
to echo
, interprets &
as the command-sequencing operator, and therefore tries to execute a command named b
.^
with the call
statement.%~1
to remove enclosing double-quotes from the 1st parameter) and, sadly, there is no direct way that I know of to get echo
to print a variable value faithfully without the enclosing double-quotes.
for
-based workaround that works as long as the value has no embedded double quotes; e.g.:set "var=^&')|;,%!"
for /f "delims=" %%v in ("%var%") do echo %%~v
cmd.exe
does not recognize single-quotes as string delimiters - they are treated as literals and cannot generally be used to delimit strings with embedded whitespace; also, it follows that the tokens abutting the single-quotes and any tokens in between are treated as unquoted by cmd.exe
and interpreted accordingly.
cmd.exe
.Windows PowerShell is a much more advanced shell than cmd.exe
, and it has been a part of Windows for many years now (and PowerShell Core brought the PowerShell experience to macOS and Linux as well).
PowerShell works consistently internally with respect to quoting:
`"
or ""
to escape double-quotes''
to escape single-quotesThis works on the PowerShell command line and when passing parameters to PowerShell scripts or functions from within PowerShell.
(As discussed above, passing an escaped double-quote to PowerShell from the outside requires \"
or, more robustly, \""
- nothing else works).
Sadly, when invoking external programs from PowerShell, you're faced with the need to both accommodate PowerShell's own quoting rules and to escape for the target program:
This problematic behavior is also discussed and summarized in this answer
Double-quotes inside double-quoted strings:
Consider string "3`" of rain"
, which PowerShell-internally translates to literal 3" of rain
.
If you want to pass this string to an external program, you have to apply the target program's escaping in addition to PowerShell's; say you want to pass the string to a C program, which expects embedded double-quotes to be escaped as \"
:
foo.exe "3\`" of rain"
Note how both `"
- to make PowerShell happy - and the \
- to make the target program happy - must be present.
The same logic applies to invoking a batch file, where ""
must be used:
foo.bat "3`"`" of rain"
By contrast, embedding single-quotes in a double-quoted string requires no escaping at all.
Single-quotes inside single-quoted strings do not require extra escaping; consider '2'' of snow'
, which is PowerShell' representation of 2' of snow
.
foo.exe '2'' of snow'
foo.bat '2'' of snow'
PowerShell translates single-quoted strings to double-quoted ones before passing them to the target program.
However, double-quotes inside single-quoted strings, which do not need escaping for PowerShell, do still need to be escaped for the target program:
foo.exe '3\" of rain'
foo.bat '3"" of rain'
PowerShell v3 introduced the magic --%
option, called the stop-parsing symbol, which alleviates some of the pain, by passing anything after it uninterpreted to the target program, save for cmd.exe
-style environment-variable references (e.g., %USERNAME%
), which are expanded; e.g.:
foo.exe --% "3\" of rain" -u %USERNAME%
Note how escaping the embedded "
as \"
for the target program only (and not also for PowerShell as \`"
) is sufficient.
However, this approach:
%
characters in order to avoid environment-variable expansions.Invoke-Expression
in a second.Thus, despite its many advancements, PowerShell has not made escaping much easier when calling external programs. It has, however, introduced support for single-quoted strings.
I wonder if it's fundamentally possible in the Windows world to ever switch to the Unix model of letting the shell do all the tokenization and quote removal predictably, up front, irrespective of the target program, and then invoke the target program by passing the resulting tokens.
Pure js alternative to window.open
let a= document.createElement('a');
a.target= '_blank';
a.href= 'https://support.wwf.org.uk/';
a.click();
here is working example (stackoverflow snippets not allow to opening)
[Belmiro@HP-550 ~]$ uname -a
Linux HP-550 2.6.30.10-105.2.23.fc11.x86_64 #1 SMP Thu Feb 11 07:06:34 UTC 2010
x86_64 x86_64 x86_64 GNU/Linux
[Belmiro@HP-550 ~]$ lsb_release -a
LSB Version: :core-3.1-amd64:core-3.1-noarch:core-3.2-amd64:core-3.2-noarch:deskt
op-3.1-amd64:desktop-3.1-noarch:desktop-3.2-amd64:desktop-3.2-noarch
Distributor ID: Fedora
Description: Fedora release 11 (Leonidas)
Release: 11
Codename: Leonidas
[Belmiro@HP-550 ~]$
$('#mainn').text(function (_,txt) {
return txt.slice(0, -1);
});
demo -->
http://jsfiddle.net/d72ML/8/
Select the Toggle Line Number Option from the View -> Toggle Line Number.
Use LayoutParams (as explained already). However be careful which LayoutParams to choose. According to https://stackoverflow.com/a/11971553/3184778 "you need to use the one that relates to the PARENT of the view you're working on, not the actual view"
If for example the TextView is inside a TableRow, then you need to use TableRow.LayoutParams instead of RelativeLayout or LinearLayout
I prefer this solution:
df = spark.table(selected_table).filter(condition)
counter = df.count()
df = df.select([(counter - count(c)).alias(c) for c in df.columns])
This appears to be an inside joke at Google. It's also featured in the Google Chrome task manager. It has no purpose, other than some engineers finding it amusing. Which is a purpose by itself, if you will.
Goats Teleported
column.There is even a huge Chromium bug report about too many teleported goats.
The following Chromium source code snippet is stolen from the HN comments.
int TaskManagerModel::GetGoatsTeleported(int index) const {
int seed = goat_salt_ * (index + 1);
return (seed >> 16) & 255;
}
Try this one Open your projectname.csproj file its work for me.
<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
You need to add this Reference "ItemGroup" tag inside.
I do it like this and it works:
var images = [imageFile]()
images.sorted(by: {$0.fileID.compare($1.fileID) == .orderedAscending })
The Content-Type
header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.
The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json
then parse it as JSON.
This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type
to detect what to do with it.
Recently I came across an issue in grep. I was trying to match the pattern x.y.z and grep returned x.y-z.Using some regular expression we may can overcome this, but with grep whole word matching did not help. Since the script I was writing is a generic one, I cannot restrict search for a specific way as in like x.y.z or x.y-z ..
Quick way I figured is to run a grep and then a condition check
var="x.y.z"
var1=grep -o x.y.z file.txt
if [ $var1 == $var ]
echo "Pattern match exact"
else
echo "Pattern does not match exact"
fi
https://linuxacatalyst.blogspot.com/2019/12/grep-pattern-matching-issues.html
public class RandomNum {
public static void main(String[] args) {
Random rn = new Random();
HashSet<Integer> hSet = new HashSet<>();
while(hSet.size() != 1000) {
hSet.add(rn.nextInt(1000));
}
System.out.println(hSet);
}
}
The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
The code up above doesn't work well when you need to make your items "wrap_content", because it measures both items height and width with MeasureSpec.UNSPECIFIED. After some troubles I've modified that solution so now items can expand. The only difference is that it provides parents height or width MeasureSpec depends on layout orientation.
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
if (getOrientation() == HORIZONTAL) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
heightSpec,
mMeasuredDimension);
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
measureScrapChild(recycler, i,
widthSpec,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
recycler.bindViewToPosition(view, position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:
Oracle Java SE 6: java.awt.Font
There is a tutorial available from Oracle that shows this example:
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
//Handle exception
}
I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.
An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.
Here's what I'm currently using. Some of the other techniques I've tried have been non-optimal because they changed the bit depth of the pixels (24-bit vs. 32-bit) or ignored the image's resolution (dpi).
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into
// Bitmap objects. This is static and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
Image to byte array:
/// <summary>
/// Method to "convert" an Image object into a byte array, formatted in PNG file format, which
/// provides lossless compression. This can be used together with the GetImageFromByteArray()
/// method to provide a kind of serialization / deserialization.
/// </summary>
/// <param name="theImage">Image object, must be convertable to PNG format</param>
/// <returns>byte array image of a PNG file containing the image</returns>
public static byte[] CopyImageToByteArray(Image theImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
theImage.Save(memoryStream, ImageFormat.Png);
return memoryStream.ToArray();
}
}
Byte array to Image:
/// <summary>
/// Method that uses the ImageConverter object in .Net Framework to convert a byte array,
/// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be
/// used as an Image object.
/// </summary>
/// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
/// <returns>Bitmap object if it works, else exception is thrown</returns>
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
Edit: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
This avoids problems related to Bitmap wanting its source stream to be kept open, and some suggested workarounds to that problem that result in the source file being kept locked.
border-radius:50%
if you want the circle to adjust to whatever dimensions the container gets (e.g. if the text is variable length)
Don't forget the (prefixing no longer needed)-moz-
and -webkit-
prefixes!
div{
border-radius: 50%;
display: inline-block;
background: lightgreen;
}
.a{
padding: 50px;
}
.b{
width: 100px;
height: 100px;
}
_x000D_
<div class='a'></div>
<div class='b'></div>
_x000D_
Try to use setStyle() in onCreate and override onCreateDialog make dialog without title
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
or just override onCreate() and setStyle fellow the code.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);
}
It would be O(n log n) if you built the heap by repeatedly inserting elements. However, you can create a new heap more efficiently by inserting the elements in arbitrary order and then applying an algorithm to "heapify" them into the proper order (depending on the type of heap of course).
See http://en.wikipedia.org/wiki/Binary_heap, "Building a heap" for an example. In this case you essentially work up from the bottom level of the tree, swapping parent and child nodes until the heap conditions are satisfied.
I have a Range
class in MiscUtil which you could find useful. Combined with the various extension methods, you could do:
foreach (DateTime date in StartDate.To(EndDate).ExcludeEnd()
.Step(DayInterval.Days())
{
// Do something with the date
}
(You may or may not want to exclude the end - I just thought I'd provide it as an example.)
This is basically a ready-rolled (and more general-purpose) form of mquander's solution.
Here's how I ended up doing this, just in case it works for someone else:
Remember that there's always risk in doing things like this, and its never a bad idea to create a save branch before starting.
Start by logging
git log --oneline
Scroll to first commit, copy SHA
git reset --soft <#sha#>
Replace <#sha#>
w/ the SHA copied from the log
git status
Make sure everything's green, otherwise run git add -A
git commit --amend
Amend all current changes to current first commit
Now force push this branch and it will overwrite what's there.
There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:
CREATE OR REPLACE FUNCTION prc_create_sch_foo_table() RETURNS VOID AS $$
BEGIN
EXECUTE 'CREATE TABLE /* IF NOT EXISTS add for PostgreSQL 9.1+ */ sch.foo (
id serial NOT NULL,
demo_column varchar NOT NULL,
demo_column2 varchar NOT NULL,
CONSTRAINT pk_sch_foo PRIMARY KEY (id));
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column ON sch.foo(demo_column);
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column2 ON sch.foo(demo_column2);'
WHERE NOT EXISTS(SELECT * FROM information_schema.tables
WHERE table_schema = 'sch'
AND table_name = 'foo');
EXCEPTION WHEN null_value_not_allowed THEN
WHEN duplicate_table THEN
WHEN others THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
END; $$ LANGUAGE plpgsql;
You could use a Scanner
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();
prints the following output:
1 2 red blue
First of all, android.graphics.Color is a class thats composed of only static methods. How and why did you create a new android.graphics.Color object? (This is completely useless and the object itself stores no data)
But anyways... I'm going to assume your using some object that actually stores data...
A integer is composed of 4 bytes (in java). Looking at the function getRGB() from the standard java Color object we can see java maps each color to one byte of the integer in the order ARGB (Alpha-Red-Green-Blue). We can replicate this behavior with a custom method as follows:
public int getIntFromColor(int Red, int Green, int Blue){
Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
Blue = Blue & 0x000000FF; //Mask out anything not blue.
return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}
This assumes you can somehow retrieve the individual red, green and blue colour components and that all the values you passed in for the colours are 0-255.
If your RGB values are in form of a float percentage between 0 and 1 consider the following method:
public int getIntFromColor(float Red, float Green, float Blue){
int R = Math.round(255 * Red);
int G = Math.round(255 * Green);
int B = Math.round(255 * Blue);
R = (R << 16) & 0x00FF0000;
G = (G << 8) & 0x0000FF00;
B = B & 0x000000FF;
return 0xFF000000 | R | G | B;
}
As others have stated, if you're using a standard java object, just use getRGB();
If you decide to use the android color class properly you can also do:
int RGB = android.graphics.Color.argb(255, Red, Green, Blue); //Where Red, Green, Blue are the RGB components. The number 255 is for 100% Alpha
or
int RGB = android.graphics.Color.rgb(Red, Green, Blue); //Where Red, Green, Blue are the RGB components.
as others have stated... (Second function assumes 100% alpha)
Both methods basically do the same thing as the first method created above.
In Bootstrap 4, you can add mx-auto
class to your img
tag.
For instance, if your image has a width of 75%, it should look like this:
<img class="d-block w-75 mx-auto" src="image.jpg" alt="First slide">
Bootstrap will automatically translate mx-auto
to:
ml-auto, .mx-auto {
margin-left: auto !important;
}
.mr-auto, .mx-auto {
margin-right: auto !important;
}
You can run multiple instances of Eclipse by creating a pseudonym for Eclipse application in it's folder and using it for running new Eclipse instance
Use clearAllTables() with RXJava like below inorder to avoid java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
getRoomDatabase().clearAllTables();
}
}).subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(new Action() {
@Override
public void run() throws Exception {
Log.d(TAG, "--- clearAllTables(): run() ---");
getInteractor().setUserAsLoggedOut();
getMvpView().openLoginActivity();
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.d(TAG, "--- clearAllTables(): accept(Throwable throwable) ----");
Log.d(TAG, "throwable.getMessage(): "+throwable.getMessage());
}
});
This actually worked for me:
private String uri2filename() {
String ret;
String scheme = uri.getScheme();
if (scheme.equals("file")) {
ret = uri.getLastPathSegment();
}
else if (scheme.equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
ret = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
}
return ret;
}
It is like Using the function without declaring it. header file will contain the function printf(). Include the header file in your program this is the solution for that. Some user defined functions may also through error when not declared before using it. If it is used globally no probs.
This produces the error description and nice clean, indented stacktrace:
begin
# Some exception throwing code
rescue => e
puts "Error during processing: #{$!}"
puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}"
end
Edit: Note that the original post has been edited since this answer was written and has been reformatted. You should look at the history to see the original formatting to understand the context for this answer.
This error occurs often when you have mismatched structure - that is, you do not have matching double quotes, matching single quotes, have not closed a control structure such as a missing fi
with an if
, or a missing done
with a for
.
The best way to spot these is to use correct indentation, which will show you where you have a broken control structure, and syntax highlighting, which will show you where quotes are not matched.
In this particular case, I can see you are missing a fi
. In the latter part of your code, you have 5 if
s and 4 fi
s. However you also have a number of other problems - your backquoted touch /tmp/alert.txt...
command is syntactically invalid, and you need a space before the closing bracket of an if
test.
Clean up your code, and errors start to stand out.
I came across this question while searching for a way to pick out the first item in one array that does not match any of the values in another array and managed to sort it out eventually with array.find() and array.filter() like this
var carList= ['mercedes', 'lamborghini', 'bmw', 'honda', 'chrysler'];
var declinedOptions = ['mercedes', 'lamborghini'];
const nextOption = carList.find(car=>{
const duplicate = declinedOptions.filter(declined=> {
return declined === car
})
console.log('duplicate:',duplicate) //should list out each declined option
if(duplicate.length === 0){//if theres no duplicate, thats the nextOption
return car
}
})
console.log('nextOption:', nextOption);
//expected outputs
//duplicate: mercedes
//duplicate: lamborghini
//duplicate: []
//nextOption: bmw
if you need to keep fetching an updated list before cross-checking for the next best option this should work well enough :)
The accepted answer is not (entirely) correct. Sure, it makes notification icons show in color, but does so with a BIG drawback - by setting the target SDK to lower than Android Lollipop!
If you solve your white icon problem by setting your target SDK to 20, as suggested, your app will not target Android Lollipop, which means that you cannot use Lollipop-specific features.
Have a look at http://developer.android.com/design/style/iconography.html, and you'll see that the white style is how notifications are meant to be displayed in Android Lollipop.
In Lollipop, Google also suggest that you use a color that will be displayed behind the (white) notification icon - https://developer.android.com/about/versions/android-5.0-changes.html
So, I think that a better solution is to add a silhouette icon to the app and use it if the device is running Android Lollipop.
For instance:
Notification notification = new Notification.Builder(context)
.setAutoCancel(true)
.setContentTitle("My notification")
.setContentText("Look, white in Lollipop, else color!")
.setSmallIcon(getNotificationIcon())
.build();
return notification;
And, in the getNotificationIcon method:
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.icon_silhouette : R.drawable.ic_launcher;
}
If you need to ask, then you need to explicitly initialize your fields/variables, because if you have to look it up, then chances are someone else needs to do that too.
The value for a primitive boolean
is false as can be seen here.
As mentioned by others the value for a Boolean
will be null by default.
You should create all your virtualenv
s in one folder, such as virt
.
Assuming your virtualenv folder name is virt, if not change it
cd
mkdir custom
Copy the below lines...
#!/usr/bin/env bash
ENV_PATH="$HOME/virt/$1/bin/activate"
bash --rcfile $ENV_PATH -i
Create a shell script file and paste the above lines...
touch custom/vhelper
nano custom/vhelper
Grant executable permission to your file:
sudo chmod +x custom/vhelper
Now export that custom folder path so that you can find it on the command-line by clicking tab...
export PATH=$PATH:"$HOME/custom"
Now you can use it from anywhere by just typing the below command...
vhelper YOUR_VIRTUAL_ENV_FOLDER_NAME
Suppose it is abc then...
vhelper abc
This will return the first 200 characters of words:
preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 201));
You can also use strstr
:
if (strstr(str, substr) == substr) {
// 'str' starts with 'substr'
}
but I think it's good only for short strings because it has to loop through the whole string when the string doesn't actually start with 'substr'.
With PHP 5.3, you can now do this:
function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.
Try with, as if if condition
returns false, so it will return empty otherwise nothing to return.
public String myMethod()
{
if(condition)
{
return x;
}
return ""
}
Because the compiler doesn't know if any of those if blocks will ever be reached, so it's giving you an error.
Yes it is possible. I have achieved using below implementation. for that I am getting array in response which I want in an object as list of attributes.
response = {
"equityMonths": [
{
"id": 1,
"month": "JANUARY",
"isEligible": false
},
{
"id": 2,
"month": "FEBRUARY",
"isEligible": true
},
{
"id": 3,
"month": "MARCH",
"isEligible": false
},
{
"id": 4,
"month": "APRIL",
"isEligible": true
},
{
"id": 5,
"month": "MAY",
"isEligible": false
},
{
"id": 6,
"month": "JUNE",
"isEligible": true
},
{
"id": 7,
"month": "JULY",
"isEligible": true
},
{
"id": 8,
"month": "AUGUST",
"isEligible": false
},
{
"id": 9,
"month": "SEPTEMBER",
"isEligible": true
},
{
"id": 10,
"month": "OCTOBER",
"isEligible": false
},
{
"id": 11,
"month": "NOVEMBER",
"isEligible": true
},
{
"id": 12,
"month": "DECEMBER",
"isEligible": false
}
]
}
here, I want equityMonths
as an object and Jan to Dec it's key and isEligible
as value. for that we have to use Object class's defineProperty()
method which allows to add dynamic property into objects.
code for adding property dynamically to the object.
let equityMonth = new Object();
response.equityMonths.forEach(element => {
Object.defineProperty(equityMonth, element['month'], {
value: element['isEligible'],
writable: true,
enumerable: true,
configurable: true
});
});
console.log("DATA : " + JSON.stringify(equityMonth));
in above code we have array of equityMonths
which we have converted as property into the object.
output:
DATA : {"JANUARY":false,"FEBRUARY":true,"MARCH":false,"APRIL":true,"MAY":false,"JUNE":true,"JULY":true,"AUGUST":false,"SEPTEMBER":true,"OCTOBER":false,"NOVEMBER":true,"DECEMBER":false}
If you do so, and you're using fail2ban, you will need to enable the proper filters/actions:
Put the following lines in /etc/fail2ban/jail.d/sshd.local
[ssh-iptables]
enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
logpath = /var/log/secure
maxretry = 5
bantime = 86400
Enable and start fail2ban:
systemctl enable fail2ban
systemctl start fail2ban
Reference: http://blog.iopsl.com/fail2ban-on-centos-7-to-protect-ssh-part-ii/
Edit!: Please be sure that you should have both Python installed on your computer.
Maybe my answer is late for you but I can help someone who has the same problem!
You don't have to download both Anaconda
.
If you are using Spyder
and Jupyter
in Anaconda environmen and,
If you have already Anaconda 2 type in Terminal:
python3 -m pip install ipykernel
python3 -m ipykernel install --user
If you have already Anaconda 3 then type in terminal:
python2 -m pip install ipykernel
python2 -m ipykernel install --user
Then before use Spyder
you can choose Python environment like below!
Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!
Also this is Jupyter. You can choose python version like this!
I hope it will help.
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
Short explanation looks like:
If you having troubles with interpreting results you could try BM.Sense results analysis service
Never thought MS could distribute this way, I understand that people downloading Visual Studio should have advanced knowledge of computers and OS but this is like a jump in time to 30 years back.
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
// for swift 2.2
// version 1
buttton.addTarget(self, action: #selector(ViewController.tappedButton), forControlEvents: .TouchUpInside)
buttton.addTarget(self, action: #selector(ViewController.tappedButton2(_:)), forControlEvents: .TouchUpInside)
// version 2
buttton.addTarget(self, action: #selector(self.tappedButton), forControlEvents: .TouchUpInside)
buttton.addTarget(self, action: #selector(self.tappedButton2(_:)), forControlEvents: .TouchUpInside)
// version 3
buttton.addTarget(self, action: #selector(tappedButton), forControlEvents: .TouchUpInside)
buttton.addTarget(self, action: #selector(tappedButton2(_:)), forControlEvents: .TouchUpInside)
func tappedButton() {
print("tapped")
}
func tappedButton2(sender: UIButton) {
print("tapped 2")
}
// swift 3.x
button.addTarget(self, action: #selector(tappedButton(_:)), for: .touchUpInside)
func tappedButton(_ sender: UIButton) {
// tapped
}
button.addTarget(self, action: #selector(tappedButton(_:_:)), for: .touchUpInside)
func tappedButton(_ sender: UIButton, _ event: UIEvent) {
// tapped
}
I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person
entity class ("entity" as in "something with an identity", for example an JPA entity). A Person
instance has friends, and for this Person
instance to return its friends, it shall delegate to its repository and query for friends there.
@Entity
public class Person {
private static PersonRepository personRepository;
@Id
@GeneratedValue
private long id;
public static void setPersonRepository(PersonRepository personRepository){
this.personRepository = personRepository;
}
public Set<Person> getFriends(){
return personRepository.getFriends(id);
}
...
}
.
@Repository
public class PersonRepository {
public Person get Person(long id) {
// do database-related stuff
}
public Set<Person> getFriends(long id) {
// do database-related stuff
}
...
}
So how did I inject that PersonRepository
singleton into the static field of the Person
class?
I created a @Configuration
, which gets picked up at Spring ApplicationContext construction time. This @Configuration
gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct
annotation, I catch a hook to do all static field injection logic.
@Configuration
public class StaticFieldInjectionConfiguration {
@Inject
private PersonRepository personRepository;
@PostConstruct
private void init() {
Person.setPersonRepository(personRepository);
}
}
You may find it better to use:
<EditText
...
android:inputType="textMultiLine"
/>
This is because android:singleLine
is deprecated.
It is also possible to include bitmaps. I think you also can use transformations on that.
There's no such thing as a "complete" list. Different people have different ways of measuring -- for example, they might include slang, neologisms, multi-word phrases, offensive terms, foreign words, verb conjugations, and so on. Some people have even counted a million words! So you'll have to decide what you want in a word list.
Does not seem like it, but android recognises a webcam as a device. Every time I run the emulator my webcam's active light comes on.
Instead using javascript, you could also use a label sending a hidden form. Very simple and small solution. The label can be anywhere in your html.
<form style="display: none" action="postUrl" method="post">_x000D_
<button type="submit" id="button_to_link"> </button>_x000D_
</form>_x000D_
<label style="text-decoration: underline" for="button_to_link"> link that posts </label>
_x000D_
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
For me, I would write an extension method like this:
public static string[] GetFieldNames(this SqlDataReader reader)
{
return Enumerable.Range(0, reader.FieldCount).Select(x => reader.GetName(x)).ToArray();
}
Since there currently isn't a MS SQL client for Mac OS X, I would, as Modesty has suggested, use Remote Desktop for the Mac.
Using Guava library, another option is to convert the Iterable
to a List
.
List list = Lists.newArrayList(some_iterator);
int count = list.size();
Use this if you need also to access the elements of the iterator after getting its size. By using Iterators.size()
you no longer can access the iterated elements.
I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.
I think you can't increase the time for query execution, but you need to increase the timeout for the request.
Execution Timeout Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.)
For Details, please have a look at https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.100%29.aspx
You can do in the web.config. e.g
<httpRuntime maxRequestLength="2097152" executionTimeout="600" />
For people finding this post and using PHP5.5+, this might help.
I was finding the approach suggested by netcoder wasn't working. i.e. this didn't work:
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
I would receive in the $_POST
var the 'uploaded_file'
field - and nothing in the $_FILES
var.
It turns out that for php5.5+ there is a new curl_file_create()
function you need to use. So the above would become:
$data = array(
'uploaded_file' => curl_file_create($tmpfile, $_FILES['image']['type'], $filename)
);
As the @
format is now deprecated.
That worked for me in WPF application:
string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();
You have to encode your email as multipart mime and then you can attach emails as attachments basically. You reference them by cid in the email.
Alternatively you could not attach them to the email and use URLs directly but most mail programs will block this as spammers use the trick to detect the liveness of email addresses.
You don't say what language but here is one example.
Use the following class, updated to the last API level: 29.
// License: MIT
// http://opensource.org/licenses/MIT
package net.i2p.android.router.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.telephony.TelephonyManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.CancellationException;
/**
* Check device's network connectivity and speed.
*
* @author emil http://stackoverflow.com/users/220710/emil
* @author str4d
* @author rodrigo https://stackoverflow.com/users/5520417/rodrigo
*/
public class ConnectivityAndInternetAccessCheck {
private static ArrayList < String > hosts = new ArrayList < String > () {
{
add("google.com");
add("facebook.com");
add("apple.com");
add("amazon.com");
add("twitter.com");
add("linkedin.com");
add("microsoft.com");
}
};
/**
* Get the network info.
*
* @param context the Context.
* @return the active NetworkInfo.
*/
private static NetworkInfo getNetworkInfo(Context context) {
NetworkInfo networkInfo = null;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo;
}
/**
* Gets the info of all networks
* @param context The context
* @return an array of @code{{@link NetworkInfo}}
*/
private static NetworkInfo[] getAllNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getAllNetworkInfo();
}
/**
* Gives the connectivity manager
* @param context The context
* @return the @code{{@link ConnectivityManager}}
*/
private static ConnectivityManager getConnectivityManager(Context context) {
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* Check if there is any connectivity at all.
*
* @param context the Context.
* @return true if we are connected to a network, false otherwise.
*/
public static boolean isConnected(Context context) {
boolean isConnected = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager connectivityManager = ConnectivityAndInternetAccessCheck.getConnectivityManager(context);
Network[] networks = connectivityManager.getAllNetworks();
networksloop: for (Network network: networks) {
if (network == null) {
isConnected = false;
} else {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)){
isConnected = true;
break networksloop;
}
else {
isConnected = false;
}
}
}
} else {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkinfosloop: for (NetworkInfo info: networkInfos) {
// Works on emulator and devices.
// Note the use of isAvailable() - without this, isConnected() can
// return true when Wifi is disabled.
// http://stackoverflow.com/a/2937915
isConnected = info != null && info.isAvailable() && info.isConnected();
if (isConnected) {
break networkinfosloop;
}
}
}
return isConnected;
}
/**
* Check if there is any connectivity to a Wifi network.
*
* @param context the Context.
* @return true if we are connected to a Wifi network, false otherwise.
*/
public static boolean isConnectedWifi(Context context) {
boolean isConnectedWifi = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager connectivityManager = ConnectivityAndInternetAccessCheck.getConnectivityManager(context);
Network[] networks = connectivityManager.getAllNetworks();
networksloop: for (Network network: networks) {
if (network == null) {
isConnectedWifi = false;
} else {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)){
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
isConnectedWifi = true;
break networksloop;
} else {
isConnectedWifi = false;
}
}
}
}
} else {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkinfosloop: for (NetworkInfo n: networkInfos) {
isConnectedWifi = n != null && n.isAvailable() && n.isConnected() && n.getType() == ConnectivityManager.TYPE_WIFI;
if (isConnectedWifi) {
break networkinfosloop;
}
}
}
return isConnectedWifi;
}
/**
* Check if there is any connectivity to a mobile network.
*
* @param context the Context.
* @return true if we are connected to a mobile network, false otherwise.
*/
public static boolean isConnectedMobile(Context context) {
boolean isConnectedMobile = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager connectivityManager = ConnectivityAndInternetAccessCheck.getConnectivityManager(context);
Network[] allNetworks = connectivityManager.getAllNetworks();
networksloop: for (Network network: allNetworks) {
if (network == null) {
isConnectedMobile = false;
} else {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)){
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
isConnectedMobile = true;
break networksloop;
} else {
isConnectedMobile = false;
}
}
}
}
} else {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkinfosloop: for (NetworkInfo networkInfo: networkInfos) {
isConnectedMobile = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if (isConnectedMobile) {
break networkinfosloop;
}
}
}
return isConnectedMobile;
}
/**
* Check if there is fast connectivity.
*
* @param context the Context.
* @return true if we have "fast" connectivity, false otherwise.
*/
public static boolean isConnectedFast(Context context) {
boolean isConnectedFast = false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkInfosloop:
for (NetworkInfo networkInfo: networkInfos) {
isConnectedFast = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected() && isConnectionFast(networkInfo.getType(), networkInfo.getSubtype());
if (isConnectedFast) {
break networkInfosloop;
}
}
} else {
throw new UnsupportedOperationException();
}
return isConnectedFast;
}
/**
* Check if the connection is fast.
*
* @param type the network type.
* @param subType the network subtype.
* @return true if the provided type/subtype combination is classified as fast.
*/
private static boolean isConnectionFast(int type, int subType) {
if (type == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (type == ConnectivityManager.TYPE_MOBILE) {
switch (subType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
/*
* Above API level 7, make sure to set android:targetSdkVersion
* to appropriate level to use these
*/
case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11
return true; // ~ 1-2 Mbps
case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
return true; // ~ 5 Mbps
case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
return true; // ~ 10-20 Mbps
case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
return false; // ~25 kbps
case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
return true; // ~ 10+ Mbps
// Unknown
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
default:
return false;
}
} else {
return false;
}
}
public ArrayList < String > getHosts() {
return hosts;
}
public void setHosts(ArrayList < String > hosts) {
this.hosts = hosts;
}
//TODO Debug on devices
/**
* Checks that Internet is available by pinging DNS servers.
*/
private static class InternetConnectionCheckAsync extends AsyncTask < Void, Void, Boolean > {
private Context context;
/**
* Creates an instance of this class
* @param context The context
*/
public InternetConnectionCheckAsync(Context context) {
this.setContext(context);
}
/**
* Cancels the activity if the device is not connected to a network.
*/
@Override
protected void onPreExecute() {
if (!ConnectivityAndInternetAccessCheck.isConnected(getContext())) {
cancel(true);
}
}
/**
* Tells whether there is Internet access
* @param voids The list of arguments
* @return True if Internet can be accessed
*/
@Override
protected Boolean doInBackground(Void...voids) {
return isConnectedToInternet(getContext());
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
/**
* The context
*/
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
} //network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException
/**
* Tells whether Internet is reachable
* @return true if Internet is reachable, false otherwise
* @param context The context
*/
public static boolean isInternetReachable(Context context) {
try {
return new InternetConnectionCheckAsync(context).execute().get();
} catch (CancellationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* Tells whether there is Internet connection
* @param context The context
* @return @code {true} if there is Internet connection
*/
private static boolean isConnectedToInternet(Context context) {
boolean isAvailable = false;
if (!ConnectivityAndInternetAccessCheck.isConnected(context)) {
isAvailable = false;
} else {
try {
foreachloop: for (String h: new ConnectivityAndInternetAccessCheck().getHosts()) {
if (isHostAvailable(h)) {
isAvailable = true;
break foreachloop;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
return isAvailable;
}
/**
* Checks if the host is available
* @param hostName
* @return
* @throws IOException
*/
private static boolean isHostAvailable(String hostName) throws IOException {
try (Socket socket = new Socket()) {
int port = 80;
InetSocketAddress socketAddress = new InetSocketAddress(hostName, port);
socket.connect(socketAddress, 3000);
return true;
} catch (UnknownHostException unknownHost) {
return false;
}
}
}
Looking forward to Web Animations in 2020.
async function moveToPosition(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
transform: `translateY(${el.getBoundingClientRect().top}px)`
},
], {
duration: durationInMs,
easing: 'ease-in',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeIn(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
opacity: '0.5',
offset: 0.5
},
{
opacity: '1',
offset: 1
}
], {
duration: durationInMs,
easing: 'linear',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeInSections() {
for (const section of document.getElementsByTagName('section')) {
await fadeIn(section, 200);
}
}
window.addEventListener('load', async() => {
await moveToPosition(document.getElementById('headerContent'), 500);
await fadeInSections();
await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
height: 100vh;
}
header {
height: 20%;
}
.text-center {
text-align: center;
}
.leading-none {
line-height: 1;
}
.leading-3 {
line-height: .75rem;
}
.leading-2 {
line-height: .25rem;
}
.bg-black {
background-color: rgba(0, 0, 0, 1);
}
.bg-gray-50 {
background-color: rgba(249, 250, 251, 1);
}
.pt-12 {
padding-top: 3rem;
}
.pt-2 {
padding-top: 0.5rem;
}
.text-lightGray {
color: lightGray;
}
.container {
display: flex;
/* or inline-flex */
justify-content: space-between;
}
.container section {
padding: 0.5rem;
}
.opacity-0 {
opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Web site created using create-snowpack-app" />
<link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>
<body>
<header class="bg-gray-50">
<div id="headerContent">
<h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
<p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
</div>
</header>
<div class="container">
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 1</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 2</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 3</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
</div>
<footer class="opacity-0">
<h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
<p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
</footer>
</body>
</html>
_x000D_
How are you running the file? Is it from the command line or from an IDE? The directory that your executable is in is not necessarily your working directory.
Try using the full path name in the fopen
and see if that fixes it. If so, then the problem is as described.
For example:
file = fopen("c:\\MyDirectory\\TestFile1.txt", "r");
file = fopen("/full/path/to/TestFile1.txt", "r");
Or open up a command window and navigate to the directory where your executable is, then run it manually.
As an aside, you can insert a simple (for Windows or Linux/UNIX/BSD/etc respectively):
system ("cd")
system("pwd")
before the fopen
to show which directory you're actually in.
Since fields
or fns
are cell arrays, you have to index with curly brackets {}
in order to access the contents of the cell, i.e. the string.
Note that instead of looping over a number, you can also loop over fields
directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for fn=fields'
fn
%# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
teststruct.(fn{1})
end
The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename
method. See this deprecation note in the documentation for more detail.
This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg
method.
These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.
Before we get there, let's create a four column DataFrame.
df = pd.DataFrame({'A' : list('wwwwxxxx'),
'B':list('yyzzyyzz'),
'C':np.random.rand(8),
'D':np.random.rand(8)})
A B C D
0 w y 0.643784 0.828486
1 w y 0.308682 0.994078
2 w z 0.518000 0.725663
3 w z 0.486656 0.259547
4 x y 0.089913 0.238452
5 x y 0.688177 0.753107
6 x z 0.955035 0.462677
7 x z 0.892066 0.368850
Let's say we want to group by columns A, B
and aggregate column C
with mean
and median
and aggregate column D
with max
. The following code would do this.
df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})
D C
max mean median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:
df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'},
'D':{'D_max': 'max'}})
D C
D_max C_mean C_median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0)
.
I couldn't do it on a Galaxy S3 (non rooted).
For me it would hang saying...
restaring in tcp mode
So i found this series of commands quite useful.
First disconnect your device, start from scratch (cmd in admin mode and all the stuff).
connect your device and write in CMD/Terminal:
adb kill-server
control should return as normal. Now type and enter
adb tcpip 5555
you will see..
- daemon not running. starting it now on port 5037 *
- daemon started successfully * restarting in TCP mode port: 5555
and then connect device with
adb connect <IP>
That's how it worked for me after a lot of hassle!
UPDATE FOR ANDROID STUDIO
I noticed this doesn't work sometimes, even after correctly repeating steps a number of times. Catch was; sometimes ADB is yet not initialized by Studio unless, Android Tab at the bottom is opened and you see "Initializing Android Studio".
Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).
This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.
Programatically, you may want to publish the application launcher yourself :
Note: this method no longer works starting with Android 8.0 - Oreo
In your AndroidManifest.xml, add :
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
Then you need create your app launcher intent:
Intent myLauncherIntent = new Intent();
myLauncherIntent.setClassName("your.package.name", "YourLauncherActivityName");
myLauncherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Create an install shortcut intent with your app launcher and custom icon:
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myLauncherIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Application Name");
intent.putExtra
(
Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext
(
getApplicationContext(),
R.drawable.app_icon
)
);
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
And finally launch the broadcast intent:
getApplicationContext().sendBroadcast(intent);
According to theory its the same things. Recursion and loop with the same O() complexity will work with the same theoretical speed, but of course real speed depends on language, compiler and processor. Example with power of number can be coded in iteration way with O(ln(n)):
int power(int t, int k) {
int res = 1;
while (k) {
if (k & 1) res *= t;
t *= t;
k >>= 1;
}
return res;
}
The most contextual description of JavaScript's Automatic Semicolon Insertion I have found comes from a book about Crafting Interpreters.
JavaScript’s “automatic semicolon insertion” rule is the odd one. Where other languages assume most newlines are meaningful and only a few should be ignored in multi-line statements, JS assumes the opposite. It treats all of your newlines as meaningless whitespace unless it encounters a parse error. If it does, it goes back and tries turning the previous newline into a semicolon to get something grammatically valid.
He goes on to describe it as you would code smell.
This design note would turn into a design diatribe if I went into complete detail about how that even works, much less all the various ways that that is a bad idea. It’s a mess. JavaScript is the only language I know where many style guides demand explicit semicolons after every statement even though the language theoretically lets you elide them.
Try this one:
echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"
The ps
command produces output like this, with the PID in the first column and the executable name (only) in the second column:
bookworm% ps -ceo pid=,comm=
1 launchd
10 kextd
11 UserEventAgent
12 mDNSResponder
13 opendirectoryd
14 notifyd
15 configd
...which awk
processes, printing the first column (pid) and exiting after the first match.
The simplest way to remove duplicates whilst preserving order is to use collections.OrderedDict (Python 2.7+).
from collections import OrderedDict
d = OrderedDict()
for x in mylist:
d[x] = True
print d.iterkeys()
When the following is invoked within a shell script, the terminal prompt will appear just like many other unix commands do when they are run with sudo
:
# get superuser password
user=$(whoami)
stty -echo
read -p "[sudo] password for $user: " password
stty echo
echo ""
Then you can use $password
as needed.
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
It's in the python docs.
import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1),
datetime.time(10, 23))
returns
datetime.datetime(2011, 1, 1, 10, 23)
there are two properties of urllib.URLopener()
namely:
addheaders = [('User-Agent', 'Python-urllib/1.17'), ('Accept', '*/*')]
and
version = 'Python-urllib/1.17'
.
To fool the website you need to changes both of these values to an accepted User-Agent. for e.g.
Chrome browser : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36'
Google bot : 'Googlebot/2.1'
like this
import urllib
page_extractor=urllib.URLopener()
page_extractor.addheaders = [('User-Agent', 'Googlebot/2.1'), ('Accept', '*/*')]
page_extractor.version = 'Googlebot/2.1'
page_extractor.retrieve(<url>, <file_path>)
changing just one property does not work because the website marks it as a suspicious request.
I always use this code below for more readable
$('table').append([
'<tr>',
'<td>My Item 1</td>',
'<td>My Item 2</td>',
'<td>My Item 3</td>',
'<td>My Item 4</td>',
'</tr>'
].join(''));
or if it have tbody
$('table').find('tbody').append([
'<tr>',
'<td>My Item 1</td>',
'<td>My Item 2</td>',
'<td>My Item 3</td>',
'<td>My Item 4</td>',
'</tr>'
].join(''));
In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :
@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}
Spring doc about Aggregating @Configuration classes with @Import: link
This subclass uses center if the image is not larger than the view, otherwise it scales down. I found this useful for a UIImageView
that changes the size.
The image it displays is smaller than the view for large sizes, but larger than the view for small sizes. I want it only to scale down, but not up.
class CenterScaleToFitImageView: UIImageView {
override var bounds: CGRect {
didSet {
adjustContentMode()
}
}
override var image: UIImage? {
didSet {
adjustContentMode()
}
}
func adjustContentMode() {
guard let image = image else {
return
}
if image.size.width > bounds.size.width ||
image.size.height > bounds.size.height {
contentMode = .ScaleAspectFit
} else {
contentMode = .Center
}
}
}
If you are using Reactive Forms you can use this:
<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>
Because if you want to trigger your data with deep of it,you have to pass 3th argument true
of your listener.By default it's false
and it meens that you function will trigger,only when your variable will change not it's field.
If you want your variables to be valid for all tests, you can have an application.properties
file in your test resources directory (by default: src/test/resources
) which will look something like this:
MYPROPERTY=foo
This will then be loaded and used unless you have definitions via @TestPropertySource
or a similar method - the exact order in which properties are loaded can be found in the Spring documentation chapter 24. Externalized Configuration.
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
With ASP.NET Core 2.0, the ideal way to return object from Web API
(which is unified with MVC and uses same base class Controller
) is
public IActionResult Get()
{
return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}
Notice that
200 OK
status code (it's an Ok
type of ObjectResult
)Accept
header in request. If Accept: application/xml
is sent in request, it'll return as XML
. If nothing is sent, JSON
is default.If it needs to send with specific status code, use ObjectResult
or StatusCode
instead. Both does the same thing, and supports content negotiation.
return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });
or even more fine grained with ObjectResult:
Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };
If you specifically want to return as JSON, there are couple of ways
//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
return Json(new Item { Id = 123, Name = "Hero" });
}
//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
return new Item { Id = 123, Name = "Hero" };
}
Notice that
JSON
in two different ways.Json(object)
.Produces()
attribute (which is a ResultFilter
) with contentType = application/json
Read more about them in the official docs. Learn about filters here.
The simple model class that is used in the samples
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
Here is a class which I'm using in one of my projects. It redirects output of a subprocess to the log. At first I tried simply overwriting the write-method but that doesn't work as the subprocess will never call it (redirection happens on filedescriptor level). So I'm using my own pipe, similar to how it's done in the subprocess-module. This has the advantage of encapsulating all logging/printing logic in the adapter and you can simply pass instances of the logger to Popen
: subprocess.Popen("/path/to/binary", stderr = LogAdapter("foo"))
class LogAdapter(threading.Thread):
def __init__(self, logname, level = logging.INFO):
super().__init__()
self.log = logging.getLogger(logname)
self.readpipe, self.writepipe = os.pipe()
logFunctions = {
logging.DEBUG: self.log.debug,
logging.INFO: self.log.info,
logging.WARN: self.log.warn,
logging.ERROR: self.log.warn,
}
try:
self.logFunction = logFunctions[level]
except KeyError:
self.logFunction = self.log.info
def fileno(self):
#when fileno is called this indicates the subprocess is about to fork => start thread
self.start()
return self.writepipe
def finished(self):
"""If the write-filedescriptor is not closed this thread will
prevent the whole program from exiting. You can use this method
to clean up after the subprocess has terminated."""
os.close(self.writepipe)
def run(self):
inputFile = os.fdopen(self.readpipe)
while True:
line = inputFile.readline()
if len(line) == 0:
#no new data was added
break
self.logFunction(line.strip())
If you don't need logging but simply want to use print()
you can obviously remove large portions of the code and keep the class shorter. You could also expand it by an __enter__
and __exit__
method and call finished
in __exit__
so that you could easily use it as context.
Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters
just go to BUILD->Build APK and it's done
It is best to also quote $1:
sed -i.bak 's/[[:blank:]]*$//' "$1"
Try Server.UrlEncode()
, or System.Web.HttpUtility.UrlEncode()
for instances when you don't have access to the Server
object. You can also use System.Uri.EscapeUriString()
to avoid adding a reference to the System.Web
assembly.
Finding a linear model such as this one can be handled with OpenTURNS.
In OpenTURNS this is done with the LinearModelAlgorithm
class which creates a linear model from numerical samples. To be more specific, it builds the following linear model :
Y = a0 + a1.X1 + ... + an.Xn + epsilon,
where the error epsilon is gaussian with zero mean and unit variance. Assuming your data is in a csv file, here is a simple script to get the regression coefficients ai :
from __future__ import print_function
import pandas as pd
import openturns as ot
# Assuming the data is a csv file with the given structure
# Y X1 X2 .. X7
df = pd.read_csv("./data.csv", sep="\s+")
# Build a sample from the pandas dataframe
sample = ot.Sample(df.values)
# The observation points are in the first column (dimension 1)
Y = sample[:, 0]
# The input vector (X1,..,X7) of dimension 7
X = sample[:, 1::]
# Build a Linear model approximation
result = ot.LinearModelAlgorithm(X, Y).getResult()
# Get the coefficients ai
print("coefficients of the linear regression model = ", result.getCoefficients())
You can then easily get the confidence intervals with the following call :
# Get the confidence intervals at 90% of the ai coefficients
print(
"confidence intervals of the coefficients = ",
ot.LinearModelAnalysis(result).getCoefficientsConfidenceInterval(0.9),
)
You may find a more detailed example in the OpenTURNS examples.
Try this code:
$(document).ready(function(){
$('#YourControlID').click(function(){
if() { //your condition
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
}
});
});
I encountered this exact problem where my client was on Atlantic Standard Time. The date value the client retrieved was "2018-11-23" and when the code passed it into new Date("2018-11-23")
the output for the client was for the previous day. I created a utility function as shown in the snippet that normalized the date, giving the client the expected date.
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
var normalizeDate = function(date) {_x000D_
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());_x000D_
return date;_x000D_
};_x000D_
_x000D_
var date = new Date("2018-11-23");_x000D_
_x000D_
document.getElementById("default").textContent = date;_x000D_
document.getElementById("normalized").textContent = normalizeDate(date);
_x000D_
<h2>Calling new Date("2018-11-23")</h2>_x000D_
<div>_x000D_
<label><b>Default</b> : </label>_x000D_
<span id="default"></span>_x000D_
</div>_x000D_
<hr>_x000D_
<div>_x000D_
<label><b>Normalized</b> : </label>_x000D_
<span id="normalized"></span>_x000D_
</div>
_x000D_
If you wish to use GIT CLI and not interact with the build in GIT wrappers in Visual Studio you need to enable Alternate Authentication Credentials
Open your account (VS Online account)
-> click on your name on the top right
-> My Profile
-> Credentials.
and set it up.
sys.exit(myString)
doesn't mean "return this string". If you pass a string to sys.exit
, sys.exit
will consider that string to be an error message, and it will write that string to stderr
. The closest concept to a return value for an entire program is its exit status, which must be an integer.
If you want to capture output written to stderr, you can do something like
python yourscript 2> return_file
You could do something like that in your bash script
output=$((your command here) 2> &1)
This is not guaranteed to capture only the value passed to sys.exit
, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.
example:
test.py
print "something"
exit('ohoh')
t.sh
va=$(python test.py 2>&1)
mkdir $va
bash t.sh
edit
Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.
import script1
import script2
if __name__ == '__main__':
filename = script1.run(sys.args)
script2.run(filename)
I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.
If you use Visual Studio, download "AWS Toolkit for Visual Studio".
After installed, go to Visual Studio - AWS Explorer - S3 - Your bucket - Double click
In the window you will be able to select all files. Right click and download files.
I found the instructions at http://www.czeskis.com/random/openssl-encrypt-file.html useful.
To paraphrase the linked site with filenames from your example:
Generate a symmetric key because you can encrypt large files with it
openssl rand -base64 32 > key.bin
Encrypt the large file using the symmetric key
openssl enc -aes-256-cbc -salt -in myLargeFile.xml \ -out myLargeFile.xml.enc -pass file:./key.bin
Encrypt the symmetric key so you can safely send it to the other person
openssl rsautl -encrypt -inkey public.pem -pubin -in key.bin -out key.bin.enc
Destroy the un-encrypted symmetric key so nobody finds it
shred -u key.bin
At this point, you send the encrypted symmetric key (
key.bin.enc
) and the encrypted large file (myLargeFile.xml.enc
) to the other personThe other person can then decrypt the symmetric key with their private key using
openssl rsautl -decrypt -inkey private.pem -in key.bin.enc -out key.bin
Now they can use the symmetric key to decrypt the file
openssl enc -d -aes-256-cbc -in myLargeFile.xml.enc \ -out myLargeFile.xml -pass file:./key.bin
And you're done. The other person has the decrypted file and it was safely sent.
Use Compressor (Image compression library). Visit zetbaitsu/Compressor for code and documentation.
add dependency in gradle (app level)
dependencies {
implementation 'id.zelory:compressor:3.0.0'
}
To Compress Image use one of these approaches:
Compress Image File:
val compressedImageFile = Compressor.compress(context, actualImageFile)
Compress Image File to Bitmap:
val compressedImageFile = Compressor.compress(context, actualImageFile)
val bitmap = BitmapFactory.decodeFile(compressedImageFile.path)
Here my common used script below. I use this for running scripts on two tables/views with SQL job and send results as two HTML tables via mail. Ofcourse you should create mail profile before run this.
DECLARE @mailfrom varchar(max)
DECLARE @subject varchar(100)
DECLARE @tableHTML NVARCHAR(MAX), @tableHTML1 NVARCHAR(MAX), @tableHTML2 NVARCHAR(MAX), @mailbody NVARCHAR(MAX)
DECLARE @Table1 NVARCHAR(MAX), @Table2 NVARCHAR(MAX)
DECLARE @jobName varchar(100)
SELECT @jobName = name from msdb..sysjobs where job_id = $(ESCAPE_NONE(JOBID))
-- If the result set is not empty then fill the Table1 HTML table
IF (SELECT COUNT(*) FROM [Database].[Schema].[Table1]) > 0
BEGIN
SET @Table1 = N''
SELECT @Table1 = @Table1 + '<tr style="font-size:13px;background-color:#FFFFFF">' +
'<td>' + ColumnText + '</td>' +
'<td>' + CAST(ColumnNumber as nvarchar(30)) + '</td>' + '</tr>'
FROM [Database].[Schema].[Table1]
ORDER BY ColumnText,ColumnNumber
SET @tableHTML1 =
N'<table border="1" align="Left" cellpadding="2" cellspacing="0" style="color:black;font-family:arial,helvetica,sans-serif;text-align:left;" >' +
N'<tr style ="font-size:13px;font-weight: normal;background: #FFFFFF">
<th align=left>ColumnTextHeader1</th>
<th align=left>ColumnNumberHeader2</th> </tr>' + @Table1 + '</table>'
END
ELSE
BEGIN
SET @tableHTML1 = N''
SET @Table1 = N''
END
-- If the result set is not empty then fill the Table2 HTML table
IF (SELECT COUNT(*) FROM [Database].[Schema].[Table2]) > 0
BEGIN
SET @Table2 = N''
SELECT @Table2 = @Table2 + '<tr style="font-size:13px;background-color:#FFFFFF">' +
'<td>' + ColumnText + '</td>' +
'<td>' + CAST(ColumnNumber as nvarchar(30)) + '</td>' + '</tr>'
FROM [Database].[Schema].[Table2]
ORDER BY ColumnText,ColumnNumber
SET @tableHTML2 =
N'<table border="1" align="Left" cellpadding="2" cellspacing="0" style="color:black;font-family:arial,helvetica,sans-serif;text-align:left;" >' +
N'<tr style ="font-size:13px;font-weight: normal;background: #FFFFFF">
<th align=left>ColumnTextHeader1</th>
<th align=left>ColumnNumberHeader2</th> </tr>' + @Table2 + '</table>'
END
ELSE
BEGIN
SET @tableHTML2 = N''
SET @Table2 = N''
END
SET @tableHTML = @tableHTML1 + @tableHTML2
-- If result sets from Table1 and Table2 are empty, then don't sent mail.
IF (SELECT @tableHTML) <> ''
BEGIN
SET @mailbody = N' Write mail text here<br><br>' + @tableHTML
SELECT @mailfrom = 'SQL Server <' + cast(SERVERPROPERTY('ComputerNamePhysicalNETBIOS') as varchar(50)) + '@domain.com>'
SELECT @subject = N'Mail Subject [Job: ' + @jobName + ']'
EXEC msdb.dbo.sp_send_dbmail
@profile_name= 'mailprofilename',
@recipients= '<[email protected]>',
@from_address = @mailfrom,
@reply_to = '<[email protected]>',
@subject = @subject,
@body = @mailbody,
@body_format = 'HTML'
-- ,@importance = 'HIGH'
END
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
Changing an image is easy, but how do you change it back to the original size after it has been changed? You may try this to change all images in a document back to the original size:
var i,L=document.images.length; for(i=0;i<L;++i){ document.images[i].style.height = 'auto'; //setting CSS value document.images[i].style.width = 'auto'; //setting CSS value // document.images[i].height = ''; (don't need this, would be setting img.attribute) // document.images[i].width = ''; (don't need this, would be setting img.attribute) }
The simplest way as you have explained is this link this is for 'Dow Jones Industrial Average'
Link 2 is for 'NASDAQ-100'
and for all related to NASDAQ link 3
I think this should be it, else you want same in JSON notations the same as Microsoft
Please refer this old post I think this will help,
Update:
To know the details of volume and other details, I have created a vbscript that is using IE object to fetch details from the link, and alerts the content in the particular id(Create a .vbs file and run it..
Set IE = CreateObject("InternetExplorer.Application")
while IE.readyState = 4: WScript.Sleep 10: wend
IE.Navigate "https://www.google.com/finance?q=INDEXNASDAQ%3ANDX&sq=NASDAQ&sp=2&ei=B3UoUsiIH5DIlgPEsQE"
IE.visible = true
while IE.readyState = 4: WScript.Sleep 10: wend
dim ht
ht= IE.document.getElementById("market-data-div").innerText
msgBox ht
IE.quit
this will alert the values from page like this
3,124.54 0.00 (0.00%)
Sep 4 - Close
INDEXNASDAQ real-time data - Disclaimer
Range -
52 week 2,494.38 - 3,149.24
Open -
Vol. 0.00
I am sure this will help..
You can use System.Uri
Uri url = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = String.Format("{0}{1}{2}{3}", url.Scheme,
Uri.SchemeDelimiter, url.Authority, url.AbsolutePath);
Or you can use substring
string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.Substring(0, url.IndexOf("?"));
EDIT: Modifying the first solution to reflect brillyfresh's suggestion in the comments.
If you want to suppress this warning in elegant way (because you are sure that accessibility is not needed for this particular ImageView), you can use special attribute:
android:importantForAccessibility="no"
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
I believe that throwing an exception is a better idea for your situation. An alternative will be the simulation method to return a tuple. The first item will be the status and the second one the result:
result = simulate(open("myfile"))
if not result[0]:
print "error parsing stream"
else:
ret= result[1]
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
for (int position = 0; position < adapter.getCount(); position++) {
if(adapter.getItemId(position) == value) {
spnr.setSelection(position);
return;
}
}
}
You can use the above like:
selectSpinnerItemByValue(spinnerObject, desiredValue);
& of course you can also select by index directly like
spinnerObject.setSelection(index);
Use asp:Panel
for that. It translates into a div.
verbose: Integer
. 0, 1, or 2. Verbosity mode.
Verbose=0 (silent)
Verbose=1 (progress bar)
Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc:
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc:
0.8071 - val_loss: 0.4617 - val_acc: 0.8168
Verbose=2 (one line per epoch)
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
Your disk also might just be full. (just had that)
Hope this would be useful to you. ^o^
df1 = pd.DataFrame({'date': ['0207', '0207'], 'col1': [1, 2]})
df2 = pd.DataFrame({'date': ['0207', '0207', '0208', '0208'], 'col1': [1, 2, 3, 4]})
print(f"df1(Before):\n{df1}\ndf2:\n{df2}")
"""
df1(Before):
date col1
0 0207 1
1 0207 2
df2:
date col1
0 0207 1
1 0207 2
2 0208 3
3 0208 4
"""
old_set = set(df1.index.values)
new_set = set(df2.index.values)
new_data_index = new_set - old_set
new_data_list = []
for idx in new_data_index:
new_data_list.append(df2.loc[idx])
if len(new_data_list) > 0:
df1 = df1.append(new_data_list)
print(f"df1(After):\n{df1}")
"""
df1(After):
date col1
0 0207 1
1 0207 2
2 0208 3
3 0208 4
"""
I've used Tail For Windows. Certainly not as elegant as using
tailbut then, you're using Windows. ;)
According to http://dev.mysql.com/ the SUBSTRING function uses start position then the length so surely the function for the second word would be:
SUBSTRING(sentence,LOCATE(' ',sentence),(LOCATE(' ',LOCATE(' ',sentence))-LOCATE(' ',sentence)))
It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.
You can use the following approach.
$data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
//...
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach
In your case you already have the data within the $query
variable.
Check out Fancybox. If you need the video to autoplay this example site was helpful!
Part 2 of the code For the link in Redfilter Answer:
References:
https://github.com/mb16/geocoderNet/blob/master/build/sql/doubleMetaphone.sql
BEGIN
SET @MP1 = @MP1 + 'N'
SET @MP2 = @MP2 + 'KN'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'KN'
SET @MP2 = @MP2 + 'KN'
END
END
SET @CurrentPosition = @CurrentPosition + 2
END
--'tagliaro'
ELSE IF (dbo.fnStringAt((@CurrentPosition + 1),@Word,'LI')=1) AND
(dbo.fnSlavoGermanic(@Word)=0)
BEGIN
SET @MP1 = @MP1 + 'KL'
SET @MP2 = @MP2 + 'L'
SET @CurrentPosition = @CurrentPosition + 2
END
-- -ges-,-gep-,-gel-, -gie- at beginning
-- This call to fnStringAt() is the 'worst case' in number of values passed. A UDF that used DEFAULT values instead of
-- a multi-valued argument would require ten DEFAULT arguments for EP, EB, EL, etc. (assuming the first was not defined with a DEFAULT).
ELSE IF ((@CurrentPosition = 1)
AND ((SUBSTRING(@Word,@CurrentPosition + 1,1) = 'Y')
OR (dbo.fnStringAt((@CurrentPosition +
1),@Word,'ES,EP,EB,EL,EY,IB,IL,IN,IE,EI,ER')=1)) )
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'J'
SET @CurrentPosition = @CurrentPosition + 2
END
-- -ger-, -gy-
ELSE IF (((dbo.fnStringAt((@CurrentPosition + 1), @Word, 'ER')=1) OR
(SUBSTRING(@Word,@CurrentPosition + 1,1) = 'Y'))
AND (dbo.fnStringAt(1, @Word, 'DANGER,RANGER,MANGER')=0)
AND (dbo.fnStringAt((@CurrentPosition - 1), @Word,
'E,I,RGY,OGY')=0) )
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'J'
SET @CurrentPosition = @CurrentPosition + 2
END
-- italian e.g, 'biaggi'
ELSE IF (dbo.fnStringAt((@CurrentPosition + 1),@Word,'E,I,Y')=1) OR
(dbo.fnStringAt((@CurrentPosition - 1),@Word,'AGGI,OGGI')=1)
BEGIN
--obvious germanic
IF ((dbo.fnStringAt(1,@Word,'VAN ,VON ,SCH')=1)
OR (dbo.fnStringAt((@CurrentPosition + 1),@Word,'ET')=1))
BEGIN
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
END
ELSE
BEGIN
--always soft if french ending
IF (dbo.fnStringAt((@CurrentPosition + 1),@Word,'IER ')=1)
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'J'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'K'
END
END
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'G')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
END
END
ELSE IF @CurrentChar = 'H'
BEGIN
--only keep if first & before vowel or btw. 2 vowels
IF (((@CurrentPosition = 1) OR
(dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition - 1,1))=1))
AND (dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition + 1,1))=1))
BEGIN
SET @MP1 = @MP1 + 'H'
SET @MP2 = @MP2 + 'H'
SET @CurrentPosition = @CurrentPosition + 2
END
--also takes care of 'HH'
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE IF @CurrentChar = 'J'
BEGIN
--obvious spanish, 'jose', 'san jacinto'
IF (dbo.fnStringAt(@CurrentPosition,@Word,'JOSE')=1) OR
(dbo.fnStringAt(1,@Word,'SAN ')=1)
BEGIN
IF (((@CurrentPosition = 1) AND (SUBSTRING(@Word,@CurrentPosition
+ 4,1) = ' ')) OR (dbo.fnStringAt(1,@Word,'SAN ')=1) )
BEGIN
SET @MP1 = @MP1 + 'H'
SET @MP2 = @MP2 + 'H'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'H'
END
SET @CurrentPosition = @CurrentPosition + 1
END
ELSE IF ((@CurrentPosition = 1) AND
(dbo.fnStringAt(@CurrentPosition,@Word,'JOSE')=0))
BEGIN
SET @MP1 = @MP1 + 'J'
--Yankelovich/Jankelowicz
SET @MP2 = @MP2 + 'A'
--it could happen!
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'J')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE
BEGIN
--spanish pron. of e.g. 'bajador'
IF( (dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition - 1,1))=1)
AND (dbo.fnSlavoGermanic(@Word)=0)
AND ((SUBSTRING(@Word,@CurrentPosition + 1,1) = 'A') OR
(SUBSTRING(@Word,@CurrentPosition + 1,1) = 'O')))
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'H'
END
ELSE
BEGIN
IF (@CurrentPosition = @WordLength)
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + ''
END
ELSE
BEGIN
IF ((dbo.fnStringAt((@CurrentPosition + 1), @Word,
'L,T,K,S,N,M,B,Z')=0)
AND (dbo.fnStringAt((@CurrentPosition - 1), @Word,
'S,K,L')=0))
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'J'
END
END
END
--it could happen!
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'J')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
END
ELSE IF @CurrentChar = 'K'
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'K')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
END
ELSE IF @CurrentChar = 'L'
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'L')
BEGIN
--spanish e.g. 'cabrillo', 'gallegos'
IF (((@CurrentPosition = (@WordLength - 3))
AND (dbo.fnStringAt((@CurrentPosition -
1),@Word,'ILLO,ILLA,ALLE')=1))
OR (((dbo.fnStringAt((@WordLength - 1),@Word,'AS,OS')=1)
OR (dbo.fnStringAt(@WordLength,@Word,'A,O')=1))
AND (dbo.fnStringAt((@CurrentPosition -
1),@Word,'ALLE')=1)) )
BEGIN
SET @MP1 = @MP1 + 'L'
SET @MP2 = @MP2 + ''
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
SET @MP1 = @MP1 + 'L'
SET @MP2 = @MP2 + 'L'
END
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
SET @MP1 = @MP1 + 'L'
SET @MP2 = @MP2 + 'L'
END
END
ELSE IF @CurrentChar = 'M'
BEGIN
--'dumb','thumb'
IF (((dbo.fnStringAt((@CurrentPosition - 1), @Word,'UMB')=1)
AND (((@CurrentPosition + 1) = @WordLength) OR
(dbo.fnStringAt((@CurrentPosition + 2),@Word,'ER')=1)))
OR (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'M') )
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'M'
SET @MP2 = @MP2 + 'M'
END
ELSE IF @CurrentChar = 'N'
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'N')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'N'
SET @MP2 = @MP2 + 'N'
END
ELSE IF @CurrentChar = 'Ñ'
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
SET @MP1 = @MP1 + 'N'
SET @MP2 = @MP2 + 'N'
END
ELSE IF @CurrentChar = 'P'
BEGIN
--What about Michelle Pfeiffer, star of Grease 2? Price-Pfister?, Pfizer?
--Don't just look for an 'F' next, what about 'topflight', helpful, campfire, leapfrog, stepfather
--Sorry, Mark Knopfler, I don't know how to help you
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'H')
OR ((@CurrentPosition = 1) AND
(SUBSTRING(@Word,@CurrentPosition + 1,1) = 'F') AND
(dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition+2,1))=1))
BEGIN
SET @MP1 = @MP1 + 'F'
SET @MP2 = @MP2 + 'F'
SET @CurrentPosition = @CurrentPosition + 2
END
--also account for "campbell", "raspberry"
ELSE
BEGIN
IF (dbo.fnStringAt((@CurrentPosition + 1),@Word, 'P,B')=1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'P'
SET @MP2 = @MP2 + 'P'
END
END
ELSE IF @CurrentChar = 'Q'
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'Q')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'K'
SET @MP2 = @MP2 + 'K'
END
ELSE IF @CurrentChar = 'R'
BEGIN
--QQ: Will SQL short circuit eval? Otherwise, I could try to read before string begins here...
--french e.g. 'rogier', but exclude 'hochmeier'
IF ((@CurrentPosition = @WordLength)
AND (dbo.fnSlavoGermanic(@Word)=0)
AND (dbo.fnStringAt((@CurrentPosition - 2), @Word, 'IE')=1)
AND (dbo.fnStringAt((@CurrentPosition - 4), @Word,
'ME,MA')=0))
BEGIN
SET @MP1 = @MP1 + ''
SET @MP2 = @MP2 + 'R'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'R'
SET @MP2 = @MP2 + 'R'
END
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'R')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE IF @CurrentChar = 'S'
BEGIN
--special cases 'island', 'isle', 'carlisle', 'carlysle'
IF (dbo.fnStringAt((@CurrentPosition - 1), @Word, 'ISL,YSL')=1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
--special case 'sugar-'
ELSE IF ((@CurrentPosition = 1) AND (dbo.fnStringAt(@CurrentPosition,
@Word, 'SUGAR')=1))
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'S'
SET @CurrentPosition = @CurrentPosition + 1
END
ELSE IF (dbo.fnStringAt(@CurrentPosition, @Word, 'SH')=1)
BEGIN
--germanic
IF (dbo.fnStringAt((@CurrentPosition + 1), @Word,
'HEIM,HOEK,HOLM,HOLZ')=1)
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'X'
END
SET @CurrentPosition = @CurrentPosition + 2
END
--italian & armenian
ELSE IF (dbo.fnStringAt(@CurrentPosition, @Word, 'SIO,SIA')=1) OR
(dbo.fnStringAt(@CurrentPosition, @Word, 'SIAN')=1)
BEGIN
IF (dbo.fnSlavoGermanic(@Word)=0)
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'X'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
END
SET @CurrentPosition = @CurrentPosition + 3
END
--german & anglicisations, e.g. 'smith' match 'schmidt', 'snider' match 'schneider'
--also, -sz- in slavic language altho in hungarian it is pronounced 's'
ELSE IF (((@CurrentPosition = 1)
AND (dbo.fnStringAt((@CurrentPosition + 1), @Word, 'M,N,L,W')=1))
OR (dbo.fnStringAt((@CurrentPosition + 1), @Word, 'Z')=1))
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'X'
IF (dbo.fnStringAt((@CurrentPosition + 1), @Word, 'Z')=1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE IF (dbo.fnStringAt(@CurrentPosition, @Word, 'SC')=1)
BEGIN
--Schlesinger's rule
IF (SUBSTRING(@Word,@CurrentPosition + 2,1) = 'H')
BEGIN
--dutch origin, e.g. 'school', 'schooner'
IF (dbo.fnStringAt((@CurrentPosition + 3), @Word,
'OO,ER,EN,UY,ED,EM')=1)
BEGIN
--'schermerhorn', 'schenker'
IF (dbo.fnStringAt((@CurrentPosition + 3), @Word, 'ER,EN')=1)
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'SK'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'SK'
SET @MP2 = @MP2 + 'SK'
END
SET @CurrentPosition = @CurrentPosition + 3
END
ELSE
BEGIN
IF ((@CurrentPosition = 1) AND
(dbo.fnIsVowel(SUBSTRING(@Word,3,1))=0) AND (SUBSTRING(@Word,3,1) <> 'W'))
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'S'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'X'
END
SET @CurrentPosition = @CurrentPosition + 3
END
END
ELSE IF (dbo.fnStringAt((@CurrentPosition + 2), @Word, 'I,E,Y')=1)
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
SET @CurrentPosition = @CurrentPosition + 3
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'SK'
SET @MP2 = @MP2 + 'SK'
SET @CurrentPosition = @CurrentPosition + 3
END
END
ELSE
BEGIN
--french e.g. 'resnais', 'artois'
IF ((@CurrentPosition = @WordLength) AND
(dbo.fnStringAt((@CurrentPosition - 2), @Word, 'AI,OI')=1))
BEGIN
SET @MP1 = @MP1 + ''
SET @MP2 = @MP2 + 'S'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
END
IF (dbo.fnStringAt((@CurrentPosition + 1), @Word, 'S,Z')=1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
END
ELSE IF @CurrentChar = 'T'
BEGIN
IF (dbo.fnStringAt(@CurrentPosition, @Word, 'TION,TIA,TCH')=1)
BEGIN
SET @MP1 = @MP1 + 'X'
SET @MP2 = @MP2 + 'X'
SET @CurrentPosition = @CurrentPosition + 3
END
ELSE IF (dbo.fnStringAt(@CurrentPosition, @Word, 'TH,TTH')=1)
BEGIN
--special case 'thomas', 'thames' or germanic
IF (dbo.fnStringAt((@CurrentPosition + 2), @Word, 'OM,AM')=1)
OR (dbo.fnStringAt(1, @Word, 'VAN ,VON ,SCH')=1)
BEGIN
SET @MP1 = @MP1 + 'T'
SET @MP2 = @MP2 + 'T'
END
ELSE
BEGIN
SET @MP1 = @MP1 + '0'
SET @MP2 = @MP2 + 'T'
END
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
IF (dbo.fnStringAt((@CurrentPosition + 1), @Word, 'T,D')=1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'T'
SET @MP2 = @MP2 + 'T'
END
END
ELSE IF @CurrentChar = 'V'
BEGIN
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'V')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
SET @MP1 = @MP1 + 'F'
SET @MP2 = @MP2 + 'F'
END
ELSE IF @CurrentChar = 'W'
BEGIN
--can also be in middle of word
IF (dbo.fnStringAt(@CurrentPosition, @Word, 'WR')=1)
BEGIN
SET @MP1 = @MP1 + 'R'
SET @MP2 = @MP2 + 'R'
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE IF ((@CurrentPosition = 1)
AND ((dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition + 1,1))=1)
OR (dbo.fnStringAt(@CurrentPosition, @Word, 'WH')=1)))
BEGIN
--Wasserman should match Vasserman
IF (dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition + 1,1))=1)
BEGIN
SET @MP1 = @MP1 + 'A'
SET @MP2 = @MP2 + 'F'
END
ELSE
BEGIN
--need Uomo to match Womo
SET @MP1 = @MP1 + 'A'
SET @MP2 = @MP2 + 'A'
END
SET @CurrentPosition = @CurrentPosition + 1
END
--Arnow should match Arnoff
ELSE IF (((@CurrentPosition = @WordLength) AND
(dbo.fnIsVowel(SUBSTRING(@Word,@CurrentPosition - 1,1))=1))
OR (dbo.fnStringAt((@CurrentPosition - 1), @Word,
'EWSKI,EWSKY,OWSKI,OWSKY')=1)
OR (dbo.fnStringAt(1, @Word, 'SCH')=1))
BEGIN
SET @MP1 = @MP1 + ''
SET @MP2 = @MP2 + 'F'
SET @CurrentPosition = @CurrentPosition + 1
END
--polish e.g. 'filipowicz'
ELSE IF (dbo.fnStringAt(@CurrentPosition, @Word, 'WICZ,WITZ')=1)
BEGIN
SET @MP1 = @MP1 + 'TS'
SET @MP2 = @MP2 + 'FX'
SET @CurrentPosition = @CurrentPosition + 4
END
-- skip it
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE IF @CurrentChar = 'X'
BEGIN
--french e.g. breaux
IF (NOT((@CurrentPosition = @WordLength)
AND ((dbo.fnStringAt((@CurrentPosition - 3), @Word, 'IAU,EAU')=1)
OR (dbo.fnStringAt((@CurrentPosition - 2), @Word,
'AU,OU')=1))) )
BEGIN
SET @MP1 = @MP1 + 'KS'
SET @MP2 = @MP2 + 'KS'
END
IF (dbo.fnStringAt((@CurrentPosition + 1), @Word, 'C,X')=1)
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
ELSE IF @CurrentChar = 'Z'
BEGIN
--chinese pinyin e.g. 'zhao'
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'H')
BEGIN
SET @MP1 = @MP1 + 'J'
SET @MP2 = @MP2 + 'J'
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
IF ((dbo.fnStringAt((@CurrentPosition + 1), @Word, 'ZO,ZI,ZA')=1)
OR ((dbo.fnSlavoGermanic(@Word)=1) AND ((@CurrentPosition >
1) AND SUBSTRING(@Word,@CurrentPosition - 1,1) <> 'T')))
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'TS'
END
ELSE
BEGIN
SET @MP1 = @MP1 + 'S'
SET @MP2 = @MP2 + 'S'
END
IF (SUBSTRING(@Word,@CurrentPosition + 1,1) = 'Z')
BEGIN
SET @CurrentPosition = @CurrentPosition + 2
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
END
ELSE
BEGIN
SET @CurrentPosition = @CurrentPosition + 1
END
END
--only give back 4 char metaphone
IF (LEN(@MP1) > 4)
BEGIN
SET @MP1 = LEFT(@MP1, 4)
END
IF (LEN(@MP2) > 4)
BEGIN
SET @MP2 = LEFT(@MP2, 4)
END
IF @MP2 = @MP1
BEGIN
SET @MP2 = ''
END
INSERT @DMP(Metaphone1,Metaphone2) VALUES( @MP1, @MP2 )
RETURN
END
GO;
------------------------------------------------------------------------
IF OBJECT_ID('fnDoubleMetaphoneScalar') IS NOT NULL BEGIN DROP FUNCTION
fnDoubleMetaphoneScalar END
GO;
CREATE FUNCTION fnDoubleMetaphoneScalar( @MetaphoneType int, @Word varchar(50) )
RETURNS char(4)
AS
BEGIN
RETURN (SELECT CASE @MetaphoneType WHEN 1 THEN Metaphone1
WHEN 2 THEN Metaphone2 END FROM fnDoubleMetaphoneTable( @Word ))
END
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
why dont you keep it simple and clean
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$acceptLang = ['fr', 'it', 'en'];
$lang = in_array($lang, $acceptLang) ? $lang : 'en';
require_once "index_{$lang}.php";
?>
First, you should list your plugins:
cordova plugin list
With this result, you can simply do:
cordova plugin remove <PLUGIN_NAME>
For example:
cordova plugin remove org.apache.cordova.media
Hope it helps.
You can use django's filter
with datetime.date
objects:
import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
sampledate__lte=datetime.date(2011, 1, 31))
You can use pathlib.
For Python 3.5 and above:
from pathlib import Path
contents = Path(file_path).read_text()
For older versions of Python use pathlib2:
$ pip install pathlib2
Then:
from pathlib2 import Path
contents = Path(file_path).read_text()
This is the actual read_text
implementation:
def read_text(self, encoding=None, errors=None):
"""
Open the file in text mode, read it, and close the file.
"""
with self.open(mode='r', encoding=encoding, errors=errors) as f:
return f.read()
You can use android:stopWithTask="false"
in manifest as bellow, This means even if user kills app by removing it from tasklist, your service won't stop.
<service android:name=".service.StickyService"
android:stopWithTask="false"/>
You mean staticly define a value, like this:
SELECT field1,
field2,
'example' AS newfield
FROM TABLE1
This will add a column called "newfield" to the output, and its value will always be "example".
I've been using this little cheat for a while now. You might enjoy it. nest the table you want to center in another table:
<table height=100% width=100%>
<td align=center valign=center>
(add your table here)
</td>
</table>
the align and valign put the table exactly in the middle of the screen, no matter what else is going on.
This one worked for me, try this
[RegularExpression("^[a-zA-Z &\-@.]*$", ErrorMessage = "--Your Message--")]
As a corollary to why the jQuery FormatCurrency plugin is a good answer, I'd like to rebut your comment:
1. code.google.com/p/jquery-formatcurrency - Does not filter out all letter's. You can type a single letter and it will not remove it.
Yes, formatCurrency() by itself does not filter out letters:
// only formats currency
$(selector).formatCurrency();
But toNumber(), included in the formatCurrency plugin, does.
You thus want to do:
// removes invalid characters, then formats currency
$(selector).toNumber().formatCurrency();
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
To answer on the first part you should provide examples where people use different approach for the exact same class-object. Otherwise it is difficult (or even strange) to answer.
As for the second question better read first this Proper use of the IDisposable interface which claims that
It's your choice! But choose Dispose.
In other words: The GC only knows about finalizer (if any. Also known as destructor to Microsoft). A good code will attempt to cleanup from both (finalizer and Dispose).
You need to use a delegated event handler, as the #add
elements dynamically appended won't have the click event bound to them. Try this:
$("#buildyourform").on('click', "#add", function() {
// your code...
});
Also, you can make your HTML strings easier to read by mixing line quotes:
var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');
Or even supplying the attributes as an object:
var fieldWrapper = $('<div></div>', {
'class': 'fieldwrapper',
'name': 'field' + intId,
'id': 'field' + intId
});
Use (V3 version):
(Get-Content c:\temp\test.txt).replace('[MYID]', 'MyValue') | Set-Content c:\temp\test.txt
Or for V2:
(Get-Content c:\temp\test.txt) -replace '\[MYID\]', 'MyValue' | Set-Content c:\temp\test.txt
Example using std::string
find method:
#include <iostream>
#include <string>
int main (){
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
size_t found = str.find(str2);
if(found!=std::string::npos){
std::cout << "first 'needle' found at: " << found << '\n';
}
return 0;
}
Result:
first 'needle' found at: 14.
In addition to the correct answer by mdma, you can also use the mail command as follows:
mail [email protected] -s"Subject Here" -a"Content-Type: text/html; charset=\"us-ascii\""
you will get what you're looking for. Don't forget to put <HTML>
and </HTML>
in the email. Here's a quick script I use to email a daily report in HTML:
#!/bin/sh
(cat /path/to/tomorrow.txt mysql -h mysqlserver -u user -pPassword Database -H -e "select statement;" echo "</HTML>") | mail [email protected] -s"Tomorrow's orders as of now" -a"Content-Type: text/html; charset=\"us-ascii\""
You have two options:
Extend your .paging
class definition:
.paging:hover {
border:1px solid #999;
color:#000;
}
Use the DOM hierarchy to apply the CSS style:
div.paginate input:hover {
border:1px solid #999;
color:#000;
}
For that you need to add change listener (a DocumentListener
which reacts for change in the text) for your JTextField
, and within actionPerformed()
, you need to update the loginButton
to enabled/disabled depending on the whether the JTextfield
is empty or not.
Below is what I found from this thread.
yourJTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
changed();
}
public void removeUpdate(DocumentEvent e) {
changed();
}
public void insertUpdate(DocumentEvent e) {
changed();
}
public void changed() {
if (yourJTextField.getText().equals("")){
loginButton.setEnabled(false);
}
else {
loginButton.setEnabled(true);
}
}
});
In .NET 4.0, the runtime handles certain exceptions raised as Windows Structured Error Handling (SEH) errors as indicators of Corrupted State. These Corrupted State Exceptions (CSE) are not allowed to be caught by your standard managed code. I won't get into the why's or how's here. Read this article about CSE's in the .NET 4.0 Framework:
http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035
But there is hope. There are a few ways to get around this:
Recompile as a .NET 3.5 assembly and run it in .NET 4.0.
Add a line to your application's config file under the configuration/runtime element:
<legacyCorruptedStateExceptionsPolicy enabled="true|false"/>
Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions
attribute. See http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035 for details.
EDIT
Previously, I referenced a forum post for additional details. But since Microsoft Connect has been retired, here are the additional details in case you're interested:
From Gaurav Khanna, a developer from the Microsoft CLR Team
This behaviour is by design due to a feature of CLR 4.0 called Corrupted State Exceptions. Simply put, managed code shouldnt make an attempt to catch exceptions that indicate corrupted process state and AV is one of them.
He then goes on to reference the documentation on the HandleProcessCorruptedStateExceptionsAttribute and the above article. Suffice to say, it's definitely worth a read if you're considering catching these types of exceptions.
All the information in this thread is now out of date with the recent release of vswhere. Download that and use it.
In Cygwin:
$cmp -bl <file1> <file2>
diffs binary offsets and values are in decimal and octal respectively.. Vladi.
As mentioned in other answers the simplest solution to the particular problem you have posed is to use something like fsolve
:
from scipy.optimize import fsolve
from math import exp
def equations(vars):
x, y = vars
eq1 = x+y**2-4
eq2 = exp(x) + x*y - 3
return [eq1, eq2]
x, y = fsolve(equations, (1, 1))
print(x, y)
Output:
0.6203445234801195 1.8383839306750887
You say how to "solve" but there are different kinds of solution. Since you mention SymPy I should point out the biggest difference between what this could mean which is between analytic and numeric solutions. The particular example you have given is one that does not have an (easy) analytic solution but other systems of nonlinear equations do. When there are readily available analytic solutions SymPY can often find them for you:
from sympy import *
x, y = symbols('x, y')
eq1 = Eq(x+y**2, 4)
eq2 = Eq(x**2 + y, 4)
sol = solve([eq1, eq2], [x, y])
Output:
?? ? 5 v17? ?3 v17? v17 1? ? ? 5 v17? ?3 v17? 1 v17? ? ? 3 v13? ?v13 5? 1 v13? ? ?5 v13? ? v13 3? 1 v13??
??-?- - - ---?·?- - ---?, - --- - -?, ?-?- - + ---?·?- + ---?, - - + ---?, ?-?- - + ---?·?--- + -?, - + ---?, ?-?- - ---?·?- --- - -?, - - ---??
?? ? 2 2 ? ?2 2 ? 2 2? ? ? 2 2 ? ?2 2 ? 2 2 ? ? ? 2 2 ? ? 2 2? 2 2 ? ? ?2 2 ? ? 2 2? 2 2 ??
Note that in this example SymPy finds all solutions and does not need to be given an initial estimate.
You can evaluate these solutions numerically with evalf
:
soln = [tuple(v.evalf() for v in s) for s in sol]
[(-2.56155281280883, -2.56155281280883), (1.56155281280883, 1.56155281280883), (-1.30277563773199, 2.30277563773199), (2.30277563773199, -1.30277563773199)]
However most systems of nonlinear equations will not have a suitable analytic solution so using SymPy as above is great when it works but not generally applicable. That is why we end up looking for numeric solutions even though with numeric solutions: 1) We have no guarantee that we have found all solutions or the "right" solution when there are many. 2) We have to provide an initial guess which isn't always easy.
Having accepted that we want numeric solutions something like fsolve
will normally do all you need. For this kind of problem SymPy will probably be much slower but it can offer something else which is finding the (numeric) solutions more precisely:
from sympy import *
x, y = symbols('x, y')
nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1])
?0.620344523485226?
? ?
?1.83838393066159 ?
With greater precision:
nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1], prec=50)
?0.62034452348522585617392716579154399314071550594401?
? ?
? 1.838383930661594459049793153371142549403114879699 ?
Check this useful method:
URLUtil.guessUrl(urlString)
It makes google.com -> http://google.com
Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);
it also provides some safety:
try{
std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
...
}
Unfortunately for all the answers given by other folks, you can't DELETE
and SELECT
from a given table in the same query.
DELETE FROM mytable WHERE id NOT IN (SELECT MAX(id) FROM mytable);
ERROR 1093 (HY000): You can't specify target table 'mytable' for update
in FROM clause
Nor can MySQL support LIMIT
in a subquery. These are limitations of MySQL.
DELETE FROM mytable WHERE id NOT IN
(SELECT id FROM mytable ORDER BY id DESC LIMIT 1);
ERROR 1235 (42000): This version of MySQL doesn't yet support
'LIMIT & IN/ALL/ANY/SOME subquery'
The best answer I can come up with is to do this in two stages:
SELECT id FROM mytable ORDER BY id DESC LIMIT n;
Collect the id's and make them into a comma-separated string:
DELETE FROM mytable WHERE id NOT IN ( ...comma-separated string... );
(Normally interpolating a comma-separate list into an SQL statement introduces some risk of SQL injection, but in this case the values are not coming from an untrusted source, they are known to be integer values from the database itself.)
note: Though this doesn't get the job done in a single query, sometimes a more simple, get-it-done solution is the most effective.
An unwind segue (sometimes called exit segue) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. "go back" multiple steps in your navigation hierarchy with a single unwind action.
When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.
Objective-C:
- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
}
Swift:
@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
}
The name of this action method is used when you create the unwind segue in the storyboard. Furthermore, this method is called just before the unwind segue is performed. You can get the source view controller from the passed UIStoryboardSegue
parameter to interact with the view controller that initiated the segue (e.g. to get the property values of a modal view controller). In this respect, the method has a similar function as the prepareForSegue:
method of UIViewController
.
iOS 8 update: Unwind segues also work with iOS 8's adaptive segues, such as Show and Show Detail.
Let us have a storyboard with a navigation controller and three child view controllers:
From Green View Controller you can unwind (navigate back) to Red View Controller. From Blue you can unwind to Green or to Red via Green. To enable unwinding you must add the special action methods to Red and Green, e.g. here is the action method in Red:
Objective-C:
@implementation RedViewController
- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
}
@end
Swift:
@IBAction func unwindToRed(segue: UIStoryboardSegue) {
}
After the action method has been added, you can define the unwind segue in the storyboard by control-dragging to the Exit icon. Here we want to unwind to Red from Green when the button is pressed:
You must select the action which is defined in the view controller you want to unwind to:
You can also unwind to Red from Blue (which is "two steps away" in the navigation stack). The key is selecting the correct unwind action.
Before the the unwind segue is performed, the action method is called. In the example I defined an unwind segue to Red from both Green and Blue. We can access the source of the unwind in the action method via the UIStoryboardSegue parameter:
Objective-C:
- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
UIViewController* sourceViewController = unwindSegue.sourceViewController;
if ([sourceViewController isKindOfClass:[BlueViewController class]])
{
NSLog(@"Coming from BLUE!");
}
else if ([sourceViewController isKindOfClass:[GreenViewController class]])
{
NSLog(@"Coming from GREEN!");
}
}
Swift:
@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) {
if let blueViewController = unwindSegue.sourceViewController as? BlueViewController {
println("Coming from BLUE")
}
else if let redViewController = unwindSegue.sourceViewController as? RedViewController {
println("Coming from RED")
}
}
Unwinding also works through a combination of push/modal segues. E.g. if I added another Yellow view controller with a modal segue, we could unwind from Yellow all the way back to Red in a single step:
When you define an unwind segue by control-dragging something to the Exit symbol of a view controller, a new segue appears in the Document Outline:
Selecting the segue and going to the Attributes Inspector reveals the "Identifier" property. Use this to give a unique identifier to your segue:
After this, the unwind segue can be performed from code just like any other segue:
Objective-C:
[self performSegueWithIdentifier:@"UnwindToRedSegueID" sender:self];
Swift:
performSegueWithIdentifier("UnwindToRedSegueID", sender: self)
_WIN32 identifier is not defined.
use #include <SDKDDKVer.h>
MSVS generated projects wrap this include by generating a local "targetver.h"
which is included by "stdafx.h"
that is comiled into a precompiled-header through "stdafx.cpp"
.
EDIT : do you have a /D "WIN32" on your commandline ?
Use otool:
otool -TV your.dylib
OR
nm -g your.dylib
It depends on how the code in the first file is structured.
If it's just a bunch of functions, like:
# first.py
def foo(): print("foo")
def bar(): print("bar")
Then you could import it and use the functions as follows:
# second.py
import first
first.foo() # prints "foo"
first.bar() # prints "bar"
or
# second.py
from first import foo, bar
foo() # prints "foo"
bar() # prints "bar"
or, to import all the names defined in first.py:
# second.py
from first import *
foo() # prints "foo"
bar() # prints "bar"
Note: This assumes the two files are in the same directory.
It gets a bit more complicated when you want to import names (functions, classes, etc) from modules in other directories or packages.
Try this:
// I suppose you have already set your JFrame
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);
Found on this tutorial on how to display animated gif in java
Or live on youtube : https://youtu.be/_NEnhm9mgdE
mvn install
(or mvn package
) will always work.
You can use mvn compile
to download compile time dependencies or mvn test
for compile time and test dependencies but I prefer something that always works.
Ack! Constant strings:
const char *strings[] = {"one","two","three"};
If I remember correctly.
Oh, and you want to use strcpy for assignment, not the = operator. strcpy_s is safer, but it's neither in C89 nor in C99 standards.
char arr[MAX_NUMBER_STRINGS][MAX_STRING_SIZE];
strcpy(arr[0], "blah");
Update: Thomas says strlcpy
is the way to go.
UPDATE: Using Java 8 Syntax
List<DataPoint> myList = new ArrayList<>();
//Fill up myList with your Data Points
List<DataPoint> dataPointsCalledJohn =
myList
.stream()
.filter(p-> p.getName().equals(("john")))
.collect(Collectors.toList());
If you don't mind using an external libaray - you can use Predicates from the Google Guava library as follows:
class DataPoint {
String name;
String getName() { return name; }
}
Predicate<DataPoint> nameEqualsTo(final String name) {
return new Predicate<DataPoint>() {
public boolean apply(DataPoint dataPoint) {
return dataPoint.getName().equals(name);
}
};
}
public void main(String[] args) throws Exception {
List<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points
Collection<DataPoint> dataPointsCalledJohn =
Collections2.filter(myList, nameEqualsTo("john"));
}
Swift 2.0 as of Xcode 7 GM Seed
var text = "Hello, world!"
let firstChar = text[text.startIndex.advancedBy(0)] // "H"
For the nth character, replace 0 with n-1.
Edit: Swift 3.0
text[text.index(text.startIndex, offsetBy: 0)]
n.b. there are simpler ways of grabbing certain characters in the string
e.g. let firstChar = text.characters.first
import operator
tuple(map(operator.add, a, b))
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest
.
There's no good substitute to testing on an actual device.
Real devices have higher display densities, meaning that pixels are smaller. If you don't test on a real device, you may not realise that your design includes text that is too small to read or buttons that are too small to tap.
You use real devices with your fingers, not a mouse. This means that the accuracy of your taps is much lower and what you are tapping is obscured by your finger. If you don't test on a real device, you may not realise you've introduced usability problems into your design.
Here is Kotlin version.
Thanks you :)
fun unSafeOkHttpClient() :OkHttpClient.Builder {
val okHttpClient = OkHttpClient.Builder()
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
if (trustAllCerts.isNotEmpty() && trustAllCerts.first() is X509TrustManager) {
okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
okHttpClient.hostnameVerifier { _, _ -> true }
}
return okHttpClient
} catch (e: Exception) {
return okHttpClient
}
}
<div id='parent' style='width: 100%;text-align:center;'>
<div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>
Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION
@trackingItems1 TABLE (
item nvarchar(25) NULL, -- 25 OR equal size of your item column
warehouse nvarchar(25) NULL, -- same as above
price int NULL
)
Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated
Ref denotes whether the function can get its hands on the object itself, or only on its value.
Passing by reference is not bound to a language; it's a parameter binding strategy next to pass-by-value, pass by name, pass by need etc...
A sidenote: the class name TestRef
is a hideously bad choice in this context ;).
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
# If you want to open Chrome
driver = webdriver.Chrome()
# If you want to open Firefox
driver = webdriver.Firefox()
username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")
username.send_keys("YourUsername")
password.send_keys("YourPassword")
driver.find_element_by_id("submit_btn").click()
For installing standard toolboxes: Just insert your CD/DVD of MATLAB and start installing, when you see typical/Custom, choose custom and check the toolboxes you want to install and uncheck the others which are installed already.
How about the H2 console application?
It can be best done by javascript reduce function.
var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
arrays = arrays.reduce(function(a, b){
return a.concat(b);
}, []);
Or, with ES2015:
arrays = arrays.reduce((a, b) => a.concat(b), []);
I had a java.lang.reflect.InvocationTargetException
error from a statement calling a logger object in an external class
inside a try
/ catch
block in my class
.
Stepping through the code in the Eclipse debugger & hovering the mouse over the logger statement I saw the logger object
was null
(some external constants needed to be instantiated at the very top of my class
).
Of course.
$('#item')[0].className = '';
// or
document.getElementById('item').className = '';
When you perform an DOM query through jQuery like $('class-name')
it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.
When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this)
. Like so:
$('.class-name').on('click', (evt) => {
$(this).hide(); // does not run a DOM query
$('.class-name').hide() // runs a DOM query
});
$(this)
will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.
Some more information:
Web Performance with jQuery selectors
Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:
In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:
When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.
It's simple .First you should clear your collection and after clear list like this code :
yourCollection.clear();
setListAdapter(null);
Using grid?
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: black;
}
body {
display: grid;
grid-template-rows: auto;
justify-items: center;
align-items: center;
}
canvas {
height: 80vh;
width: 80vw;
display: block;
}
_x000D_
<html>
<body>
<canvas></canvas>
</body>
</html>
_x000D_
Just a poke, but here's another way to write FizzBuzz :) 100 rows is enough to show the WITH statement, I reckon.
;WITH t100 AS (
SELECT n=number
FROM master..spt_values
WHERE type='P' and number between 1 and 100
)
SELECT
ISNULL(NULLIF(
CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
FROM t100
But the real power behind WITH (known as Common Table Expression http://msdn.microsoft.com/en-us/library/ms190766.aspx "CTE") in SQL Server 2005 and above is the Recursion, as below where the table is built up through iterations adding to the virtual-table each time.
;WITH t100 AS (
SELECT n=1
union all
SELECT n+1
FROM t100
WHERE n < 100
)
SELECT
ISNULL(NULLIF(
CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
FROM t100
To run a similar query in all database, you can use the undocumented sp_msforeachdb. It has been mentioned in another answer, but it is sp_msforeachdb, not sp_foreachdb.
Be careful when using it though, as some things are not what you expect. Consider this example
exec sp_msforeachdb 'select count(*) from sys.objects'
Instead of the counts of objects within each DB, you will get the SAME count reported, begin that of the current DB. To get around this, always "use" the database first. Note the square brackets to qualify multi-word database names.
exec sp_msforeachdb 'use [?]; select count(*) from sys.objects'
For your specific query about populating a tally table, you can use something like the below. Not sure about the DATE column, so this tally table has only the DBNAME and IMG_COUNT columns, but hope it helps you.
create table #tbl (dbname sysname, img_count int);
exec sp_msforeachdb '
use [?];
if object_id(''tbldoc'') is not null
insert #tbl
select ''?'', count(*) from tbldoc'
select * from #tbl
In the context of constraint animation, I would like to mention a specific situation where I animated a constraint immediately within a keyboard_opened notification.
Constraint defined a top space from a textfield to top of the container. Upon keyboard opening, I just divide the constant by 2.
I was unable to achieve a conistent smooth constraint animation directly within the keyboard notification. About half the times view would just jump to its new position - without animating.
It occured to me there might be some additional layouting happening as result of keyboard opening. Adding a simple dispatch_after block with a 10ms delay made the animation run every time - no jumping.
is there a way to pass param from
navigate.goback()
and parent can listen to the params and update its state?
You can pass a callback function as parameter (as mentioned in other answers).
Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect
):
ViewA.js
import React from "react";
import { Button, Text, View } from "react-native";
class ViewA extends React.Component {
state = { selected: false };
onSelect = data => {
this.setState(data);
};
onPress = () => {
this.props.navigate("ViewB", { onSelect: this.onSelect });
};
render() {
return (
<View>
<Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
<Button title="Next" onPress={this.onPress} />
</View>
);
}
}
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation } = this.props;
navigation.goBack();
navigation.state.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617
For React Navigation v5
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation, route } = this.props;
navigation.goBack();
route.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Doing an if exists ... else ... involves doing two requests minimum (one to check, one to take action). The following approach requires only one where the record exists, two if an insert is required:
DECLARE @RowExists bit
SET @RowExists = 0
UPDATE MyTable SET DataField1 = 'xxx', @RowExists = 1 WHERE Key = 123
IF @RowExists = 0
INSERT INTO MyTable (Key, DataField1) VALUES (123, 'xxx')
Inside your project folder their is a bin folder. Inside your bin folder, there are 2 folders, a Release and a Debug. For your polished .exe, you want to go into your Release folder.
I'm not quite sure if thats what youre asking
Isn't it this simple?
var result = _(data)
.groupBy(x => x.color)
.map((value, key) => ({color: key, users: value}))
.value();
srand(time(NULL));
int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);
let me make it more clear
function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file
If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this
devServer: {
contentBase: path.join(__dirname, './dist'),
compress: true,
host: 'localhost',
// host: '0.0.0.0',
port: 8080,
disableHostCheck: true //for ngrok
},
You could use :
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.
It was already mentioned, but thought I could add to using touch
If you touch
all the source files to be compiled, the touch
command changes the timestamps of a file to the system time the touch
command was executed.
The source file timstamp is what make
uses to "know" a file has changed, and needs to be re-compiled
For example: If the project was a c++ project, then do touch *.cpp
, then run make
again, and make should recompile the entire project.
you need /q at the end
MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
Try:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}
It's awesome I used to work with mysql bench but for big databases (something like more than 300 tables) won't work very well but visual paradigm reverse database works so much better
Go to data directory and try this:
mv database1 database2
It works for me on a 900 MB database size.
First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library
If the above mentioned are done or if you already have them, then just add the below code in your nginx server block
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
To remove www from every request you can use
if ($host = 'www.your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.com/$1 permanent;
}
so your server block will look like
server {
listen 80;
server_name test.com;
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
client_max_body_size 10M;
client_body_buffer_size 128k;
root /home/test/test/public;
passenger_enabled on;
rails_env production;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
It could be something like that:
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var arrays = [], size = 3;
while (a.length > 0)
arrays.push(a.splice(0, size));
console.log(arrays);
_x000D_
See splice Array's method.
A python string is a list of characters. You can iterate over it right now!
justdigits = ""
for char in string:
if char.isdigit():
justdigits += str(char)
it is not displayed in your application... it is under your emulator's logcat