If you can live with pixel-sized margins, just add font-size: 1px;
to the .frame
. But remember, that now on the .frame
1em = 1px, which means, you need to set the margin in pixels too.
http://jsfiddle.net/feeela/4RPFa/96/
Now it's not centered any more in Opera…
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
Live Example:
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
An additional simple solution
HTML:
<div id="d1">
<div id="d2">
Text
</div>
</div>
CSS:
#d1{
position:absolute;
top:100px;left:100px;
}
#d2{
border:1px solid black;
height:50px; width:50px;
display:table-cell;
vertical-align:middle;
text-align:center;
}
For me, VerticalAlignment="Center"
fixes this problem.
This could be because the TextBlock
is wrapped in a grid, but then so is practically everything in wpf.
#3 ways to make center child div in a parent div
Transform/Translate Method
/* 1st way */_x000D_
.parent1 {_x000D_
background: darkcyan;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
position: relative;_x000D_
}_x000D_
.child1 {_x000D_
background: white;_x000D_
height: 30px;_x000D_
width: 30px;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: -15px;_x000D_
}_x000D_
_x000D_
/* 2nd way */_x000D_
.parent2 {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
background: darkcyan;_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
}_x000D_
.child2 {_x000D_
background: white;_x000D_
height: 30px;_x000D_
width: 30px;_x000D_
}_x000D_
_x000D_
/* 3rd way */_x000D_
.parent3 {_x000D_
position: relative;_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
background: darkcyan;_x000D_
}_x000D_
.child3 {_x000D_
background: white;_x000D_
height: 30px;_x000D_
width: 30px;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}
_x000D_
<div class="parent1">_x000D_
<div class="child1"></div>_x000D_
</div>_x000D_
<hr />_x000D_
_x000D_
<div class="parent2">_x000D_
<div class="child2"></div>_x000D_
</div>_x000D_
<hr />_x000D_
_x000D_
<div class="parent3">_x000D_
<div class="child3"></div>_x000D_
</div>
_x000D_
You can use line-height: 50px;
, you won't need vertical-align: middle;
there.
The above will fail if you've multiple lines, so in that case you can wrap your text using span
and than use display: table-cell;
and display: table;
along with vertical-align: middle;
, also don't forget to use width: 100%;
for #abc
#abc{
font:Verdana, Geneva, sans-serif;
font-size:18px;
text-align:left;
background-color:#0F0;
height:50px;
display: table;
width: 100%;
}
#abc span {
vertical-align:middle;
display: table-cell;
}
Another solution I can think of here is to use transform
property with translateY()
where Y
obviously stands for Y Axis. It's pretty straight forward... All you need to do is set the elements position to absolute
and later position 50%
from the top
and translate from it's axis with negative -50%
div {
height: 100px;
width: 100px;
background-color: tomato;
position: relative;
}
p {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
Note that this won't be supported on older browsers, for example IE8, but you can make IE9 and other older browser versions of Chrome and Firefox by using -ms, -moz
and -webkit
prefixes respectively.
For more information on transform
, you can refer here.
You could use tabs instead of spaces between columns, and/or set maximum size for a column in format strings ...
I always using tutorial from this article to center things. It's great
div.container3 {
height: 10em;
position: relative } /* 1 */
div.container3 p {
margin: 0;
position: absolute; /* 2 */
top: 50%; /* 3 */
transform: translate(0, -50%) } /* 4 */
The essential rules are:
Tested in IE, Firefox, and Chrome.
.parent-container {_x000D_
position: relative;_x000D_
height:100%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.child-container {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}
_x000D_
<div class="parent-container">_x000D_
<div class="child-container">_x000D_
<h2>Header Text</h2>_x000D_
<span>Some Text</span>_x000D_
</div>_x000D_
</div>
_x000D_
Found on https://css-tricks.com/centering-css-complete-guide/
All these answers and none worked for me... I'm no flexbox expert, but this was reasonably easy to figure out, it is simple and easy to understand and use. To separate something from the rest of the content, insert an empty div and let it grow to fill the space.
https://jsfiddle.net/8sfeLmgd/1/
.myContainer {
display: flex;
height: 250px;
flex-flow: column;
}
.filler {
flex: 1 1;
}
<div class="myContainer">
<div>Top</div>
<div class="filler"></div>
<div>Bottom</div>
</div>
This reacts as expected when the bottom content is not fixed sized also when the container is not fixed sized.
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
Tested and works in Safari 5 and IE6+.
This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks. When we get browser support for css 3 you'll get your vertical centering without sinning.
For a better explanation of the technique you can look the article I adapted it from, but basically it involves adding an extra element and applying different styles in IE and browsers that support position:table\table-cell
on non-table elements.
<div class="valign-outer">
<div class="valign-middle">
<div class="valign-inner">
Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.
</div>
</div>
</div>
<style>
/* Non-structural styling */
.valign-outer { height: 400px; border: 1px solid red; }
.valign-inner { border: 1px solid blue; }
</style>
<!--[if lte IE 7]>
<style>
/* For IE7 and earlier */
.valign-outer { position: relative; overflow: hidden; }
.valign-middle { position: absolute; top: 50%; }
.valign-inner { position: relative; top: -50% }
</style>
<![endif]-->
<!--[if gt IE 7]> -->
<style>
/* For other browsers */
.valign-outer { position: static; display: table; overflow: hidden; }
.valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }
</style>
There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.
Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases. If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.
Update: We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See this other question for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.
I figured this one out. I know this will help someone someday.
How to Vertically & Horizontally Center a Div Over a Relatively Positioned Image
The key was a 3rd wrapper. I would vote up any answer that uses less wrappers.
HTML
<div class="wrapper">
<img src="my-slide.jpg">
<div class="outer-wrapper">
<div class="table-wrapper">
<div class="table-cell-wrapper">
<h1>My Title</h1>
<p>Subtitle</p>
</div>
</div>
</div>
</div>
CSS
html, body {
margin: 0; padding: 0;
width: 100%; height: 100%;
}
ul {
width: 100%;
height: 100%;
list-style-position: outside;
margin: 0; padding: 0;
}
li {
width: 100%;
display: table;
}
img {
width: 100%;
height: 100%;
}
.outer-wrapper {
width: 100%;
height: 100%;
position: absolute;
top: 0;
margin: 0; padding: 0;
}
.table-wrapper {
width: 100%;
height: 100%;
display: table;
vertical-align: middle;
text-align: center;
}
.table-cell-wrapper {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
}
You can see the working jsFiddle here.
Sorry to dig an old grave here, but why not just do this?
<div class="form-group">
</div>
It will add a space the height of a normal form element.
It seems about 1 line on a form is roughly 50px (47px on my element I just inspected). This is a horizontal form, with label on left 2col and input on right 10col. So your pixels may vary.
Since mine is basically 50px, I would create a spacer of 50px tall with no margins or padding;
.spacer { margin:0; padding:0; height:50px; }
<div class="spacer"></div>
Use column-width property of css like below
<ul style="column-width:135px">
Place it inside another div, use CSS to move the button to the middle:
<div style="width:100%;height:100%;position:absolute;vertical-align:middle;text-align:center;">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname</button>
</div>?
Here is an example: JsFiddle
Since each time I need to center div vertically I google for it over and over again and this answer always comes first I'll leave this for future me (since none of the provided solutions fit my need well):
So if one is already using bootstrap this can be done as below:
<div style="min-height: 100vh;" class="align-items-center row">
<div class="col" style="margin: auto; max-width: 750px;"> //optional style to center horizontally as well
//content goes here
</div>
</div>
If:
X is image width,
Y is image height,
then:
img {
position: absolute;
top: 50%;
left: 50%;
margin-left: -(X/2)px;
margin-top: -(Y/2)px;
}
But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.
Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.
Try this solution:
.EXTENDER {_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
left: 0px;_x000D_
bottom: 0px;_x000D_
right: 0px;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow-y: hidden;_x000D_
overflow-x: hidden;_x000D_
}_x000D_
_x000D_
.PADDER-CENTER {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
display: -webkit-box;_x000D_
display: -moz-box;_x000D_
display: -ms-flexbox;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-box-pack: center;_x000D_
-moz-box-pack: center;_x000D_
-ms-flex-pack: center;_x000D_
-webkit-justify-content: center;_x000D_
justify-content: center;_x000D_
-webkit-box-align: center;_x000D_
-moz-box-align: center;_x000D_
-ms-flex-align: center;_x000D_
-webkit-align-items: center;_x000D_
align-items: center;_x000D_
}
_x000D_
<div class="EXTENDER">_x000D_
<div class="PADDER-CENTER">_x000D_
<div contentEditable="true">Edit this text...</div>_x000D_
</div>_x000D_
</div>
_x000D_
Built using CSS+.
Add CSS:_x000D_
_x000D_
_x000D_
li {_x000D_
display: table-row;_x000D_
_x000D_
}_x000D_
li div {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
_x000D_
}_x000D_
.check{_x000D_
width:20px;_x000D_
_x000D_
}_x000D_
ul{_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
<ul>_x000D_
<li>_x000D_
_x000D_
<div><label for="myid1">Subject1</label></div>_x000D_
<div class="check"><input type="checkbox" value="1"name="subject" class="subject-list" id="myid1"></div>_x000D_
</li>_x000D_
<li>_x000D_
_x000D_
<div><label for="myid2">Subject2</label></div>_x000D_
<div class="check" ><input type="checkbox" value="2" class="subject-list" name="subjct" id="myid2"></div>_x000D_
</li>_x000D_
</ul>
_x000D_
These days (we don't need Internet Explorer 6-7-8 any more) I would just use CSS display: table
for this issue (or display: flex
).
Table:
.vcenter {_x000D_
display: table;_x000D_
background: #eee; /* optional */_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
text-align: center; /* optional */_x000D_
}_x000D_
_x000D_
.vcenter > :first-child {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div class="vcenter">_x000D_
<p>This is my Text</p>_x000D_
</div>
_x000D_
Flex:
.vcenter {_x000D_
display: flex; /* <-- Here */_x000D_
align-items: center; /* <-- Here */_x000D_
justify-content: center; /* optional */_x000D_
height: 150px; /* <-- Here */_x000D_
background: #eee; /* optional */_x000D_
width: 150px;_x000D_
}
_x000D_
<div class="vcenter">_x000D_
<p>This is my text</p>_x000D_
</div>
_x000D_
This is (actually, was) my favorite solution for this issue (simple and very well browser supported):
div {_x000D_
margin: 5px;_x000D_
text-align: center;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.vcenter {_x000D_
background: #eee; /* optional */_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
}_x000D_
.vcenter:before {_x000D_
content: " ";_x000D_
display: inline-block;_x000D_
height: 100%;_x000D_
vertical-align: middle;_x000D_
max-width: 0.001%; /* Just in case the text wrapps, you shouldn't notice it */_x000D_
}_x000D_
_x000D_
.vcenter > :first-child {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
max-width: 99.999%;_x000D_
}
_x000D_
<div class="vcenter">_x000D_
<p>This is my text</p>_x000D_
</div>_x000D_
<div class="vcenter">_x000D_
<h4>This is my Text<br/>Text<br/>Text</h4>_x000D_
</div>_x000D_
<div class="vcenter">_x000D_
<div>_x000D_
<p>This is my</p>_x000D_
<p>Text</p>_x000D_
</div>_x000D_
</div>
_x000D_
It can be confusing, I agree. Try utilizing table features. I use this simple CSS trick to position modals at the center of the webpage. It has large browser support:
<div class="table">
<div class="cell">
<img src="..." alt="..." />
<span>It works now</span>
</div>
</div>
and CSS part:
.table { display: table; }
.cell { display: table-cell; vertical-align: middle; }
Note that you have to style and adjust the size of image and table container to make it work as you desire. Enjoy.
Give vertical-align:top;
in a
& span
. Like this:
a, span{
vertical-align:top;
}
Check this http://jsfiddle.net/TFPx8/10/
h2.text-left{
position:relative;
top:50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
}
Explanation:
The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.
Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.
A possible fix for multiple lines would be to use a percentage slightly less than 50%.
If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.
The most effective way to center text in IE is to use something like this with "dy":
<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>
The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.
Update April 10, 2016
Flexboxes should now be used to vertically (or even horizontally) align items.
body {
height: 150px;
border: 5px solid cyan;
font-size: 50px;
display: flex;
align-items: center; /* Vertical center alignment */
justify-content: center; /* Horizontal center alignment */
}
_x000D_
Middle
_x000D_
A good guide to flexbox can be read on CSS Tricks. Thanks Ben (from comments) for pointing it out. I didn't have time to update.
A good guy named Mahendra posted a very working solution here.
The following class should make the element horizontally and vertically centered to its parent.
.absolute-center {
/* Internet Explorer 10 */
display: -ms-flexbox;
-ms-flex-pack: center;
-ms-flex-align: center;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari, Opera, and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr;" class="add-heading">
<hr class="add-hr">
<h2>Add Employer</h2>
<hr class="add-hr">
</div>
.add-hr {
display: block; height: 1px;
border: 0; border-top: 4px solid #000;
margin: 1em 0; padding: 0;
}
.add-heading h2{
text-align: center;
}
Though I'm too late, but this is very easy and simple. Page center is always left 50%, and top 50%. So minus the div width and height 50% and set left margin and right margin. Hope it work's for everywhere -
body{_x000D_
background: #EEE;_x000D_
}_x000D_
.center-div{_x000D_
position: absolute;_x000D_
width: 200px;_x000D_
height: 60px;_x000D_
left: 50%; _x000D_
margin-left: -100px;_x000D_
top: 50%;_x000D_
margin-top: -30px;_x000D_
background: #CCC;_x000D_
color: #000;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="center-div">_x000D_
<h3>This is center div</h3>_x000D_
</div>
_x000D_
However many years late this response may be, anyone coming across this might just want to try
li {
display: flex;
flex-direction: row;
align-items: center;
}
Browser support for flexbox is far better than it was when @scottjoudry posted his response above, but you may still want to consider prefixing or other options if you're trying to support much older browsers. caniuse: flex
Here is an example of some SVG code I used to get three lines of vertical text into a table column heading. Other angles are possible with a bit of tweaking. I believe most browsers support SVG these days.
<svg height="150" width="40">
<text font-weight="bold" x="-150" y="10" transform="rotate(-90 0 0)">Jane Doe</text>
<text x="-150" y="25" transform="rotate(-90 0 0)">0/0 0/0</text>
<text x="-150" y="40" transform="rotate(-90 0 0)">2015-06-06</text>
Sorry, your browser does not support inline SVG.
</svg>
I think you can use layout:weight = 5
instead android:lines = 5
because when you port your app to smaller device - it does it nicely.. well, both attributes will accomplish your job..
There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
It works most of the time. I did have a problem where a div
was in a div
in a li
. The list item had a height set and the outer div
s made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.
Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then?
You now can do this with Flexbox justify-content: flex-end
now:
div {_x000D_
display: flex;_x000D_
justify-content: flex-end;_x000D_
align-items: flex-end;_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border: solid 1px red;_x000D_
}_x000D_
_x000D_
<div>_x000D_
Something to align_x000D_
</div>
_x000D_
Consult your Caniuse to see if Flexbox is right for you.
This is a very interesting bug. (In my opinion, it is a bug anyway) Nice find!
Regarding how to set it, I would recommend Camilo Martin's answer. But as to why, I'd like to explain this a bit if you guys don't mind.
In the CSS specs I found:
'padding'
Percentages: refer to width of containing block
… which is weird, but okay.
So, with a parent width: 210px
and a child padding-top: 50%
, I get a calculated/computed value of padding-top: 96.5px
– which is not the expected 105px
.
That is because in Windows (I'm not sure about other OSs), the size of common scrollbars is per default 17px × 100%
(or 100% × 17px
for horizontal bars). Those 17px
are substracted before calculating the 50%
, hence 50% of 193px = 96.5px
.
something like
position:relative;
top:-5px;
just on the inline element itself works for me. Have to play with the top to get it centered vertically...
Here's a technique that allows you to center ANY content both vertically and horizontally!
Basically, you just need a two containers and make sure your elements meet the following criteria.
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
If you use this technique, just add your image (along with any other content you want to go with it) to the content box.
body {_x000D_
margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
position : absolute;_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
display: inline-block;_x000D_
background: #fff;_x000D_
padding : 12px;_x000D_
border : 1px solid #000;_x000D_
}_x000D_
_x000D_
img {_x000D_
max-width : 120px;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
<div class="inner-container">_x000D_
<div class="centered-content">_x000D_
<img src="https://i.stack.imgur.com/mRsBv.png" />_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
See also this Fiddle!
I found this solution in this article
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
It work like a charm if the height of element is not fixed.
Edited:
The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.
Read this article for Understanding vertical-align
I'm aware this question was asked over two years ago, but for any recent viewers, here's an alternative solution, which has a few advantages over Marc-François's solution:
div {
height: 50px;
border: 1px solid blue;
line-height: 50px;
}
Here we simply only add a line-height
equal to that of the height of the div. The advantage being you can now change the display property of the div as you see fit, to inline-block
for instance, and it's contents will remain vertically centered. The accepted solution requires you treat the div as a table cell. This should work perfectly, cross-browser.
The only other advantage being it's just one more CSS rule instead of two :)
Cheers!
well, the other answers seem to cover everything required, so I would like to just add this if you are using JMonkeyEngine:
Vector3f.angleBetween(otherVector)
as that is what I came here looking for :)
Xcode 8.2.1 • Swift 3.0.2
Locale.availableIdentifiers
Locale.isoRegionCodes
Locale.isoCurrencyCodes
Locale.isoLanguageCodes
Locale.commonISOCurrencyCodes
Locale.current.regionCode // "US"
Locale.current.languageCode // "en"
Locale.current.currencyCode // "USD"
Locale.current.currencySymbol // "$"
Locale.current.groupingSeparator // ","
Locale.current.decimalSeparator // "."
Locale.current.usesMetricSystem // false
Locale.windowsLocaleCode(fromIdentifier: "pt_BR") // 1,046
Locale.identifier(fromWindowsLocaleCode: 1046) ?? "" // "pt_BR"
Locale.windowsLocaleCode(fromIdentifier: Locale.current.identifier) // 1,033 Note: I am in Brasil but I use "en_US" format with all my devices
Locale.windowsLocaleCode(fromIdentifier: "en_US") // 1,033
Locale.identifier(fromWindowsLocaleCode: 1033) ?? "" // "en_US"
Locale(identifier: "en_US_POSIX").localizedString(forLanguageCode: "pt") // "Portuguese"
Locale(identifier: "en_US_POSIX").localizedString(forRegionCode: "br") // "Brazil"
Locale(identifier: "en_US_POSIX").localizedString(forIdentifier: "pt_BR") // "Portuguese (Brazil)"
TimeZone.current.localizedName(for: .standard, locale: .current) ?? "" // "Brasilia Standard Time"
TimeZone.current.localizedName(for: .shortStandard, locale: .current) ?? "" // "GMT-3
TimeZone.current.localizedName(for: .daylightSaving, locale: .current) ?? "" // "Brasilia Summer Time"
TimeZone.current.localizedName(for: .shortDaylightSaving, locale: .current) ?? "" // "GMT-2"
TimeZone.current.localizedName(for: .generic, locale: .current) ?? "" // "Brasilia Time"
TimeZone.current.localizedName(for: .shortGeneric, locale: .current) ?? "" // "Sao Paulo Time"
var timeZone: String {
return TimeZone.current.localizedName(for: TimeZone.current.isDaylightSavingTime() ?
.daylightSaving :
.standard,
locale: .current) ?? "" }
timeZone // "Brasilia Summer Time"
put at the start of my programs its use full for work with python
import sys
if sys.version_info[0] < 3:
raise Exception("Python 3 or a more recent version is required.")
This code will help full for the progress
The cleanest way to fix this is to apply the vertical-align: top
property to you CSS rules:
#div1 div {
width:30px;height:30px;
border:blue 1px solid;
display:inline-block;
*display:inline;zoom:1;
margin:0px;outline:none;
vertical-align: top;
}
If you were to add content to your div
's, then using either line-height: 0
or font-size: 0
would cause problems with your text layout.
See fiddle: http://jsfiddle.net/audetwebdesign/eJqaZ/
This problem can arise when a browser is in "quirks" mode. In this example, changing the doctype from:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
to
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
will change how the browser deals with extra whitespace.
In quirks mode, the whitespace is ignored, but preserved in strict mode.
References:
https://developer.mozilla.org/en/Images,_Tables,_and_Mysterious_Gaps
I had the same issue symbolic link helped me out: sudo ln -s /usr/bin/nodejs /usr/bin/node after that sudo npm install -g phantomjs-prebuilt
went smoothly
If your computer, OS and python are 64-bit, then you can use the mmap module to map the contents of the file into memory and access it with indices and slices. Here an example from the documentation:
import mmap
with open("hello.txt", "r+") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print map.readline() # prints "Hello Python!"
# read content via slice notation
print map[:5] # prints "Hello"
# update content using slice notation;
# note that new content must have same size
map[6:] = " world!\n"
# ... and read again using standard file methods
map.seek(0)
print map.readline() # prints "Hello world!"
# close the map
map.close()
If either your computer, OS or python are 32-bit, then mmap-ing large files can reserve large parts of your address space and starve your program of memory.
This is what you need.
var hasNumber = /\d/;
hasNumber.test("ABC33SDF"); //true
hasNumber.test("ABCSDF"); //false
I use this method for purely counting how many lines in a file. What is the downside of doing this verses the other answers. I'm seeing many lines as opposed to my two line solution. I'm guessing there's a reason nobody does this.
$lines = count(file('your.file'));
echo $lines;
What about using something like PouchDB? http://pouchdb.com/
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
For get response in JSON format :
1.$response = (string) $res->getBody();
$response =json_decode($response); // Using this you can access any key like below
$key_value = $response->key_name; //access key
2. $response = json_decode($res->getBody(),true);
$key_value = $response['key_name'];//access key
I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:
while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd
So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.
<input type="file" onchange="getBaseUrl()">
function getBaseUrl () {
var file = document.querySelector('input[type=file]')['files'][0];
var reader = new FileReader();
var baseString;
reader.onloadend = function () {
baseString = reader.result;
console.log(baseString);
};
reader.readAsDataURL(file);
}
Unix timestamp is in seconds, so simply add the corresponding number of seconds to the timestamp:
$timeInFuture = time() + (60 * 60 * 24);
protected void lbAddtoDestination_Click(object sender, EventArgs e)
{
AddRemoveItemsListBox(lstSourceSkills, lstDestinationSkills);
}
protected void lbRemovefromDestination_Click(object sender, EventArgs e)
{
AddRemoveItemsListBox(lstDestinationSkills, lstSourceSkills);
}
private void AddRemoveItemsListBox(ListBox source, ListBox destination)
{
List<ListItem> toBeRemoved = new List<ListItem>();
foreach (ListItem item in source.Items)
{
if (item.Selected)
{
toBeRemoved.Add(item);
destination.Items.Add(item);
}
}
foreach (ListItem item in toBeRemoved) source.Items.Remove(item);
}
In case anyone else comes by and was still wondering, here's a function using Michael's explanation in C++
vector< vector<int> > getAllSubsets(vector<int> set)
{
vector< vector<int> > subset;
vector<int> empty;
subset.push_back( empty );
for (int i = 0; i < set.size(); i++)
{
vector< vector<int> > subsetTemp = subset; //making a copy of given 2-d vector.
for (int j = 0; j < subsetTemp.size(); j++)
subsetTemp[j].push_back( set[i] ); // adding set[i] element to each subset of subsetTemp. like adding {2}(in 2nd iteration to {{},{1}} which gives {{2},{1,2}}.
for (int j = 0; j < subsetTemp.size(); j++)
subset.push_back( subsetTemp[j] ); //now adding modified subsetTemp to original subset (before{{},{1}} , after{{},{1},{2},{1,2}})
}
return subset;
}
Take into account though, that this will return a set of size 2^N with ALL possible subsets, meaning there will possibly be duplicates. If you don't want this, I would suggest actually using a set
instead of a vector
(which I used to avoid iterators in the code).
Seems like you have your path right. But what is your working directory? on command prompt run:
javac -version
this should show your java version. if it doesnt, you have not set java in path correctly.
navigate to C:
cd \
Then:
javac -sourcepath users\AccName\Desktop -d users\AccName\Desktop first.java
-sourcepath is the complete path to your .java file, -d is the path/directory you want your .class files to be, then finally the file you want compiled (first.java).
var text = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);
This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().
Bootstrap 3 example with side by side buttons below the content
.panel-heading {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.panel-group .panel+.panel {_x000D_
margin: 0;_x000D_
border: 0;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
border: 0 !important;_x000D_
-webkit-box-shadow: none !important;_x000D_
box-shadow: none !important;_x000D_
background-color: transparent !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<div class="panel-group" id="accordion">_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse1" class="panel-collapse collapse in">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse2" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse3" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collaple Group 3</a>_x000D_
</h4>_x000D_
</div>
_x000D_
Bootstrap 3 example with side by side buttons above the content
.panel-heading {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.panel-group .panel+.panel {_x000D_
margin: 0;_x000D_
border: 0;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
border: 0 !important;_x000D_
-webkit-box-shadow: none !important;_x000D_
box-shadow: none !important;_x000D_
background-color: transparent !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-heading">_x000D_
<h4 class="panel-title">_x000D_
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collaple Group 3</a>_x000D_
</h4>_x000D_
</div>_x000D_
<div class="panel-group" id="accordion">_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse1" class="panel-collapse collapse in">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse2" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div id="collapse3" class="panel-collapse collapse">_x000D_
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.
Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.
Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.
References have a couple more advantages compared to pointers (e. g. they can't be NULL
, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.
We control fork() process call by if, else statement. See my code below:
int main()
{
int forkresult, parent_ID;
forkresult=fork();
if(forkresult !=0 )
{
printf(" I am the parent my ID is = %d" , getpid());
printf(" and my child ID is = %d\n" , forkresult);
}
parent_ID = getpid();
if(forkresult ==0)
printf(" I am the child ID is = %d",getpid());
else
printf(" and my parent ID is = %d", parent_ID);
}
Something like this ought to do:
$url = preg_replace("|^.+?://|", "", $url);
Removes everything up to and including the ://
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.
This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.
Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts
On stackoverflow, see:
Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?
MattDMo's answer here: What is the default font of Sublime Text?
I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)
Other viewing environments that benefit from shorter lines:
github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.
The code of JS20'07'11 is really incredible simple and direct. One suggestion that I would like to give is to put a exclamation mark in the conditions:
InStr(1, objName.RefersTo, sWsName+"!", vbTextCompare)
Because this will prevent adding a NamedRange in an incorrect Sheet. Eg: If the NamedRange refers to a Sheet named Plan11 and you have another Sheet named Plan1 the code can do some mess when add the ranges if you don't use the exclamation mark.
UPDATE
A correction: It's best to use a regular expression evaluate the name of the Sheet. A simple function that you can use is the following (adapted by http://blog.malcolmp.com/2010/regular-expressions-excel-add-in, enable Microsoft VBScript Regular Expressions 5.5):
Function xMatch(pattern As String, searchText As String, Optional matchIndex As Integer = 1, Optional ignoreCase As Boolean = True) As String
On Error Resume Next
Dim RegEx As New RegExp
RegEx.Global = True
RegEx.MultiLine = True
RegEx.pattern = pattern
RegEx.ignoreCase = ignoreCase
Dim matches As MatchCollection
Set matches = RegEx.Execute(searchText)
Dim i As Integer
i = 1
For Each Match In matches
If i = matchIndex Then
xMatch = Match.Value
End If
i = i + 1
Next
End Function
So, You can use something like that:
xMatch("'?" +sWsName + "'?" + "!", objName.RefersTo, 1) <> ""
instead of
InStr(1, objName.RefersTo, sWsName+"!", vbTextCompare)
This will cover Plan1 and 'Plan1' (when the range refers to more than one cell) variations
TIP: Avoid Sheet names with single quotes ('), :) .
Unique Keys: The columns in which no two rows are similar
Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.
Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.
# If you want to edit the file in-place
sed -i -e 's/^/prefix/' file
# If you want to create a new file
sed -e 's/^/prefix/' file > file.new
If prefix
contains /
, you can use any other character not in prefix
, or
escape the /
, so the sed
command becomes
's#^#/opt/workdir#'
# or
's/^/\/opt\/workdir/'
Sometimes you need to reset ADB. To do that, in Eclipse, go:
Window>> Show View >> Android (Might be found in the "Other" option)>>Devices
in the device Tab, click the down arrow, and choose reset adb.
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
In Netbeans 11(Gladle Project) follow these steps:
In the tab files>yourprojectname>
double click in the file "build.gladle"
than set in line "mainClassName:'yourpackagepath.YourMainClass'"
Hope this helps!
You can try with this. You have this error because we can not divide by 'zero' (0)
value. So we want to validate before when we do calculations.
if ($itemCost != 0 && $itemCost != NULL && $itemQty != 0 && $itemQty != NULL)
{
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}
And also we can validate POST
data. Refer following
$itemQty = isset($_POST['num1']) ? $_POST['num1'] : 0;
$itemCost = isset($_POST['num2']) ? $_POST['num2'] : 0;
$itemSale = isset($_POST['num3']) ? $_POST['num3'] : 0;
$shipMat = isset($_POST['num4']) ? $_POST['num4'] : 0;
You also may encounter this issue because your device manufacturer did not license the Google commercial apps, such as Play Store, YouTube, Google Maps, etc. Follow this answer to solve the problem.
let a = 0.0500
a.toFixed(2);
//output
0.05
So if the insert time is what you need, it's already there:
Login to mongodb shell
ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test
Create your database by inserting items
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
>
Lets make that database the one we are on now
> use penguins
switched to db penguins
Get the rows back:
> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }
Get each row in yyyy-MM-dd HH:mm:ss format:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53
If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131
MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.
This means that @Jader Dias's solution wouldn't work everywhere.
Here is a solution that would work when ONLY_FULL_GROUP_BY
is enabled:
SET @row := NULL;
SELECT
SomeColumn,
AnotherColumn
FROM (
SELECT
CASE @id <=> SomeColumn AND @row IS NOT NULL
WHEN TRUE THEN @row := @row+1
ELSE @row := 0
END AS rownum,
@id := SomeColumn AS SomeColumn,
AnotherColumn
FROM
SomeTable
ORDER BY
SomeColumn, -AnotherColumn DESC
) _values
WHERE rownum = 0
ORDER BY SomeColumn;
I had same issue. I found the answer:
ini_set('memory_limit', '-1');
Update: Use this carefully as this might slow down your system if the PHP script starts using an excessive amount of memory, causing a lot of swap space usage. You can use this if you know program will not take much memory and also you don't know how much to set it right now. But you will eventually find it how much memory you require for that program.
You should always memory limit as some value as answered by @sarki dinle
.
ini_set('memory_limit', '512M');
I have used ajax load to do this:
$('#user_content').load('@Url.Action("UserDetails","User")');
Tools-> Options-> Select no proxy is worked for me
Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":
List initialization does not allow narrowing (§iso.8.5.4). That is:
Example:
void fun(double val, int val2) {
int x2 = val; // if val == 7.9, x2 becomes 7 (bad)
char c2 = val2; // if val2 == 1025, c2 becomes 1 (bad)
int x3 {val}; // error: possible truncation (good)
char c3 {val2}; // error: possible narrowing (good)
char c4 {24}; // OK: 24 can be represented exactly as a char (good)
char c5 {264}; // error (assuming 8-bit chars): 264 cannot be
// represented as a char (good)
int x4 {2.0}; // error: no double to int value conversion (good)
}
The only situation where = is preferred over {} is when using auto
keyword to get the type determined by the initializer.
Example:
auto z1 {99}; // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99; // z3 is an int
Prefer {} initialization over alternatives unless you have a strong reason not to.
Put all the ids into a variable called $ids and separate them with a ",":
$ids = "1,2,3,4,5,6";
Pass them like so:
$url = "?ids={$ids}";
Process them:
$ids = explode(",", $_GET['ids']);
One of the most straightforward ways to do it is
git for-each-ref --format='%(refname:short)' refs/heads/
This works perfectly for scripts as well.
Since there is no complete example for C++ yet, this is how you can insert and retrieve an array/vector of float data without error checking:
#include <sqlite3.h>
#include <iostream>
#include <vector>
int main()
{
// open sqlite3 database connection
sqlite3* db;
sqlite3_open("path/to/database.db", &db);
// insert blob
{
sqlite3_stmt* stmtInsert = nullptr;
sqlite3_prepare_v2(db, "INSERT INTO table_name (vector_blob) VALUES (?)", -1, &stmtInsert, nullptr);
std::vector<float> blobData(128); // your data
sqlite3_bind_blob(stmtInsertFace, 1, blobData.data(), static_cast<int>(blobData.size() * sizeof(float)), SQLITE_STATIC);
if (sqlite3_step(stmtInsert) == SQLITE_DONE)
std::cout << "Insert successful" << std::endl;
else
std::cout << "Insert failed" << std::endl;
sqlite3_finalize(stmtInsert);
}
// retrieve blob
{
sqlite3_stmt* stmtRetrieve = nullptr;
sqlite3_prepare_v2(db, "SELECT vector_blob FROM table_name WHERE id = ?", -1, &stmtRetrieve, nullptr);
int id = 1; // your id
sqlite3_bind_int(stmtRetrieve, 1, id);
std::vector<float> blobData;
if (sqlite3_step(stmtRetrieve) == SQLITE_ROW)
{
// retrieve blob data
const float* pdata = reinterpret_cast<const float*>(sqlite3_column_blob(stmtRetrieve, 0));
// query blob data size
blobData.resize(sqlite3_column_bytes(stmtRetrieve, 0) / static_cast<int>(sizeof(float)));
// copy to data vector
std::copy(pdata, pdata + static_cast<int>(blobData.size()), blobData.data());
}
sqlite3_finalize(stmtRetrieve);
}
sqlite3_close(db);
return 0;
}
sharing the latest on mat-dialog two ways of achieving this... 1) either you set the width and height during the open e.g.
let dialogRef = dialog.open(NwasNtdSelectorComponent, {
data: {
title: "NWAS NTD"
},
width: '600px',
height: '600px',
panelClass: 'epsSelectorPanel'
});
or
2) use the panelClass
and style it accordingly.
1) is easiest but 2) is better and more configurable.
The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath()
(and thus NOT getServletPath()
as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}
.
<p>The context path is: ${pageContext.request.contextPath}.</p>
If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base>
tag:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
<!doctype html>
<html lang="en">
<head>
<title>SO question 2204870</title>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
<script src="js/global.js"></script>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<ul>
<li><a href="home.jsp">Home</a></li>
<li><a href="faq.jsp">FAQ</a></li>
<li><a href="contact.jsp">Contact</a></li>
</ul>
</body>
</html>
All links in the page will then automagically be relative to the <base>
so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /
, then they will not be relative to the <base>
anymore, but to the domain root instead.
use os.path.isdir(path)
more info here http://docs.python.org/library/os.path.html
There is a great solution for this problem ,You can use the Merge Keyword of Sql
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
You can check this before following, below is the sample
IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
DROP TABLE dbo.TargetTable
GO
CREATE TABLE dbo.TargetTable
(
Id INT NOT NULL,
Name VARCHAR (255) NOT NULL,
CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
)
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'
Sooner or later you will have property with special character. You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
Let's say you are writing a test case for a negative flow where the code being tested should raise an exception.
try{
bizMethod(badData);
fail(); // FAIL when no exception is thrown
} catch (BizException e) {
assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}
// for numbers
a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
$.unique(a)
[7, 6, 1, 8, 3, 2, 5, 4]
// for string
a = ["a", "a", "b"]
$.unique(a)
["b", "a"]
And for dom elements there is no example is needed here I guess because you already know that!
Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/
As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.
secondly, i think a correct constructor of the BufferedReader class will help you do your task.
String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();
this should help you.
There are already some great answers but I would like to add a little visual explanation
Now, take a look at the image, there are
n/2^1
green nodes with height 0 (here 23/2 = 12)
n/2^2
red nodes with height 1 (here 23/4 = 6)
n/2^3
blue node with height 2 (here 23/8 = 3)
n/2^4
purple nodes with height 3 (here 23/16 = 2)
so there are n/2^(h+1)
nodes for height h
To find the time complexity lets count the amount of work done or max no of iterations performed by each node
now it can be noticed that each node can perform(atmost) iterations == height of the node
Green = n/2^1 * 0 (no iterations since no children)
red = n/2^2 * 1 (heapify will perform atmost one swap for each red node)
blue = n/2^3 * 2 (heapify will perform atmost two swaps for each blue node)
purple = n/2^4 * 3 (heapify will perform atmost three swaps for each purple node)
so for any nodes with height h maximum work done is n/2^(h+1) * h
Now total work done is
->(n/2^1 * 0) + (n/2^2 * 1)+ (n/2^3 * 2) + (n/2^4 * 3) +...+ (n/2^(h+1) * h)
-> n * ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) )
now for any value of h, the sequence
-> ( 0 + 1/4 + 2/8 + 3/16 +...+ h/2^(h+1) )
will never exceed 1
Thus the time complexity will never exceed O(n) for building heap
Recursively find all controls matching the specified predicate (do not include root Control):
public static IEnumerable<Control> FindControlsRecursive(this Control control, Func<Control, bool> predicate)
{
var results = new List<Control>();
foreach (Control child in control.Controls)
{
if (predicate(child))
{
results.Add(child);
}
results.AddRange(child.FindControlsRecursive(predicate));
}
return results;
}
Usage:
myControl.FindControlsRecursive(c => c.ID == "findThisID");
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("listfile.txt")
Dim inFile: Set inFile = obj.OpenTextFile("listfile.txt")
' read file
data = inFile.ReadAll
inFile.Close
' write file
outFile.write (data)
outFile.Close
Generally git pull
is enough, but I'm not sure what layout you have chosen (or has github chosen for you).
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
Just an update.
Now if it's a github repository then using just a github shorthand is enough if you do not mind the version of course.
$ bower install desandro/masonry
I installed Bitnami WAMP Stack 7.1.29-0 and it asked for a password during installation. In this case it was
username: root
password: <password set by you during install>
How about sys.exit()
from the module sys
.
If sys.exit()
is executed from within a thread it will close that thread only.
This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?
How to get the size of a list?
To find the size of a list, use the builtin function, len
:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
And now:
len(items)
returns 3.
Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.
Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called ob_size
, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.
But if you're checking if list size is zero or not, don't use len
- instead, put the list in a boolean context - it treated as False if empty, True otherwise.
len(s)
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
len
is implemented with __len__
, from the data model docs:
object.__len__(self)
Called to implement the built-in function
len()
. Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a__nonzero__()
[in Python 2 or__bool__()
in Python 3] method and whose__len__()
method returns zero is considered to be false in a Boolean context.
And we can also see that __len__
is a method of lists:
items.__len__()
returns 3.
len
(length) ofAnd in fact we see we can get this information for all of the described types:
>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,
range, dict, set, frozenset))
True
len
to test for an empty or nonempty listTo test for a specific length, of course, simply test for equality:
if len(items) == required_length:
...
But there's a special case for testing for a zero length list or the inverse. In that case, do not test for equality.
Also, do not do:
if len(items):
...
Instead, simply do:
if items: # Then we have some items, not empty!
...
or
if not items: # Then we have an empty list!
...
I explain why here but in short, if items
or if not items
is both more readable and more performant.
You don't need to list ContactPhoneAreaCode1 and ContactPhoneNumber1
SELECT FirstName AS First_Name,
LastName AS Last_Name,
COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.
Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?
Browsers might use the canPlayType
method internally to check if a <source>
is candidate to playback.
In Chrome, I have these results:
document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"
.box-author-txt {width:596px; float:left; padding:5px 0px 10px 10px; border:1px #dddddd solid; -moz-border-radius: 0 0 5px 5px; -webkit-border-radius: 0 0 5px 5px; -o-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; overflow-x: scroll; white-space: nowrap; overflow-y: hidden;}
.box-author-txt ul{ vertical-align:top; height:auto; display: inline-block; white-space: nowrap; margin:0 9px 0 0; padding:0px;}
.box-author-txt ul li{ list-style-type:none; width:140px; }
How about
Scanner scanner = new Scanner(result);
String line = scanner.nextLine();//will contain 34.1 -118.33
It didn't work for me when I tried to import the certificate in the browser... In chrome open Developer Tools > Security, and select View certificate. Click the Details tab and export it.
// LINUX
sudo apt-get install libnss3-tools
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n [EXPORTED_FILE_PATH] -i [EXPORTED_FILE_PATH]
Run this command and if you see the file You've just imported You are good to go!
certutil -d sql:$HOME/.pki/nssdb -L
// Windows
Start => run => certmgr.msc
On the left side select Trusted Root Certification Authorities => Personal. Click on actions tab => All actions/import then choose the file You exported before from the browser
Don't forget to restart chrome!!!
GOOD LUCK! ;)
Keep it Simple
Adding Floating Action Button using TextView by giving rounded xml background.
- Add compile com.android.support:design:23.1.1
to gradle file
Circle Xml is
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/colorPrimary"/>
<size
android:width="30dp"
android:height="30dp"/>
</shape>
Layout xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="5"
>
<RelativeLayout
android:id="@+id/viewA"
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1.6"
android:background="@drawable/contact_bg"
android:gravity="center_horizontal|center_vertical"
>
</RelativeLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="3.4"
android:orientation="vertical"
android:padding="16dp"
android:weightSum="10"
>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Name"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:id="@+id/name"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="Ritesh Kumar Singh"
android:singleLine="true"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Phone"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:id="@+id/number"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="8283001122"
android:textSize="22dp"
android:textColor="@android:color/black"
android:singleLine="true"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Email"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="[email protected]"
android:textSize="22dp"
android:singleLine="true"
android:textColor="@android:color/black"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="City"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="Panchkula"
android:textSize="22dp"
android:textColor="@android:color/black"
android:singleLine="true"
android:padding="3dp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/floating"
android:transitionName="@string/transition_name_circle"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="16dp"
android:clickable="false"
android:background="@drawable/circle"
android:elevation="10dp"
android:text="R"
android:textSize="40dp"
android:gravity="center"
android:textColor="@android:color/black"
app:layout_anchor="@id/viewA"
app:layout_anchorGravity="bottom"/>
</android.support.design.widget.CoordinatorLayout>
You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.
Something like:
...
watch: {
leaveType () {
this.whateverMethod(this.leaveType)
}
},
methods: {
onChange() {
console.log('The new value is: ', this.leaveType)
}
}
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
I have seen a bug that manifested as "Error installing artifact: File ../null/... does not exist" (that is, the file was not found because there was "null" in the path). The reason was that one environment variable was not visible to maven. It was:
JV_SRCROOT=$DIRECTORY
instead of
export JV_SRCROOT=$DIRECTORY
(in the latter case the variable is visible to child processes)
select *
from
tableA a
inner join
tableB b
on a.common = b.common
inner join
TableC c
on b.common = c.common
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);
<!DOCTYPE html>
<html>
<head>
<style>
table, td, th {
border: 1px solid;
border-collapse: collapse;
}
td , th {
padding: 5px;
width: 100px;
}
th {
background-color: lightgreen;
}
</style>
</head>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort car objects on age.</p>
<p id="demo"></p>
<script>
var nameArrow = "", yearArrow = "";
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
yearACS = true;
function sortYear() {
if (yearACS) {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
return a.year - b.year;
});
yearACS = false;
}else {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
return b.year - a.year;
});
yearACS = true;
}
displayCars();
}
nameACS = true;
function sortName() {
if (nameACS) {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
x = a.type.toLowerCase();
y = b.type.toLowerCase();
if (x > y) {return 1;}
if (x < y) {return -1};
return 0;
});
nameACS = false;
} else {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
x = a.type.toUpperCase();
y = b.type.toUpperCase();
if (x > y) { return -1};
if (x <y) { return 1 };
return 0;
});
nameACS = true;
}
displayCars();
}
displayCars();
function displayCars() {
var txt = "<table><tr><th onclick='sortName()'>name " + nameArrow + "</th><th onclick='sortYear()'>year " + yearArrow + "</th><tr>";
for (let i = 0; i < cars.length; i++) {
txt += "<tr><td>"+ cars[i].type + "</td><td>" + cars[i].year + "</td></tr>";
}
txt += "</table>";
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
_x000D_
The original code is a bit cumbersome and you might want to use the collections.deque instead if you want to use BFS to find if a path exists between 2 points on the graph. Here is a quick solution I hacked up:
Note: this method might continue infinitely if there exists no path between the two nodes. I haven't tested all cases, YMMV.
from collections import deque
# a sample graph
graph = {'A': ['B', 'C','E'],
'B': ['A','C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F','D'],
'F': ['C']}
def BFS(start, end):
""" Method to determine if a pair of vertices are connected using BFS
Args:
start, end: vertices for the traversal.
Returns:
[start, v1, v2, ... end]
"""
path = []
q = deque()
q.append(start)
while len(q):
tmp_vertex = q.popleft()
if tmp_vertex not in path:
path.append(tmp_vertex)
if tmp_vertex == end:
return path
for vertex in graph[tmp_vertex]:
if vertex not in path:
q.append(vertex)
If anyone like me is searching to read only a specific line, example only line 18 here is the code:
filename = "C:\log.log"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
For i = 1 to 17
f.ReadLine
Next
strLine = f.ReadLine
Wscript.Echo strLine
f.Close
That work sharp for me
SELECT *
FROM [dbo].[table1] t1
LEFT JOIN [dbo].[table2] t2 ON t1.[t1_ID] = t2.[t2_ID]
WHERE t2.[t2_ID] IS NULL
Add the jar file to your WEB-INF/lib folder. Right-click your project in Eclipse, and go to "Build Path > Configure Build Path" Add the "Web App Libraries" library This will ensure all WEB-INF/lib jars are included on the classpath. helped me..
Drag and drop in WEB-INF/lib folder and restart eclipse ans start webservice then create client
Another scenario for Static method.
Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.
Here, we have private constructor and using static method we are creating a object.
Ex::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
Demo obj1 = Demo.createObj();
Here, Only 1 instance will be alive at a time.
IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:
<?php
// First Array To Compare
$a1 = array('foo','bar','c');
// Target Array
$b1 = array('foo','bar');
// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
if (!in_array($x,$b1)) {
$b=false;
}
};
// Actual Test on array (can be repeated with others, but guard
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);
This relies on a closure; comparison function can become much more powerful. Good luck!
Add in numberOfRowsInSection your code [self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)];
. So you will set your contentInset always you reload data in your table
Since seotweaks
was originally created as a branch from master
, merging it back in is a good idea. However if you are in a situation where one of your branches is not really a branch from master
or your history is so different that you just want to obliterate the master
branch in favor of the new branch that you've been doing the work on you can do this:
git push [-f] origin seotweaks:master
This is especially helpful if you are getting this error:
! [remote rejected] master (deletion of the current branch prohibited)
And you are not using GitHub and don't have access to the "Administration" tab to change the default branch for your remote repository. Furthermore, this won't cause down time or race conditions as you may encounter by deleting master:
git push origin :master
Minimal example
And just to make what Mizux said as a minimal example:
main_c.c
#include <stdio.h>
int main(void) {
puts("hello");
}
main_cpp.cpp
#include <iostream>
int main(void) {
std::cout << "hello" << std::endl;
}
Then, without any Makefile
:
make CFLAGS='-g -O3' \
CXXFLAGS='-ggdb3 -O0' \
CPPFLAGS='-DX=1 -DY=2' \
CCFLAGS='--asdf' \
main_c \
main_cpp
runs:
cc -g -O3 -DX=1 -DY=2 main_c.c -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2 main_cpp.cpp -o main_cpp
So we understand that:
make
had implicit rules to make main_c
and main_cpp
from main_c.c
and main_cpp.cpp
.c
compilation.cpp
compilationThose variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:
main_c: main_c.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<
main_cpp: main_c.c
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<
to achieve a similar affect to the implicit rules.
We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.
Tested in Ubuntu 16.04, GNU Make 4.1.
It's very simple ;-)
First you must create two drawable file one for old api version and another one for newest version, Of course! if you create the drawable file for newest api version android studio suggest you to create old one automatically. and finally set this drawable to your background view.
Sample drawable for new api version (res/drawable-v21/ripple.xml):
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<corners android:radius="@dimen/round_corner" />
</shape>
</item>
</ripple>
Sample drawable for old api version (res/drawable/ripple.xml)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<corners android:radius="@dimen/round_corner" />
</shape>
For more info about ripple drawable just visit this: https://developer.android.com/reference/android/graphics/drawable/RippleDrawable.html
Vector needs to be initialized before using it as cin>>v[i][j]
. Even if it was 1D vector, it still needs an initialization, see this link
After initialization there will be no errors, see this link
use this code
var sid = $(this);
sid.attr('checked','checked');
WinPython is an open-source distribution that has 64-bit NumPy and SciPy.
Generators could be thought of as shorthand for creating an iterator. They behave like a Java Iterator. Example:
>>> g = (x for x in range(10))
>>> g
<generator object <genexpr> at 0x7fac1c1e6aa0>
>>> g.next()
0
>>> g.next()
1
>>> g.next()
2
>>> list(g) # force iterating the rest
[3, 4, 5, 6, 7, 8, 9]
>>> g.next() # iterator is at the end; calling next again will throw
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Hope this helps/is what you are looking for.
Update:
As many other answers are showing, there are different ways to create a generator. You can use the parentheses syntax as in my example above, or you can use yield. Another interesting feature is that generators can be "infinite" -- iterators that don't stop:
>>> def infinite_gen():
... n = 0
... while True:
... yield n
... n = n + 1
...
>>> g = infinite_gen()
>>> g.next()
0
>>> g.next()
1
>>> g.next()
2
>>> g.next()
3
...
Set the path JAVA_HOME and ANDROID_HOME > You have to open terminal and enter the below cmd.
touch ~/.bash_profile; open ~/.bash_profile
After that paste below paths in base profile file and save it
export ANDROID_HOME=/Users/<username>/Library/Android/sdk
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH"
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home
You should just use something like:
YourModel.update_all(
ActiveRecord::Base.send(:sanitize_sql_for_assignment, {:value => "'wow'"})
)
That would do the trick. Using the ActiveRecord::Base#send method to invoke the sanitize_sql_for_assignment makes the Ruby (at least the 1.8.7 version) skip the fact that the sanitize_sql_for_assignment is actually a protected method.
Swift 3.0 solution:
let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)
Check the Owner directory of "PHP-FPM"
You can do:
ls -lah /var/log/php-fpm/
chown -R webusr:webusr /var/log/php-fpm/
chmod -R 777 /var/log/php-fpm/
You are looking for the command scandir.
$path = '/tmp';
$files = scandir($path);
Following code will remove .
and ..
from the returned array from scandir
:
$files = array_diff(scandir($path), array('.', '..'));
I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find
... earlier):
<script type="text/javascript">
$(document).ready(function(){
$("select[showChoices]").each(function(){
$(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'> </span>");
doShowSelected($(this).attr('id'));//shows initial selections
}).change(function(){
doShowSelected($(this).attr('id'));//as user makes new selections
});
});
function doShowSelected(inId){
var aryVals=$("#"+inId).val();
var selText="";
for(var i=0; i<aryVals.length; i++){
var o="#"+inId+" option[value='"+aryVals[i]+"']";
selText+=$(o).text()+"<br>";
}
$("#spn"+inId).html(selText);
}
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
<option selected="selected" value=1>opt 1</option>
<option selected="selected" value=2>opt 2</option>
<option value=3>opt 3</option>
<option value=4>opt 4</option>
</select>
According to Swift 4 Documentation, String values can be added together (or concatenated) with the addition operator (+) to create a new String value:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
You can also append a String value to an existing String variable with the addition assignment operator (+=):
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
You can append a Character value to a String variable with the String type’s append() method:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
You have to enable USB debugging before plugging your device in to the computer. Unplug device then try to enable USB debugging. This should work. If so, you can then plug it back into the computer and it should work
On start or refresh value = 0 (default) How to get value from http request
<script>
$(function() {
$( "#slider-vertical" ).slider({
animate: 5000,
orientation: "vertical",
range: "max",
min: 0,
max: 100,
value: function( event, ui ) {
$( "#amount" ).val( ui.value );
// build a URL using the value from the slider
var geturl = "http://192.168.0.101/position";
// make an AJAX call to the Arduino
$.get(geturl, function(data) {
});
},
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
// build a URL using the value from the slider
var resturl = "http://192.168.0.101/set?points=" + ui.value;
// make an AJAX call to the Arduino
$.get(resturl, function(data) {
});
}
});
$( "#amount" ).val( $( "#slider-vertical" ).slider( "value" ) );
});
</script>
Arrays (called list
in python) use the []
notation. {}
is for dict
(also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
This is a development storage
part of Tomas M answer for Chrome. We must add listener
window.addEventListener("storage", (e)=> { console.log(e) } );
Load/save item in storage not runt this event - we MUST trigger it manually by
window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME
and now, all open tab-s will receive event
Try this command
msiexec /x {product-id} /qr
PHP’s mysql_real_escape_string
function is only a wrapper for MySQL’s mysql_real_escape_string
function. It basically prepares the input string to be safely used in a MySQL string declaration by escaping certain characters so that they can’t be misinterpreted as a string delimiter or an escape sequence delimiter and thereby allow certain injection attacks.
The real in mysql_real_escape_string
in opposite to mysql_escape_string
is due to the fact that it also takes the current character encoding into account as the risky characters are not encoded equally in the different character encodings. But you need to specify the character encoding change properly in order to get mysql_real_escape_string
work properly.
Turn on less secure app from this link and boom...
You can use this
"String.Format("{0:F2}", String Value);"
Gives you only the two digits after Dot, exactly two digits.
You can see marked answer on top. But i used getDialog().getCurrentFocus()
and working well. I post this answer cause i cant type "this"
in my oncreatedialog.
So this is my answer. If you tried marked answer and not worked , you can simply try this:
InputMethodManager inputManager = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
Try enclosing your date into a character string.
select *
from dbo.March2010 A
where A.Date >= '2010-04-01';
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
This is my version:
public String convertBytestoString(InputStream inputStream)
{
int bytes;
byte[] buffer = new byte[1024];
bytes = inputStream.read(buffer);
String stringData = new String(buffer,0,bytes);
return stringData;
}
Non-standard things are always strange :)
for the long long portion
under GNU it's L
, ll
or q
and under windows I believe it's ll
only
If you want to use it with groups, you can use:
library(plyr)
mydata<-mtcars
ddply(mydata,.(carb),colwise(sd))
carb mpg cyl disp hp drat wt qsec vs am gear
1 1 6.001349 0.9759001 75.90037 19.78215 0.5548702 0.6214499 0.590867 0.0000000 0.5345225 0.5345225
2 2 5.472152 2.0655911 122.50499 43.96413 0.6782568 0.8269761 1.967069 0.5270463 0.5163978 0.7888106
3 3 1.053565 0.0000000 0.00000 0.00000 0.0000000 0.1835756 0.305505 0.0000000 0.0000000 0.0000000
4 4 3.911081 1.0327956 132.06337 62.94972 0.4575102 1.0536001 1.394937 0.4216370 0.4830459 0.6992059
5 6 NA NA NA NA NA NA NA NA NA NA
6 8 NA NA NA NA NA NA NA NA NA NA
the documentations refers to an ASP.NET application.
You can try and have a look at my answer here.
I have an example attached to my reply.
Another example for ASP.NET MVC3 can be found here.
When embedding same-origin SVGs using <object>
, you can access the internal contents using objectElement.contentDocument.rootElement
. From there, you can easily attach event handlers (e.g. via onclick
, addEventListener()
, etc.)
For example:
var object = /* get DOM node for <object> */;
var svg = object.contentDocument.rootElement;
svg.addEventListener('click', function() {
console.log('hooray!');
});
Note that this is not possible for cross-origin <object>
elements unless you also control the <object>
origin server and can set CORS headers there. For cross-origin cases without CORS headers, access to contentDocument
is blocked.
The fastest way if your keys are in an SSH agent:
$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin
Each key in the agent will be printed as:
4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)
Put this in your title popover constructor...
'<button class="btn btn-danger btn-xs pull-right"
onclick="$(this).parent().parent().parent().hide()"><span class="glyphicon
glyphicon-remove"></span></button>some text'
...to get a small red 'x' button on top-right corner
//$('[data-toggle=popover]').popover({title:that string here})
If anyone using MS SQL Server 2008 and higher lands on this question: SQL Server 2008 and higher has a new "hierarchyId" feature designed specifically for this task.
More info at https://docs.microsoft.com/en-us/sql/relational-databases/hierarchical-data-sql-server
On MacOS
(I have Mojave/ 10.14, git
version 2.7.1), use bindfs
.
brew install bindfs
cd /path/to/git_controlled_dir
mkdir local_copy_dir
bindfs </full/path/to/source_dir> </full/path/to/local_copy_dir>
It's been hinted by other comments, but not clearly provided in other answers. Hopefully this saves someone some time.
str.isspace() returns False
for a valid and empty string
>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]
Therefore, checking with not
will also evaluate None
Type and ''
or ""
(empty string)
>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]
Yes, use @import
detailed info easily googled for, a good one at http://webdesign.about.com/od/beginningcss/f/css_import_link.htm
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
The idea consists to use the keys, when a value is already present in the array keys, the array size stays the same:
function getDistinctRandomNumbers ($nb, $min, $max) {
if ($max - $min + 1 < $nb)
return false; // or throw an exception
$res = array();
do {
$res[mt_rand($min, $max)] = 1;
} while (count($res) !== $nb);
return array_keys($res);
}
Pro: This way avoids the use of in_array
and doesn't generate a huge array. So, it is fast and preserves a lot of memory.
Cons: when the rate (range/quantity) decreases, the speed decreases too (but stays correct). For a same rate, relative speed increases with the range size.(*)
(*) I understand that fact since there are more free integers to select (in particular for the first steps), but if somebody has the mathematical formula that describes this behaviour, I am interested by, don't hesitate.
Conclusion: The best "general" function seems to be a mix between this function and @Anne function that is more efficient with a little rate. This function should switch between the two ways when a certain quantity is needed and a rate (range/quantity) is reached. So the complexity/time of the test to know that, must be taken in account.
I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.
The best way to combat this is to call the .always
chain method and do a bit of cleaning up. Here is my code.
$.ajax({
...
}).always(function(data, textStatus, xhr) {
var responseCode = null;
if (textStatus === "error") {
// data variable is actually xhr
responseCode = data.status;
if (data.responseText) {
try {
data = JSON.parse(data.responseText);
} catch (e) {
// Ignore
}
}
} else {
responseCode = xhr.status;
}
console.log("Response code", responseCode);
console.log("JSON Data", data);
});
Use reduce
let arr = [1, 2, 3, 4];_x000D_
_x000D_
let sum = arr.reduce((v, i) => (v + i));_x000D_
_x000D_
console.log(sum);
_x000D_
I recently came across this problem myself.
<!--Instead of using input-->
<input type="submit"/>
<!--Use button-->
<button type="submit">
<!--You can then attach your custom CSS to the button-->
Hope that helps.
edit your ~/.vimrc
$ vim ~/.vimrc
add following lines :
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
this seems to work as wel ->
@Override
public List<SomeObject> findAllForThisSpecificThing(String thing) {
final Query query = entityManager.createQuery(
"from " + getDomain().getSimpleName() + " t where t.thing = " + ((thing == null) ? " null" : " :thing"));
if (thing != null) {
query.setParameter("thing", thing);
}
return query.getResultList();
}
Btw, I'm pretty new at this, so if for any reason this isn't a good idea, let me know. Thanks.
Agree with previous answers.
A little correction: There's a better way to print the decimal digits from left to right, without allocating extra buffer. In addition you may want to display a zero characeter if the score
is 0 (the loop suggested in the previous answers won't print anythng).
This demands an additional pass:
int div;
for (div = 1; div <= score; div *= 10)
;
do
{
div /= 10;
printf("%d\n", score / div);
score %= div;
} while (score);
The px needs to be left off, for some odd reason.
If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:
Go to "Edit" in the figure window
Go to "Figure Properties"
At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".
That's all.
Good luck.
This has happened to me multiple times. I have used Amazon Linux AMI 2013.09.2 and Ubuntu Server 12.04.3 LTS which are both on the free tier.
Every time I have launched an instance I have permission denied show up. I haven't verified this but my theory is that the server is not completely set up before I try to ssh into it. After a few tries with permission denied, I wait a few minutes and then I am able to connect. If you are having this problem I suggest waiting five minutes and trying again.
In PHP, use mysqli_real_escape_string.
Example from the PHP Manual:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", mysqli_sqlstate($link));
}
$city = mysqli_real_escape_string($link, $city);
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
mysqli_close($link);
?>
Using .stop() on the stream works on chrome when connected via http. It does not work when using ssl (https).
I added a ticket to add an option of some sort here:
https://github.com/pydata/pandas/issues/1450
In the meantime, result.fillna('')
should do what you want
EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values
, empty strings will stay empty strings in the result
try this to get the current date.You can also get current hour, minutes and seconds by using getters :
new Date(System.currentTimeMillis()).get....()
From the npm docs:
git://github.com/<user>/<project>.git#<branch>
git://github.com/<user>/<project>.git#feature\/<branch>
As of NPM version 1.1.65, you can do this:
<user>/<project>#<branch>
You may try it like this:
DECLARE @i int = 0
WHILE @i < 300
BEGIN
SET @i = @i + 1
/* your code*/
END
Cross fields validations can be done by creating custom constraints.
Example:- Compare password and confirmPassword fields of User instance.
CompareStrings
@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy=CompareStringsValidator.class)
@Documented
public @interface CompareStrings {
String[] propertyNames();
StringComparisonMode matchMode() default EQUAL;
boolean allowNull() default false;
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
StringComparisonMode
public enum StringComparisonMode {
EQUAL, EQUAL_IGNORE_CASE, NOT_EQUAL, NOT_EQUAL_IGNORE_CASE
}
CompareStringsValidator
public class CompareStringsValidator implements ConstraintValidator<CompareStrings, Object> {
private String[] propertyNames;
private StringComparisonMode comparisonMode;
private boolean allowNull;
@Override
public void initialize(CompareStrings constraintAnnotation) {
this.propertyNames = constraintAnnotation.propertyNames();
this.comparisonMode = constraintAnnotation.matchMode();
this.allowNull = constraintAnnotation.allowNull();
}
@Override
public boolean isValid(Object target, ConstraintValidatorContext context) {
boolean isValid = true;
List<String> propertyValues = new ArrayList<String> (propertyNames.length);
for(int i=0; i<propertyNames.length; i++) {
String propertyValue = ConstraintValidatorHelper.getPropertyValue(String.class, propertyNames[i], target);
if(propertyValue == null) {
if(!allowNull) {
isValid = false;
break;
}
} else {
propertyValues.add(propertyValue);
}
}
if(isValid) {
isValid = ConstraintValidatorHelper.isValid(propertyValues, comparisonMode);
}
if (!isValid) {
/*
* if custom message was provided, don't touch it, otherwise build the
* default message
*/
String message = context.getDefaultConstraintMessageTemplate();
message = (message.isEmpty()) ? ConstraintValidatorHelper.resolveMessage(propertyNames, comparisonMode) : message;
context.disableDefaultConstraintViolation();
ConstraintViolationBuilder violationBuilder = context.buildConstraintViolationWithTemplate(message);
for (String propertyName : propertyNames) {
NodeBuilderDefinedContext nbdc = violationBuilder.addNode(propertyName);
nbdc.addConstraintViolation();
}
}
return isValid;
}
}
ConstraintValidatorHelper
public abstract class ConstraintValidatorHelper {
public static <T> T getPropertyValue(Class<T> requiredType, String propertyName, Object instance) {
if(requiredType == null) {
throw new IllegalArgumentException("Invalid argument. requiredType must NOT be null!");
}
if(propertyName == null) {
throw new IllegalArgumentException("Invalid argument. PropertyName must NOT be null!");
}
if(instance == null) {
throw new IllegalArgumentException("Invalid argument. Object instance must NOT be null!");
}
T returnValue = null;
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, instance.getClass());
Method readMethod = descriptor.getReadMethod();
if(readMethod == null) {
throw new IllegalStateException("Property '" + propertyName + "' of " + instance.getClass().getName() + " is NOT readable!");
}
if(requiredType.isAssignableFrom(readMethod.getReturnType())) {
try {
Object propertyValue = readMethod.invoke(instance);
returnValue = requiredType.cast(propertyValue);
} catch (Exception e) {
e.printStackTrace(); // unable to invoke readMethod
}
}
} catch (IntrospectionException e) {
throw new IllegalArgumentException("Property '" + propertyName + "' is NOT defined in " + instance.getClass().getName() + "!", e);
}
return returnValue;
}
public static boolean isValid(Collection<String> propertyValues, StringComparisonMode comparisonMode) {
boolean ignoreCase = false;
switch (comparisonMode) {
case EQUAL_IGNORE_CASE:
case NOT_EQUAL_IGNORE_CASE:
ignoreCase = true;
}
List<String> values = new ArrayList<String> (propertyValues.size());
for(String propertyValue : propertyValues) {
if(ignoreCase) {
values.add(propertyValue.toLowerCase());
} else {
values.add(propertyValue);
}
}
switch (comparisonMode) {
case EQUAL:
case EQUAL_IGNORE_CASE:
Set<String> uniqueValues = new HashSet<String> (values);
return uniqueValues.size() == 1 ? true : false;
case NOT_EQUAL:
case NOT_EQUAL_IGNORE_CASE:
Set<String> allValues = new HashSet<String> (values);
return allValues.size() == values.size() ? true : false;
}
return true;
}
public static String resolveMessage(String[] propertyNames, StringComparisonMode comparisonMode) {
StringBuffer buffer = concatPropertyNames(propertyNames);
buffer.append(" must");
switch(comparisonMode) {
case EQUAL:
case EQUAL_IGNORE_CASE:
buffer.append(" be equal");
break;
case NOT_EQUAL:
case NOT_EQUAL_IGNORE_CASE:
buffer.append(" not be equal");
break;
}
buffer.append('.');
return buffer.toString();
}
private static StringBuffer concatPropertyNames(String[] propertyNames) {
//TODO improve concating algorithm
StringBuffer buffer = new StringBuffer();
buffer.append('[');
for(String propertyName : propertyNames) {
char firstChar = Character.toUpperCase(propertyName.charAt(0));
buffer.append(firstChar);
buffer.append(propertyName.substring(1));
buffer.append(", ");
}
buffer.delete(buffer.length()-2, buffer.length());
buffer.append("]");
return buffer;
}
}
User
@CompareStrings(propertyNames={"password", "confirmPassword"})
public class User {
private String password;
private String confirmPassword;
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getConfirmPassword() { return confirmPassword; }
public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; }
}
Test
public void test() {
User user = new User();
user.setPassword("password");
user.setConfirmPassword("paSSword");
Set<ConstraintViolation<User>> violations = beanValidator.validate(user);
for(ConstraintViolation<User> violation : violations) {
logger.debug("Message:- " + violation.getMessage());
}
Assert.assertEquals(violations.size(), 1);
}
Output Message:- [Password, ConfirmPassword] must be equal.
By using the CompareStrings validation constraint, we can also compare more than two properties and we can mix any of four string comparison methods.
ColorChoice
@CompareStrings(propertyNames={"color1", "color2", "color3"}, matchMode=StringComparisonMode.NOT_EQUAL, message="Please choose three different colors.")
public class ColorChoice {
private String color1;
private String color2;
private String color3;
......
}
Test
ColorChoice colorChoice = new ColorChoice();
colorChoice.setColor1("black");
colorChoice.setColor2("white");
colorChoice.setColor3("white");
Set<ConstraintViolation<ColorChoice>> colorChoiceviolations = beanValidator.validate(colorChoice);
for(ConstraintViolation<ColorChoice> violation : colorChoiceviolations) {
logger.debug("Message:- " + violation.getMessage());
}
Output Message:- Please choose three different colors.
Similarly, we can have CompareNumbers, CompareDates, etc cross-fields validation constraints.
P.S. I have not tested this code under production environment (though I tested it under dev environment), so consider this code as Milestone Release. If you find a bug, please write a nice comment. :)
Use re.sub
import re
regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'
Alternatively, if you only want to remove a certain set of characters (as an apostrophe might be okay in your input...)
regex = re.compile('[,\.!?]') #etc.
The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
This piece of code compares two lists both containing a field for a CultureCode like 'en-GB'. This will leave non existing translations in the list. (we needed a dropdown list for not-translated languages for articles)
var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();
map
can be used for the situation mentioned in the question.
E.g.
map(len, ['abcd','abc', 'a']) # 4 3 1
For functions that take multiple arguments, more arguments can be given to map:
map(pow, [2, 3], [4,2]) # 16 9
It returns a list in python 2.x and an iterator in python 3
In case your function takes multiple arguments and the arguments are already in the form of tuples (or any iterable since python 2.6) you can use itertools.starmap
. (which has a very similar syntax to what you were looking for). It returns an iterator.
E.g.
for num in starmap(pow, [(2,3), (3,2)]):
print(num)
gives us 8 and 9
Maven also houses a large repository of commonly used open source projects. During the build Maven can download these dependencies for you (as well as your dependencies dependencies :)) to make this part of building a project a little more manageable.
Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.
@Throws(IOException::class)
fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
.also {
if (!it.exists()) {
it.outputStream().use { cache ->
context.assets.open(fileName).use { inputStream ->
inputStream.copyTo(cache)
}
}
}
}
Get the path to the file like:
val filePath = getFileFromAssets(context, "fileName.extension").absolutePath
Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.
NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)
Here is a link with the appropriate formulas.
The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))
More information on the Index/Match formula
Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.
I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.
Good luck! Hope this helps.
I would use something like (with Scala [the code in old "good" Java 8 may be similar to this]):
object SeleniumFacade {
def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {
val elements = maybeParent match {
case Some(parent) => parent.findElements(bySelector).asScala
case None => driver.findElements(bySelector).asScala
}
if (elements.nonEmpty) {
Try { Some(elements(withIndex)) } getOrElse None
} else None
}
...
}
so then,
val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))
startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');
This Solved my problem: Open your VS Project
Double click on Package.appxmanifest
Go to Packaging tab
click choose certificate
click configure certificate
select from file and use example.pfx that unity or anything else created
Use the Array().forEach loop to take advantage of parallelism
Another option would be to just use perl with globstar.
Enabling shopt -s globstar
in your .bashrc
(or wherever) allows the **
glob pattern to match all sub-directories and files recursively.
Thus using perl -pXe 's/SEARCH/REPLACE/g' -i **
will recursively
replace SEARCH
with REPLACE
.
The -X
flag tells perl to "disable all warnings" - which means that
it won't complain about directories.
The globstar also allows you to do things like sed -i 's/SEARCH/REPLACE/g' **/*.ext
if you wanted to replace SEARCH
with REPLACE
in all child files with the extension .ext
.
maybe it help:
<see additional>
pip install gprof2dot
sudo apt-get install graphviz
gprof2dot -f pstats profile_for_func1_001 | dot -Tpng -o profile.png
def profileit(name):
"""
@profileit("profile_for_func1_001")
"""
def inner(func):
def wrapper(*args, **kwargs):
prof = cProfile.Profile()
retval = prof.runcall(func, *args, **kwargs)
# Note use of name from outer scope
prof.dump_stats(name)
return retval
return wrapper
return inner
@profileit("profile_for_func1_001")
def func1(...)
Nope, it doesn't seem like you're doing it wrong. MongoDB joins are "client side". Pretty much like you said:
At the moment, I am first getting the comments which match my criteria, then figuring out all the uid's in that result set, getting the user objects, and merging them with the comment's results. Seems like I am doing it wrong.
1) Select from the collection you're interested in.
2) From that collection pull out ID's you need
3) Select from other collections
4) Decorate your original results.
It's not a "real" join, but it's actually alot more useful than a SQL join because you don't have to deal with duplicate rows for "many" sided joins, instead your decorating the originally selected set.
There is alot of nonsense and FUD on this page. Turns out 5 years later MongoDB is still a thing.
One more related question, since it took me forever to find the answer:
How to make the legend background blank (i.e. transparent, not white):
legend = plt.legend()
legend.get_frame().set_facecolor('none')
Warning, you want 'none'
(the string). None
means the default color instead.
Object doesn't support this property or method.
Think of it like if anything after the dot is called on an object. It's like a chain.
An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot .
you get intelli-sense (that white dropdown) trying to help you pick the correct action.
(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)
Type this much anywhere in your code area
Dim a As Worksheets
a.
you get help from VBE, it's a little dropdown called Intelli-sense
It lists all available actions that particular object exposes to any user. You can't see the .Selection
member of the Worksheets()
class. That's what the error tells you exactly.
Object doesn't support this property or method.
If you look at the example on MSDN
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
It activates
the sheet first then calls the Selection...
it's not connected together because Selection
is not a member of Worksheets()
class. Simply, you can't prefix the Selection
What about
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
MsgBox "The selection contains " & Selection.Columns.Count & " columns."
Else
For i = 1 To iAreaCount
MsgBox "Area " & i & " of the selection contains " & _
Selection.Areas(i).Columns.Count & " columns."
Next i
End If
End Sub
from HERE
Make a class that will fit table cell width to content
.table td.fit,
.table th.fit {
white-space: nowrap;
width: 1%;
}
Afer looking at the source, for WP7 Hammock doesn't actually use Json.Net for JSON parsing. Instead it uses it's own parser which doesn't cope with custom types very well.
If using Json.Net directly it is possible to deserialize to a strongly typed collection inside a wrapper object.
var response = @"
{
""data"": [
{
""name"": ""A Jones"",
""id"": ""500015763""
},
{
""name"": ""B Smith"",
""id"": ""504986213""
},
{
""name"": ""C Brown"",
""id"": ""509034361""
}
]
}
";
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
return des.data.Count.ToString();
and with:
public class MyClass
{
public List<User> data { get; set; }
}
public class User
{
public string name { get; set; }
public string id { get; set; }
}
Having to create the extra object with the data property is annoying but that's a consequence of the way the JSON formatted object is constructed.
Documentation: Serializing and Deserializing JSON
In your comparator factory class, do something like this:
private static final Comparator<String> MYSTRING_COMPARATOR = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
};
public static Comparator<String> getMyStringComparator() {
return MYSTRING_COMPARATOR;
This uses the compare to method which is case insensitive (why write your own). This way you can use Collections sort like this:
List<String> myArray = new ArrayList<String>();
//fill your array here
Collections.sort(MyArray, MyComparators. getMyStringComparator());
"Curly Braces" are used in Python to define a dictionary. A dictionary is a data structure that maps one value to another - kind of like how an English dictionary maps a word to its definition.
Python:
dict = {
"a" : "Apple",
"b" : "Banana",
}
They are also used to format strings, instead of the old C style using %, like:
ds = ['a', 'b', 'c', 'd']
x = ['has_{} 1'.format(d) for d in ds]
print x
['has_a 1', 'has_b 1', 'has_c 1', 'has_d 1']
They are not used to denote code blocks as they are in many "C-like" languages.
C:
if (condition) {
// do this
}
I kept wondering why -fvisibility=hidden and #pragma GCC visibility did not seem to have any influence, as all the symbols were always visible with nm - until I found this post that pointed me to readelf and objdump, which made me realize that there seem to actually be two symbol tables:
I think the former contains debugging symbols that can be stripped with strip or the -s switch that you can give to the linker or the install command. And even if nm does not list anything anymore, your exported symbols are still exported because they are in the ELF "dynamic symbol table", which is the latter.
I use numpy.size() to do the same:
import numpy as np
import cv2
image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)
Here is a solution using hooks, Timer component, I'm replicating same logic above with hooks
import React from 'react'
import { useState, useEffect } from 'react';
const Timer = (props:any) => {
const {initialMinute = 0,initialSeconds = 0} = props;
const [ minutes, setMinutes ] = useState(initialMinute);
const [seconds, setSeconds ] = useState(initialSeconds);
useEffect(()=>{
let myInterval = setInterval(() => {
if (seconds > 0) {
setSeconds(seconds - 1);
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(myInterval)
} else {
setMinutes(minutes - 1);
setSeconds(59);
}
}
}, 1000)
return ()=> {
clearInterval(myInterval);
};
});
return (
<div>
{ minutes === 0 && seconds === 0
? null
: <h1> {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
}
</div>
)
}
export default Timer;
After trying several of these answers, then reaching out to a colleague, what worked for me on Ubuntu 16.04 was:
pip install --force-reinstall -U setuptools
pip install --force-reinstall -U pip
In my case, it was only an old version of pillow 3.1.1 that was having trouble (pillow 4.x worked fine), and that's now resolved!
UPDATED with latest official NuGet documentation as of v3.3.0
NuGet offers three approaches to using package restore.
Automatic Package Restore is the NuGet team's recommended approach to Package Restore within Visual Studio, and it was introduced in NuGet 2.7. Beginning with NuGet 2.7, the NuGet Visual Studio extension integrates into Visual Studio's build events and restores missing packages when a build begins. This feature is enabled by default, but developers can opt out if desired.
Here's how it works:
- On project or solution build, Visual Studio raises an event that a build is beginning within the solution.
- NuGet responds to this event and checks for packages.config files included in the solution.
- For each packages.config file found, its packages are enumerated and Checked for exists in the solution's packages folder.
- Any missing packages are downloaded from the user's configured (and enabled) package sources, respecting the order of the package sources.
- As packages are downloaded, they are unzipped into the solution's packages folder.
If you have Nuget 2.7+ installed; it's important to pick one method for > managing Automatic Package Restore in Visual Studio.
Two methods are available:
- (Nuget 2.7+): Visual Studio -> Tools -> Package Manager -> Package Manager Settings -> Enable Automatic Package Restore
- (Nuget 2.6 and below) Right clicking on a solution and clicking "Enable Package Restore for this solution".
Command-Line Package Restore is required when building a solution from the command-line; it was introduced in early versions of NuGet, but was improved in NuGet 2.7.
nuget.exe restore contoso.sln
The MSBuild-integrated package restore approach is the original Package Restore implementation and though it continues to work in many scenarios, it does not cover the full set of scenarios addressed by the other two approaches.
The VPATH option might come in handy, which tells make what directories to look in for source code. You'd still need a -I option for each include path, though. An example:
CXXFLAGS=-Ipart1/inc -Ipart2/inc -Ipart3/inc
VPATH=part1/src:part2/src:part3/src
OutputExecutable: part1api.o part2api.o part3api.o
This will automatically find the matching partXapi.cpp files in any of the VPATH specified directories and compile them. However, this is more useful when your src directory is broken into subdirectories. For what you describe, as others have said, you are probably better off with a makefile for each part, especially if each part can stand alone.
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
library(lubridate)
if your date format is like this '04/24/2017 05:35:00'then change it like below
prods.all$Date2<-gsub("/","-",prods.all$Date2)
then change the date format
parse_date_time(prods.all$Date2, orders="mdy hms")
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
Swift 5 Use button.setTitle()
@IBOutlet weak var button: UIButton!
setTitle
on the button followed by the text and the state.button.setTitle("Button text here", forState: .normal)
You can change background color and drop down icon like doing this way
Step1: In drawable folder make background.xml for border of spinner.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<corners android:radius="5dp" />
<stroke
android:width="1dp"
android:color="@color/darkGray" />
</shape> //edited
Step2: for layout design of spinner use this drop down icon or any image drop.pnj
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_weight=".28"
android:background="@drawable/spinner_border"
android:orientation="horizontal">
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:background="@android:color/transparent"
android:gravity="center"
android:layout_marginLeft="5dp"
android:spinnerMode="dropdown" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:src="@mipmap/drop" />
</RelativeLayout>
Finally looks like below image and it is every where clickable in round area and no need of to write click Lister for imageView.
For more details , you can see Here
Parse it (i.e. with Integer#parseInt
) and simply catch the exception. =)
To clarify: The parseInt function checks if it can parse the number in any case (obviously) and if you want to parse it anyway, you are not going to take any performance hit by actually doing the parsing.
If you would not want to parse it (or parse it very, very rarely) you might wish to do it differently of course.
As of this writing, it was necessary to:
You can use GROUP_CONCAT
:
SELECT person_id,
GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
As Ludwig stated in his comment, you can add the DISTINCT
operator to avoid duplicates:
SELECT person_id,
GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
As Jan stated in their comment, you can also sort the values before imploding it using ORDER BY
:
SELECT person_id,
GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
As Dag stated in his comment, there is a 1024 byte limit on the result. To solve this, run this query before your query:
SET group_concat_max_len = 2048;
Of course, you can change 2048
according to your needs. To calculate and assign the value:
SET group_concat_max_len = CAST(
(SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
FROM peoples_hobbies
GROUP BY person_id) AS UNSIGNED);
Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.
You need to:
Go to cloud.google.com
Go to my Console
Choose your Project
Choose Networking > VPC network
Choose "Firewalls rules"
Choose "Create Firewall Rule"
To apply the rule to select VM instances, select Targets > "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like. Then, make sure the instances have the network tag applied.
To allow incoming TCP connections to port 9090, in "Protocols and Ports" enter tcp:9090
Click Create
I hope this helps you.
Update Please refer to docs to customize your rules.
//@parram $data-array,$d-if true then die by default it is false
//@author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can use in this way....
while($row = mysql_fetch_array($result)){
p($row); // Use this function if you use above function in your page.
}
Newer versions of VirtualBox add an option for VBoxManage clonehd that allows you to clone to an existing (larger) virtual disk.
The process is detailed here: Expanding VirtualBox Dynamic VDIs
It's not built in, but if you want unusual length numbers then you could use the bitstring module.
>>> from bitstring import Bits
>>> a = Bits(bin='111111111111')
>>> a.int
-1
The same object can equivalently be created in several ways, including
>>> b = Bits(int=-1, length=12)
It just behaves like a string of bits of arbitrary length, and uses properties to get different interpretations:
>>> print a.int, a.uint, a.bin, a.hex, a.oct
-1 4095 111111111111 fff 7777
out
or ref
(since that changes the reference, not the object). A programmer therefore knows that if string x = "abc"
at the start of a method, and that doesn't change in the body of the method, then x == "abc"
at the end of the method."abc" == "ab" + "c"
. While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).Christmas.AddMonths(1)
produces a new DateTime
rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.return this
. Since the copy can't be changed anyway, pretending something is its own copy is safe.In all, for objects which don't have undergoing change as part of their purpose, there can be many advantages in being immutable. The main disadvantage is in requiring extra constructions, though even here it's often overstated (remember, you have to do several appends before StringBuilder becomes more efficient than the equivalent series of concatenations, with their inherent construction).
It would be a disadvantage if mutability was part of the purpose of an object (who'd want to be modeled by an Employee object whose salary could never ever change) though sometimes even then it can be useful (in a many web and other stateless applications, code doing read operations is separate from that doing updates, and using different objects may be natural - I wouldn't make an object immutable and then force that pattern, but if I already had that pattern I might make my "read" objects immutable for the performance and correctness-guarantee gain).
Copy-on-write is a middle ground. Here the "real" class holds a reference to a "state" class. State classes are shared on copy operations, but if you change the state, a new copy of the state class is created. This is more often used with C++ than C#, which is why it's std:string enjoys some, but not all, of the advantages of immutable types, while remaining mutable.
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
using this you can format date.
you can change the appearance in the way you want then
for more info you can visit here
One solution might be to change the i18n default error format:
en:
errors:
format: "%{message}"
Default is format: %{attribute} %{message}
Found here you can use user-scalable=no
:
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
axios.get(
'/app/export'
).then(response => {
const url = window.URL.createObjectURL(new Blob([response]));
const link = document.createElement('a');
link.href = url;
const fileName = `${+ new Date()}.csv`// whatever your file name .
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
link.remove();// you need to remove that elelment which is created before.
})
I have released a package called python-drawnow that provides functionality to let a figure update, typically called within a for loop, similar to Matlab's drawnow
.
An example usage:
from pylab import figure, plot, ion, linspace, arange, sin, pi
def draw_fig():
# can be arbitrarily complex; just to draw a figure
#figure() # don't call!
plot(t, x)
#show() # don't call!
N = 1e3
figure() # call here instead!
ion() # enable interactivity
t = linspace(0, 2*pi, num=N)
for i in arange(100):
x = sin(2 * pi * i**2 * t / 100.0)
drawnow(draw_fig)
This package works with any matplotlib figure and provides options to wait after each figure update or drop into the debugger.
you could try:
<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>
<div>
<div ng-view=""></div>
</div>
I had this same issue I solved it in the following steps:
docker-machine restart
Quit terminal (or iTerm2, etc, etc) and restart
eval $(docker-machine env default)
I also answered it here
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
Add display: block;
and overflow: auto;
to .my-table
. This will simply cut off anything past the 280px
limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough
which are wider than 280px
.
Is this possible using HttpWebRequest and HttpWebResponse?
You could have your web server simply catch and write the exception text into the body of the response, then set status code to 500. Now the client would throw an exception when it encounters a 500 error but you could read the response stream and fetch the message of the exception.
So you could catch a WebException which is what will be thrown if a non 200 status code is returned from the server and read its body:
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (Exception ex)
{
// Something more serious happened
// like for example you don't have network access
// we cannot talk about a server exception here as
// the server probably was never reached
}
This worked for me on Swift 5
let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)
This version is packed in a function that accepts a custom delimiter, filter, and returns a flat dictionary:
function flatten(source, delimiter, filter) {
var result = {}
;(function flat(obj, stack) {
Object.keys(obj).forEach(function(k) {
var s = stack.concat([k])
var v = obj[k]
if (filter && filter(k, v)) return
if (typeof v === 'object') flat(v, s)
else result[s.join(delimiter)] = v
})
})(source, [])
return result
}
var obj = {
a: 1,
b: {
c: 2
}
}
flatten(obj)
// <- Object {a: 1, b.c: 2}
flatten(obj, '/')
// <- Object {a: 1, b/c: 2}
flatten(obj, '/', function(k, v) { return k.startsWith('a') })
// <- Object {b/c: 2}
Oh My God! I think this could be more shorter than ever, let see this:
function isObject(obj)_x000D_
{_x000D_
return obj != null && obj.constructor.name === "Object"_x000D_
}_x000D_
_x000D_
console.log(isObject({})) // returns true_x000D_
console.log(isObject([])) // returns false_x000D_
console.log(isObject(null)) // returns false
_x000D_
typeof JavaScript objects (including null
) returns "object"
console.log(typeof null, typeof [], typeof {})
_x000D_
Checking on their constructor
property returns function with their names.
console.log(({}).constructor) // returns a function with name "Object"_x000D_
console.log(([]).constructor) // returns a function with name "Array"_x000D_
console.log((null).constructor) //throws an error because null does not actually have a property
_x000D_
Function.name
returns a readonly name of a function or "anonymous"
for closures.
console.log(({}).constructor.name) // returns "Object"_x000D_
console.log(([]).constructor.name) // returns "Array"_x000D_
console.log((null).constructor.name) //throws an error because null does not actually have a property
_x000D_
Note: As of 2018, Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility
You can use assertThrows()
. My example is taken from the docs http://junit.org/junit5/docs/current/user-guide/
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
....
@Test
void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
Note: You should not use the com.android.support and com.google.android.material dependencies in your app at the same time.
Add Material Components for Android in your build.gradle(app) file
dependencies {
// ...
implementation 'com.google.android.material:material:1.0.0-beta01'
// ...
}
If your app currently depends on the original Design Support Library, you can make use of the Refactor to AndroidX… option provided by Android Studio. Doing so will update your app’s dependencies and code to use the newly packaged androidx and com.google.android.material libraries.
If you don’t want to switch over to the new androidx and com.google.android.material packages yet, you can use Material Components via the com.android.support:design:28.0.0-alpha3 dependency.
Ok, I know there is an accepted answer but… for more special cases you also could use this one:
array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);
Or in a more un-complex way:
function printItem($n){
echo $n['filename'];
echo $n['filepath'];
}
array_map('printItem', $array);
This will allow you to manipulate the data in an easier way.
Just like any other text file, .js
files have specific encodings they are saved in. This message means you are saving the .js
file with a non-UTF8 encoding (probably ASCII), and so your non-ASCII characters never even make it to the disk.
That is, the problem is not at the level of HTML or <meta charset>
or Content-Type
headers, but instead a very basic issue of how your text file is saved to disk.
To fix this, you'll need to change the encoding that Dreamweaver saves files in. It looks like this page outlines how to do so; choose UTF8 without saving a Byte Order Mark (BOM). This Super User answer (to a somewhat-related question) even includes screenshots.
Adding to Rob?'s answer: in case you want to print rather large numbers, using thousand separators can be a great help (note the comma).
>>> f'{a*1000:,.2f}'
'10,123.40'
For Fish terminal users on Mac (I believe it's available on Linux as well), this should work:
set -Ux JAVA_8 (/usr/libexec/java_home --version 1.8)
set -Ux JAVA_12 (/usr/libexec/java_home --version 12)
set -Ux JAVA_HOME $JAVA_8 //or whichever version you want as default