I'm using UAParser https://github.com/faisalman/ua-parser-js
var a = new UAParser();
var name = a.getResult().browser.name;
var version = a.getResult().browser.version;
A responsive table is simply a 100% width table.
You can just set up your table with this CSS:
.table { width: 100%; }
You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child
, etc):
@media screen and (max-width: 320px) {
.hide { display: none; }
}
HTML
<td class="hide">Not important</td>
If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:
Here is media queries for common device breakpoints.
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
I was able to resolve this issue using this
@media (hover:none), (hover:on-demand) {
Your class or ID{
attributes
}
}
You should be able to use those breakpoints if you use http://lesscss.org/ to build your CSS.
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) { }
/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) { }
/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) { }
From https://getbootstrap.com/docs/3.4/css/#grid-media-queries
In fact @screen-sm-min
is a variable than is replaced by the value specified in _variable
when building with Less. If you don't use Less, you can replace this variable by the value:
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) { }
/* Medium devices (desktops, 992px and up) */
@media (min-width: 992px) { }
/* Large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) { }
Bootstrap 3 officially supports Sass: https://github.com/twbs/bootstrap-sass. If you are using Sass (and you should) the syntax is a bit different.
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
/* Small devices (tablets, 768px and up) */
@media (min-width: $screen-sm-min) { }
/* Medium devices (desktops, 992px and up) */
@media (min-width: $screen-md-min) { }
/* Large devices (large desktops, 1200px and up) */
@media (min-width: $screen-lg-min) { }
Yes, this can be done via javascript feature detection ( or browser detection , e.g. Modernizr ) . Then, use yepnope.js to load required resources ( JS and/or CSS )
If you are making a cross-platform app (eg. using phonegap/cordova) then,
Don't use device-width or device-height. Rather use width or height in CSS media queries because Android device will give problems in device-width or device-height. For iOS it works fine. Only android devices doesn't support device-width/device-height.
Inline styles cannot currently contain anything other than declarations (property: value
pairs).
You can use style
elements with appropriate media
attributes in head
section of your document.
Short answer No. CSS is not specific to brands.
Below are the articles to implement for iOS using media only.
https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
http://stephen.io/mediaqueries/
Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance
for me, the query that did the job was:
only screen and (device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)
if(window.matchMedia('(max-width: 768px)').matches)
{
$(".article-item").text(function(i, text) {
if (text.length >= 150) {
text = text.substring(0, 250);
var lastIndex = text.lastIndexOf(" ");
text = text.substring(0, lastIndex) + '...';
}
$(this).text(text);
});
}
I've been using:
@media only screen and (min-width: 768px) {
/* tablets and desktop */
}
@media only screen and (max-width: 767px) {
/* phones */
}
@media only screen and (max-width: 767px) and (orientation: portrait) {
/* portrait phones */
}
It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).
That's Media Queries. It allows you to apply part of CSS rules only to the specific devices on specific configuration.
Try this, it worked for me on Google Chrome:
<style media="print" type="text/css">
.page {
background-color: white !important;
}
</style>
Bootstrap primarily uses the following media query ranges—or breakpoints—in our source Sass files for our layout, grid system, and components.
Extra small devices (portrait phones, less than 576px)
No media query for xs
since this is the default in Bootstrap
Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }
Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }
Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }
Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
Since we write our source CSS in Sass, all our media queries are available via Sass mixins:
No media query necessary for xs breakpoint as it's effectively @media (min-width: 0) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }
For understand it deeply please go through below link
The correct value for the content
attribute should include initial-scale
instead:
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
^^^^^^^^^^^^^^^
_x000D_
just wanted to leave my .scss
example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.
Im looking forward for your feedback!
// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;
// Prepare your "function"
@mixin in-between {
@media (min-width:$widthSmall) and (max-width:$widthMedium) {
@content;
}
}
// Apply your "function"
main {
@include in-between {
//Do something between two media queries
padding-bottom: 20px;
}
}
In Javascript it is better to use screen.width
and screen.height
. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth
changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.
The values of screen.width
and screen.height
change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width
is greater than 1280px you're dealing with a PC or laptop.
You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).
The answer by @hybrid is quite informative, except it doesn't explain the purpose as mentioned by @ashitaka "What if you use the Mobile First approach? So, we have the mobile CSS first and then use min-width to target larger sites. We shouldn't use the only keyword in that context, right? "
Want to add in here that the purpose is simply to prevent non supporting browsers to use that Other device style as if it starts from "screen" without it will take it for a screen whereas if it starts from "only" style will be ignored.
Answering to ashitaka consider this example
<link rel="stylesheet" type="text/css"
href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css"
href="desktop.css" media="screen and (min-width: 481px)" />
If we don't use "only" it will still work as desktop-style will also be used striking android styles but with unnecessary overhead. In this case, IF a browser is non-supporting it will fallback to the second Style-sheet ignoring the first.
Here's how I did it:
@media (pointer:none), (pointer:coarse) {
}
The best breakpoints recommended by Twitter Bootstrap
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) {
}
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {
}
/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {
}
/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {
}
/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {
}
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):
.box {
background: url( 'img/box-bg.png' ) no-repeat top left;
width: 200px;
height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
only screen and ( min--moz-device-pixel-ratio: 1.3 ),
only screen and ( -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
only screen and ( min-device-pixel-ratio: 1.3 ),
only screen and ( min-resolution: 124.8dpi ),
only screen and ( min-resolution: 1.3dppx ) {
.box {
background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
}
}
As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.
As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio
of 1.325
. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.
Too late but may this save you from headache! All of these is because we have to detect the target browser is a mobile!
Is this a mobile then combine it with min/max-(width/height)'s
So Just this seems works:
@media (hover: none) {
/* ... */
}
If the primary input mechanism system of the device cannot hover over elements with ease or they can but not easily (for example a long touch is performed to emulate the hover) or there is no primary input mechanism at all, we use none! There are many cases that you can read from bellow links.
Described as well Also for browser Support See this from MDN
Media queries are not supported at all in IE8 and below.
To add support for IE8, you could use one of several JS solutions. For example, Respond can be added to add media query support for IE8 only with the following code :
<!--[if lt IE 9]>
<script
src="respond.min.js">
</script>
<![endif]-->
CSS Mediaqueries is another library that does the same thing. The code for adding that library to your HTML would be identical :
<!--[if lt IE 9]>
<script
src="css3-mediaqueries.js">
</script>
<![endif]-->
If you don't like a JS based solution, you should also consider adding an IE<9 only stylesheet where you adjust your styling specific to IE<9. For that, you should add the following HTML to your code:
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ielt9.css"/>
<![endif]-->
Note :
Technically it's one more alternative: using CSS hacks to target IE<9. It has the same impact as an IE<9 only stylesheet, but you don't need a seperate stylesheet for that. I do not recommend this option, though, as they produce invalid CSS code (which is but one of several reasons why the use of CSS hacks is generally frowned upon today).
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
The @media query specifically for 'phones' is..
@media (max-width: 480px) { ... }
But, you may want to remove the padding/margin for any smaller screen sizes. By default, Bootstrap adjusts margins/padding to the body, container and navbars at 978px.
Here are some queries that have worked (in most cases) for me:
@media (max-width: 978px) {
.container {
padding:0;
margin:0;
}
body {
padding:0;
}
.navbar-fixed-top, .navbar-fixed-bottom, .navbar-static-top {
margin-left: 0;
margin-right: 0;
margin-bottom:0;
}
}
Update for Bootstrap 4
Use the new responsive spacing utils which let you set padding/margins for different screen widths (breakpoints): https://stackoverflow.com/a/43208888/171456
You have to target screen size using media query for different screen size.
for iphone:
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio : 2)
{ }
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio : 2)
{ }
and for desktop version:
@media only screen (max-width: 1080){
}
Here are some of the following media queries for iPhones. Here is the ref link https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
/* iphone 3 */
@media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 1) { }
/* iphone 4 */
@media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 2) { }
/* iphone 5 */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (-webkit-device-pixel-ratio: 2) { }
/* iphone 6, 6s, 7, 8 */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (-webkit-device-pixel-ratio: 2) { }
/* iphone 6+, 6s+, 7+, 8+ */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (-webkit-device-pixel-ratio: 3) { }
/* iphone X , XS, 11 Pro, 12 Mini */
@media only screen and (min-device-width: 375px) and (max-device-height: 812px) and (-webkit-device-pixel-ratio: 3) { }
/* iphone 12, 12 Pro */
@media only screen and (min-device-width: 390px) and (max-device-height: 844px) and (-webkit-device-pixel-ratio: 3) { }
/* iphone XR, 11 */
@media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 2) { }
/* iphone XS Max, 11 Pro Max */
@media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 3) { }
/* iphone 12 Pro Max */
@media only screen and (min-device-width : 428px) and (max-device-height : 926px) and (-webkit-device-pixel-ratio : 3) { }
yes, using and
, like:
@media screen and (max-width: 800px),
screen and (max-height: 600px) {
...
}
<html>
<head>
<title>orientation and device detection in css3</title>
<link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:portrait)" href="iphone-portrait.css" />
<link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:landscape)" href="iphone-landscape.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
<link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 1184px) and (orientation:portrait)" href="htcdesire-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 390px) and (orientation:landscape)" href="htcdesire-landscape.css" />
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="desktop.css" />
</head>
<body>
<div id="iphonelandscape">iphone landscape</div>
<div id="iphoneportrait">iphone portrait</div>
<div id="ipadlandscape">ipad landscape</div>
<div id="ipadportrait">ipad portrait</div>
<div id="htcdesirelandscape">htc desire landscape</div>
<div id="htcdesireportrait">htc desire portrait</div>
<div id="desktop">desktop</div>
<script type="text/javascript">
function res() { document.write(screen.width + ', ' + screen.height); }
res();
</script>
</body>
</html>
It can also be as simple as this.
@media (orientation: landscape) {
}
Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.
I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.
<div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
<div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>
function setMobDeskCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value + "; path=/";
window.location.reload();
}
$(function() {
$(".make_desktop").click(function() {
setMobDeskCookie('deskmob', 1, 3650);
});
$(".make_responsive").click(function() {
setMobDeskCookie('deskmob', 0, 3650);
});
});`enter code here`
i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me
and i also created non-responsive.css that forces the grid to maintain the large screen version
in case u select mobile i would load / echo
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />
in case you select desktop i would load /echo
<meta name="viewport" content="width=1024">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
<!-- Main CSS -->
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />
the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files
please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me
I was also thinking of media queries, but then I found this:
Just create a wrapper <div>
with a percentage value for padding-bottom
, like this:
div {_x000D_
width: 100%;_x000D_
padding-bottom: 75%;_x000D_
background:gold; /** <-- For the demo **/_x000D_
}
_x000D_
<div></div>
_x000D_
It will result in a <div>
with height equal to 75% of the width of its container (a 4:3 aspect ratio).
This technique can also be coupled with media queries and a bit of ad hoc knowledge about page layout for even more finer-grained control.
It's enough for my needs. Which might be enough for your needs too.
For me I had indicated max-height
instead of max-width
.
If that is you, go change it !
@media screen and (max-width: 350px) { // Not max-height
.letter{
font-size:20px;
}
}
I think using window.devicePixelRatio
is more elegant than the window.matchMedia
solution:
if (window.innerWidth*window.devicePixelRatio <= 960
&& window.innerHeight*window.devicePixelRatio <= 640) {
...
}
You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options
//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>
<script>
new Chart(somechart, {
options: {
responsive: true,
maintainAspectRatio: false
/*, your other options*/
}
});
</script>
301 redirects are cached indefinitely (at least by some browsers).
This means, if you set up a 301, visit that page, you not only get redirected, but that redirection gets cached.
When you visit that page again, your Browser* doesn't even bother to request that URL, it just goes to the cached redirection target.
The only way to undo a 301 for a visitor with that redirection in Cache, is re-redirecting back to the original URL**. In that case, the Browser will notice the loop, and finally really request the entered URL.
Obviously, that's not an option if you decided to 301 to facebook or any other resource you're not fully under control.
Unfortunately, many Hosting Providers offer a feature in their Admin Interface simply called "Redirection", which does a 301 redirect. If you're using this to temporarily redirect your domain to facebook as a coming soon page, you're basically screwed.
*at least Chrome and Firefox, according to How long do browsers cache HTTP 301s?. Just tried it with Chrome 45. Edit: Safari 7.0.6 on Mac also caches, a browser restart didn't help (Link says that on Safari 5 on Windows it does help.)
**I tried javascript window.location = ''
, because it would be the solution which could be applied in most cases - it doesn't work. It results in an undetected infinite Loop. However, php header('Location: new.url')
does break the loop
Bottom Line: only use 301s if you're absolutely sure you're never going to use that URL again. Usually never on the root dir (example.com/)
Adding cacerts
did not work for me.
After enabling log with flag -Djavax.net.debug=all
, then came to know java reading from jssecacerts
.
Import to jssecacerts
worked finally.
It seems that in lollipop and up (or maybe just a different WebView Version) that calling cprcrack's
onHideCustomView()
method does not work. It works if it is called from the exit fullscreen button but when you specifically call the method it will only exit fullscreen but the webView
stays blank. A way around it is to simply add these lines of code to onHideCustomView()
:
String js = "javascript:";
js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";
js += "_ytrp_html5_video.webkitExitFullscreen();";
webView.loadUrl(js);
This will notify the webView that fullscreen has exited.
If pattern match, copy next line into the pattern buffer, delete a return, then quit -- side effect is to print.
sed '/pattern/ { N; s/.*\n//; q }; d'
ignoreParent() is a pure JavaScript solution.
It works as an intermediary layer that compares the coordinates of the mouse click with the coordinates of the child element/s. Two simple implementation steps:
1. Put the ignoreParent() code on your page.
2. Instead of the parent's original onclick="parentEvent();", write:
onclick="ignoreParent(['parentEvent()', 'child-ID']);"
You may pass IDs of any number of child elements to the function, and exclude others.
If you clicked on one of the child elements, the parent event doesn't fire. If you clicked on parent, but not on any of the child elements [provided as arguments], the parent event is fired.
This error also show up when file's owner of MainWindow.xib is set incorrectly.
File's owner is UIApplication
->inserted object of app delegate class with window outlet connected to window
what about
chunk_split($str,20);
Entry in the PHP Manual
If you're running PHP 5.3+ this will do the trick, place it at the topmost of your page:
if (get_magic_quotes_gpc() === 1)
{
$_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
$_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
$_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
$_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}
Handles keys, values and multi-dimensional arrays.
You'll have to pass your arguments as reference types.
#First create the variables (note you have to set them to something)
$global:var1 = $null
$global:var2 = $null
$global:var3 = $null
#The type of the reference argument should be of type [REF]
function foo ($a, $b, [REF]$c)
{
# add $a and $b and set the requested global variable to equal to it
# Note how you modify the value.
$c.Value = $a + $b
}
#You can then call it like this:
foo 1 2 [REF]$global:var3
In perl 5.10, there's the close-to-magic ~~ operator:
sub invite_in {
my $vampires = [ qw(Angel Darla Spike Drusilla) ];
return ($_[0] ~~ $vampires) ? 0 : 1 ;
}
See here: http://dev.perl.org/perl5/news/2007/perl-5.10.0.html
If the response code isn't 200 or 2xx, use getErrorStream()
instead of getInputStream().
Add &autoplay=1 to your syntax, like this
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&autoplay=1" frameborder="0" allowfullscreen></iframe>
When you work with web page or javascript file you want it to be reloaded every time you change it. You can change settings in IE 8 so the browser will never cache.
Follow this simple steps.
If you're platform is Windows, I wouldn't actually recommend Python. Instead, look into Autohotkey. Trust me, I love Python, but in this circumstance a macro program is the ideal tool for the job. Autohotkey's scripting is only decent (in my opinion), but the ease of simulating input will save you countless hours. Autohotkey scripts can be "compiled" as well so you don't need the interpreter to run the script.
Also, if this is for something on the Web, I recommend iMacros. It's a firefox plugin and therefore has a much better integration with websites. For example, you can say "write 1000 'a's in this form" instead of "simulate a mouseclick at (319,400) and then press 'a' 1000 times".
For Linux, I unfortunately have not been able to find a good way to easily create keyboard/mouse macros.
If expr is greater than or equal to min and expr is less than or equal to max,
BETWEEN
returns 1, otherwise it returns 0.
The important part here is EQUAL to max., which 1st of July is.
You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add
.
Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d
.
Prevent browser cache is not a good idea depending on the case. Looking for a solution I found solutions like this:
<link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">
the problem here is that if the file is overwritten during an update on the server, which is my scenario, the cache is ignored because timestamp is modified even the content of the file is the same.
I use this solution to force browser to download assets only if its content is modified:
<link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">
The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.
In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.
PushKit reference from Apple:
The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.
To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.
You could also use:
List<int> codes = new List<int>();
codes.add(1);
codes.add(2);
var foo = from codeData in channel.AsQueryable<CodeData>()
where codes.Any(code => codeData.CodeID.Equals(code))
select codeData;
Paul Ruane is correct, I have just tried myself building the project. I just made a whole SLN to test if it worked.
I made this in VC# VS2008
<< ( Just helping other people that read this aswell with () comments )
Step1:
Make solution called DoubleProject
Step2:
Make Project in solution named DoubleProjectTwo (to do this select the solution file, right click --> Add --> New Project)
I now have two project in the same solution
Step3:
As Paul Ruane stated. go to references in the solution explorer (if closed it's in the view tab of the compiler). DoubleProjectTwo is the one needing functions/methods of DoubleProject so in DoubleProjectTwo right mouse reference there --> Add --> Projects --> DoubleProject.
Step4:
Include the directive for the namespace:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DoubleProject; <------------------------------------------
namespace DoubleProjectTwo
{
class ClassB
{
public string textB = "I am in Class B Project Two";
ClassA classA = new ClassA();
public void read()
{
textB = classA.read();
}
}
}
Step5:
Make something show me proof of results:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DoubleProject
{
public class ClassA //<---------- PUBLIC class
{
private const string textA = "I am in Class A Project One";
public string read()
{
return textA;
}
}
}
The main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DoubleProjectTwo; //<----- to use ClassB in the main
namespace DoubleProject
{
class Program
{
static void Main(string[] args)
{
ClassB foo = new ClassB();
Console.WriteLine(foo.textB);
Console.ReadLine();
}
}
}
That SHOULD do the trick
Hope this helps
EDIT::: whoops forgot the method call to actually change the string , don't do the same :)
I believe you need to put the libeay32.dll and ssleay32.dll files in the systems folder
Try this :
<style type="text/css">
.myTableStyle
{
position:absolute;
top:50%;
left:50%;
/*Alternatively you could use: */
/*
position: fixed;
bottom: 50%;
right: 50%;
*/
}
</style>
A simple way to plot sine wave in python using matplotlib.
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,3*np.pi,0.1)
y=np.sin(x)
plt.plot(x,y)
plt.title("SINE WAVE")
plt.show()
The standalone
declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.
As an example, consider the humble <img>
tag. If you look at the XHTML 1.0 DTD, you see a markup declaration telling the parser that <img>
tags must be EMPTY and possess src
and alt
attributes. When a browser is going through an XHTML 1.0 document and finds an <img>
tag, it should notice that the DTD requires src
and alt
attributes and add them if they are not present. It will also self-close the <img>
tag since it is supposed to be EMPTY. This is what the XML specification means by "markup declarations can affect the content of the document." You can then use the standalone
declaration to tell the parser to ignore these rules.
Whether or not your parser actually does this is another question, but a standards-compliant validating parser (like a browser) should.
Note that if you do not specify a DTD, then the standalone declaration "has no meaning," so there's no reason to use it unless you also specify a DTD.
Annotate your Entity class with the code below.
In Java:
@PrimaryKey(autoGenerate = true)
private int id;
In Kotlin:
@PrimaryKey(autoGenerate = true)
var id: Int
Room will then auto-generate and auto-increment the id field.
Exported variables such as $HOME
and $PATH
are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.
$ env | grep '^variable='
$ # No environment variable called variable
$ variable=Hello # Create local (non-exported) variable with value
$ env | grep '^variable='
$ # Still no environment variable called variable
$ export variable # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$
For more information, see the entry for the export
builtin in the GNU Bash manual, and also the sections on command execution environment and environment.
Note that non-exported variables will be available to subshells run via ( ... )
and similar notations because those subshells are direct clones of the main shell:
$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$
The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.
Some information about subshells can be found under command grouping and command execution environment in the Bash manual.
Try the following
download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.
Unzip the file and Run intelhaxm-android.exe.
Run silent_install.bat.
In my computer Win10 x64 - VS2015 it worked
The problem with joining subsequent sample points together with disjoint "curveTo" type functions, is that where the curves meet is not smooth. This is because the two curves share an end point but are influenced by completely disjoint control points. One solution is to "curve to" the midpoints between the next 2 subsequent sample points. Joining the curves using these new interpolated points gives a smooth transition at the end points (what is an end point for one iteration becomes a control point for the next iteration.) In other words the two disjointed curves have much more in common now.
This solution was extracted out of the book "Foundation ActionScript 3.0 Animation: Making things move". p.95 - rendering techniques: creating multiple curves.
Note: this solution does not actually draw through each of the points, which was the title of my question (rather it approximates the curve through the sample points but never goes through the sample points), but for my purposes (a drawing application), it's good enough for me and visually you can't tell the difference. There is a solution to go through all the sample points, but it is much more complicated (see http://www.cartogrammar.com/blog/actionscript-curves-update/)
Here is the the drawing code for the approximation method:
// move to the first point
ctx.moveTo(points[0].x, points[0].y);
for (i = 1; i < points.length - 2; i ++)
{
var xc = (points[i].x + points[i + 1].x) / 2;
var yc = (points[i].y + points[i + 1].y) / 2;
ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc);
}
// curve through the last two points
ctx.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x,points[i+1].y);
SELECT
AGE('2012-03-05', '2010-04-01'),
DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;
This will give you full years, month, days ... between two dates:
age | years | months | days
-----------------------+-------+--------+------
1 year 11 mons 4 days | 1 | 11 | 4
More detailed datediff information.
This is useful if you want to do nothing if it does exist but create it if it doesn't exist.
def get_var
@var ||= SomeClass.new()
end
This only creates the new instance once. After that it just keeps returning the var.
By getting the getLastKnownLocation
you do not actually initiate a fix yourself.
Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.
According to the docs getLastKnownLocation:
Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider.
Here is a quick snippet:
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
public class UtilLocation {
public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location utilLocation = null;
List<String> providers = manager.getProviders(enabledProvidersOnly);
for(String provider : providers){
utilLocation = manager.getLastKnownLocation(provider);
if(utilLocation != null) return utilLocation;
}
return null;
}
}
You also have to add new permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
max
function is used to get the maximum out of an iterable
.
The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
So, the key=func
basically allows us to pass an optional argument key
to the function on whose basis is the given iterator/arguments are sorted & the maximum is returned.
lambda
is a python keyword that acts as a pseudo function. So, when you pass player
object to it, it will return player.totalScore
. Thus, the iterable passed over to function max
will sort according to the key
totalScore of the player
objects given to it & will return the player
who has maximum totalScore
.
If no key
argument is provided, the maximum is returned according to default Python orderings.
Examples -
max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7
people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')
Try this one-shot solution that should figure out where ImageMagick is, if you have access to it...
This found all versions on my Godaddy hosting.
Upload this file to your server and call it ImageMagick.php
or something then run it. You will get all the info you need... hopefully...
Good luck.
<?
/*
// This file will run a test on your server to determine the location and versions of ImageMagick.
//It will look in the most commonly found locations. The last two are where most popular hosts (including "Godaddy") install ImageMagick.
//
// Upload this script to your server and run it for a breakdown of where ImageMagick is.
//
*/
echo '<h2>Test for versions and locations of ImageMagick</h2>';
echo '<b>Path: </b> convert<br>';
function alist ($array) { //This function prints a text array as an html list.
$alist = "<ul>";
for ($i = 0; $i < sizeof($array); $i++) {
$alist .= "<li>$array[$i]";
}
$alist .= "</ul>";
return $alist;
}
exec("convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
echo '<br>';
echo '<b>This should test for ImageMagick version 5.x</b><br>';
echo '<b>Path: </b> /usr/bin/convert<br>';
exec("/usr/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
echo '<br>';
echo '<b>This should test for ImageMagick version 6.x</b><br>';
echo '<b>Path: </b> /usr/local/bin/convert<br>';
exec("/usr/local/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version";
?>
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
To answer your questions in order:
1) There is no specific name for this. It's simply multiple elements with the same name (and in this case type as well). Name isn't unique, which is why id was invented (it's supposed to be unique).
2)
function getElementsByTagAndName(tag, name) { //you could pass in the starting element which would make this faster var elem = document.getElementsByTagName(tag); var arr = new Array(); var i = 0; var iarr = 0; var att; for(; i < elem.length; i++) { att = elem[i].getAttribute("name"); if(att == name) { arr[iarr] = elem[i]; iarr++; } } return arr; }
tee is perfect for this, but this will also do the job
ls -lr / > output | cat output
CharField
has max_length of 255
characters while TextField
can hold more than 255
characters. Use TextField
when you have a large string as input. It is good to know that when the max_length
parameter is passed into a TextField
it passes the length validation to the TextArea
widget.
You mean while the mysql environment?
create database testdb;
Or directly from command line:
mysql -u root -e "create database testdb";
Nobody mentioned one crucial difference, ironically answered on a question closed as a duplicated of this.
IEnumerable is read-only and List is not.
Drop Table/Migration
run:- $ rails generate migration DropTablename
exp:- $ rails generate migration DropProducts
I had the same issue with Python3.
My code was writing into io.BytesIO()
.
Replacing with io.StringIO()
solved.
For C++, you could do:
export CXXFLAGS=-m32
This works with cmake.
just like pure js do preventdefault : in class you should like this create a handler method :
handler(event) {
event.preventDefault();
console.log(event);
}
A combination of "git show --stat
" (thanks Ryan) and a couple of sed commands should trim the data down for you:
git show --stat <SHA1> | sed -n "/ [\w]\*|/p" | sed "s/|.\*$//"
That will produce just the list of modified files.
Use C# Dictionary datastructure it good for you...
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
You can retrieve data from Ditionary in a simple way..
foreach (KeyValuePair<string, int> pair in dict)
{
MessageBox.Show(pair.Key.ToString ()+ " - " + pair.Value.ToString () );
}
For more example using C# Dictionary... C# Dictionary
Navi.
you can go to Tools > Kotlin > Show kotlin bytecode
The representation of pointers is irrelevant to comparing them, since all comparisons in C take place as values not representations. The only way to compare the representation would be something hideous like:
static const char ptr_rep[sizeof ptr] = { 0 };
if (!memcmp(&ptr, ptr_rep, sizeof ptr)) ...
If you want to fix the issue for date ranges that cross daylight savings time boundary (e.g. one date in summer time and the other one in winter time), you can use this to get the difference in days:
public static long calculateDifferenceInDays(Date start, Date end, Locale locale) {
Calendar cal = Calendar.getInstance(locale);
cal.setTime(start);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long startTime = cal.getTimeInMillis();
cal.setTime(end);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long endTime = cal.getTimeInMillis();
// calculate the offset if one of the dates is in summer time and the other one in winter time
TimeZone timezone = cal.getTimeZone();
int offsetStart = timezone.getOffset(startTime);
int offsetEnd = timezone.getOffset(endTime);
int offset = offsetEnd - offsetStart;
return TimeUnit.MILLISECONDS.toDays(endTime - startTime + offset);
}
One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:
$content = ${C:file.txt}
This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:
${D:\path\to\file.txt} = $content
Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:
${C:file.txt} = ${C:file.txt} | select -skip 1
I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.
One final note on using this: you must use a drive designation, i.e. ${drive:filespec}
as I have done in all the examples above. Without the drive (e.g. ${file.txt}
) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.
.switch {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 90px;_x000D_
height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #ca2222;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
position: absolute;_x000D_
content: "";_x000D_
height: 26px;_x000D_
width: 26px;_x000D_
left: 4px;_x000D_
bottom: 4px;_x000D_
background-color: white;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
-webkit-transform: translateX(55px);_x000D_
-ms-transform: translateX(55px);_x000D_
transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
color: white;_x000D_
position: absolute;_x000D_
transform: translate(-50%,-50%);_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 10px;_x000D_
font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
Facelets is a XML based view technology. The &
is a special character in XML representing the start of an entity like &
which ends with the ;
character. You'd need to either escape it, which is ugly:
rendered="#{beanA.prompt == true && beanB.currentBase != null}"
or to use the and
keyword instead, which is preferred as to readability and maintainability:
rendered="#{beanA.prompt == true and beanB.currentBase != null}"
Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true
:
rendered="#{beanA.prompt and beanB.currentBase != null}"
One important function of the main
key is that it provides the path for your entry point. This is very helpful when working with nodemon
. If you work with nodemon
and you define the main
key in your package.json
as let say "main": "./src/server/app.js"
, then you can simply crank up the server with typing nodemon
in the CLI with root as pwd instead of nodemon ./src/server/app.js
.
Default html color code like this:
Red #FF0000 rgb(255, 0, 0)
Maroon #800000 rgb(128, 0, 0)
Yellow #FFFF00 rgb(255, 255, 0)
Olive #808000 rgb(128, 128, 0)
Blue #0000FF rgb(0, 0, 255)
Navy #000080 rgb(0, 0, 128)
Fuchsia #FF00FF rgb(255, 0, 255)
Purple #800080 rgb(128, 0, 128)
if you use T-SQL(MSSQL); you should try this script:
ALTER TABLE [Employee] ALTER COLUMN [Salary] NUMERIC(22,5)
if you use MySQL; you should try this script:
ALTER TABLE [Employee] MODIFY COLUMN [Salary] NUMERIC(22,5)
if you use Oracle; you should try this script:
ALTER TABLE [Employee] MODIFY [Salary] NUMERIC(22,5)
In my case this problem started after eclipse updated the plugin with the v4.0 API release. I fixed it by going to the main preferences for Eclipse and under Android->Build uncheck 'Skip packaging and dexing until export or launch'
Note: if you eclipse gives you the Unknown Command 'crunch' error then follow this post
Linux minimal runnable examples with disassembly analysis
Since this is an implementation detail not specified by standards, let's just have a look at what the compiler is doing on a particular implementation.
In this answer, I will either link to specific answers that do the analysis, or provide the analysis directly here, and summarize all results here.
All of those are in various Ubuntu / GCC versions, and the outcomes are likely pretty stable across versions, but if we find any variations let's specify more precise versions.
Local variable inside a function
Be it main
or any other function:
void f(void) {
int my_local_var;
}
As shown at: What does <value optimized out> mean in gdb?
-O0
: stack-O3
: registers if they don't spill, stack otherwiseFor motivation on why the stack exists see: What is the function of the push / pop instructions used on registers in x86 assembly?
Global variables and static
function variables
/* BSS */
int my_global_implicit;
int my_global_implicit_explicit_0 = 0;
/* DATA */
int my_global_implicit_explicit_1 = 1;
void f(void) {
/* BSS */
static int my_static_local_var_implicit;
static int my_static_local_var_explicit_0 = 0;
/* DATA */
static int my_static_local_var_explicit_1 = 1;
}
0
or not initialized (and therefore implicitly initialized to 0
): .bss
section, see also: Why is the .bss segment required?.data
sectionchar *
and char c[]
As shown at: Where are static variables stored in C and C++?
void f(void) {
/* RODATA / TEXT */
char *a = "abc";
/* Stack. */
char b[] = "abc";
char c[] = {'a', 'b', 'c', '\0'};
}
TODO will very large string literals also be put on the stack? Or .data
? Or does compilation fail?
Function arguments
void f(int i, int j);
Must go through the relevant calling convention, e.g.: https://en.wikipedia.org/wiki/X86_calling_conventions for X86, which specifies either specific registers or stack locations for each variable.
Then as shown at What does <value optimized out> mean in gdb?, -O0
then slurps everything into the stack, while -O3
tries to use registers as much as possible.
If the function gets inlined however, they are treated just like regular locals.
const
I believe that it makes no difference because you can typecast it away.
Conversely, if the compiler is able to determine that some data is never written to, it could in theory place it in .rodata
even if not const.
TODO analysis.
Pointers
They are variables (that contain addresses, which are numbers), so same as all the rest :-)
malloc
The question does not make much sense for malloc
, since malloc
is a function, and in:
int *i = malloc(sizeof(int));
*i
is a variable that contains an address, so it falls on the above case.
As for how malloc works internally, when you call it the Linux kernel marks certain addresses as writable on its internal data structures, and when they are touched by the program initially, a fault happens and the kernel enables the page tables, which lets the access happen without segfaul: How does x86 paging work?
Note however that this is basically exactly what the exec
syscall does under the hood when you try to run an executable: it marks pages it wants to load to, and writes the program there, see also: How does kernel get an executable binary file running under linux? Except that exec
has some extra limitations on where to load to (e.g. is the code is not relocatable).
The exact syscall used for malloc
is mmap
in modern 2020 implementations, and in the past brk
was used: Does malloc() use brk() or mmap()?
Dynamic libraries
Basically get mmap
ed to memory: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710
envinroment variables and main
's argv
Above initial stack: https://unix.stackexchange.com/questions/75939/where-is-the-environment-string-actual-stored TODO why not in .data?
There isn't any need to write this much. Just put your desired field separator with the -F
option in the AWK command and the column number you want to print segregated as per your mentioned field separator.
echo "1: " | awk -F: '{print $1}'
1
echo "1#2" | awk -F# '{print $1}'
1
For completeness, the issue may be heroku itself. In rare cases like these https://status.heroku.com would show something along the lines of:
Update
The Heroku Dashboard and Elements have been restored. We are still working to restore the other affected services.
The services still affected are:
- Builds
- Review apps
- Pipelines
- Github deploys
- Heroku CI
- Heroku Buttons
I was able to deploy about 40 minutes later after heroku reported:
All affected services have been restored and are now working as expected. We will be monitoring to ensure there are no further issues.
video/mp4
should be used when you have video content in your file. If there is none, but there is audio, you should use audio/mp4
. If no audio and no video is used, for instance if the file contains only a subtitle track or a metadata track, the MIME should be application/mp4
.
Also, as a server, you should try to include the codecs
or profiles
parameters as defined in RFC6381, as this will help clients determine if they can play the file, prior to downloading it.
Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n
and you use \n
.
If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.
try {
//Dangerous code: could throw an error
} catch (Exception e) {
//Cleanup: make sure that this methods variables and such are in the desired state
throw e;
}
This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.
An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.
You can use this to call predefined android colours:
element.setBackgroundColor(android.R.color.red);
If you want to use one of your own custom colours, you can add your custom colour to strings.xml and then use the below to call it.
element.setBackgroundColor(R.color.mycolour);
However if you want to set the colour in your layout.xml you can modify and add the below to any element that accepts it.
android:background="#FFFFFF"
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
First of all, install the prerequisite libraries:
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
Then install rbenv, which is used to install Ruby:
cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL
rbenv install 2.3.1
rbenv global 2.3.1
ruby -v
Then (optional) tell Rubygems to not install local documentation:
echo "gem: --no-ri --no-rdoc" > ~/.gemrc
Credits: https://gorails.com/setup/ubuntu/14.10
Warning!!!
There are issues with Gnome-Shell
. See comment below.
What worked for me is:
LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysql-python
LLVM is a library that is used to construct, optimize and produce intermediate and/or binary machine code.
LLVM can be used as a compiler framework, where you provide the "front end" (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code).
LLVM can also act as a JIT compiler - it has support for x86/x86_64 and PPC/PPC64 assembly generation with fast code optimizations aimed for compilation speed.
Unfortunately disabled since 2013, there was the ability to play with LLVM's machine code generated from C or C++ code at the demo page.
This should work:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
Try the following query:
DECLARE @Temp NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
SET @Temp = '';
SELECT @Temp = @Temp + COLUMN_NAME + ', ' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='Person' AND COLUMN_NAME NOT IN ('Id')
SET @SQL = 'SELECT ' + SUBSTRING(@Temp, 0, LEN(@Temp)) +' FROM [Person]';
EXECUTE SP_EXECUTESQL @SQL;
I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.
Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.
So, for your particular question:
today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))
Works like a charm.
I use this method all the time for doing rolling 30/60/365 day calculations.
You can easily extrapolate this to create units of time for months, years, etc.
To prevent form submit when pressing enter in a textarea
or input
field, check the submit event to find what type of element sent the event.
<button type="submit" form="my-form">Submit</button>
<form id="my-form">
...
</form>
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.type!=="submit") {
e.preventDefault();
}
});
A better solution is if you don't have a submit button and you fire the event with a normal button. It is better because in the first examlple 2 submit events are fired, but in the second example only 1 submit event is fired.
<button type="button" onclick="$('#my-form').submit();">Submit</button>
<form id="my-form">
...
</form>
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.localName!=="button") {
e.preventDefault();
}
});
Just discovered that if the source table for a subform is updated using adodb, it takes a while until the requery can find the updated information.
In my case, I was adding some records with 'dbconn.execute "sql" ' and wondered why the requery command in vba doesn't seem to work. When I was debugging, the requery worked. Added a 2-3 second wait in the code before requery just to test made a difference.
But changing to 'currentdb.execute "sql" ' fixed the problem immediately.
Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)
In rule #2 for permanent redirect there is thing missing:
redirectType="Permanent"
So rule #2 should look like this:
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^page$" />
<action type="Redirect" url="/page.html" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
Edit
For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference
In response to @kneidels question from the comments; To match the url: topic.php?id=39
something like the following could be used:
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^topic.php$" />
<conditions logicalGrouping="MatchAll">
<add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
</conditions>
<action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
This will match topic.php?id=ab
where a
is any number between 0-9
and b is also any number between 0-9
.
It will then redirect to /newpage/xy
where xy
comes from the original url.
I have not tested this but it should work.
The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).
Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:
When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:
Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)
(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)
#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT
From the n3242.pdf file (I expect the final standard text to be similar):
17.6.3.3.2 Global names [global.names]
Certain sets of names and function signatures are always reserved to the implementation:
— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
But also:
17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]
Literal suffix identifiers that do not start with an underscore are reserved for future standardization.
This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...
writing data in tables declared declare @tb
and after joining with other tables, I realized that the response time compared to temporary tables tempdb .. # tb
is much higher.
When I join them with @tb the time is much longer to return the result, unlike #tm, the return is almost instantaneous.
I did tests with a 10,000 rows join and join with 5 other tables
Try this
SELECT top 10 * from record WHERE IsActive = 1 and CONVERT(VARCHAR, register_date, 120) LIKE '2020-01%'
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.
Here are the options in question :
-T seconds
--timeout=seconds
Set the network timeout to seconds seconds. This is equivalent to specifying
--dns-timeout
,--connect-timeout
, and--read-timeout
, all at the same time.
And for those three options :
--dns-timeout=seconds
Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.
--connect-timeout=seconds
Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.
--read-timeout=seconds
Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.
I suppose using something like
wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run
should make sure there is no timeout before longer than the duration of your script.
(Yeah, that's probably the most brutal solution possible ^^ )
update mytable set title=trim(replace(REPLACE(title,CHAR(13),''),CHAR(10),''));
Above is working for fine.
You might want to check out this old thread.
If you can omit AM/PM portion and using SQL Server 2008, you should go with the approach suggested here
To get the rid from nenoseconds in time(SQL Server 2008), do as below :
SELECT CONVERT(TIME(0),GETDATE()) AS HourMinuteSecond
I hope it helps!!
To extract text from a PDF, try this on Linux, BSD, etc. machine or use Cygwin if on Windows:
pdfinfo -layout some_pdf_file.pdf
A plain text file named some_pdf_file.txt
is created. The simpler the PDF file layout, the more straightforward the .txt file output will be.
Hexadecimal characters are frequently present in the .txt file output and will look strange in text editors. These hexadecimal characters usually represent curly single and double quotes, bullet points, hyphens, etc. in the PDF.
To see the context where the hexadecimal characters appear, run this grep command, and keep the original PDF handy to see what character the codes represent in the PDF:
grep -a --color=always "\\\\[0-9][0-9][0-9]" some_pdf_file.txt
This will provide a unique list of the different octal codes in the document:
grep -ao "\\\\[0-9][0-9][0-9]" some_pdf_file.txt|sort|uniq
To convert these hexadecimal characters to ASCII equivalents, a combination of grep, sed, and bc can be used, I'll post the procedure to do that soon.
I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
Since you want a random element, this will also work:
>>> import random
>>> s = set([1,2,3])
>>> random.sample(s, 1)
[2]
The documentation doesn't seem to mention performance of random.sample
. From a really quick empirical test with a huge list and a huge set, it seems to be constant time for a list but not for the set. Also, iteration over a set isn't random; the order is undefined but predictable:
>>> list(set(range(10))) == range(10)
True
If randomness is important and you need a bunch of elements in constant time (large sets), I'd use random.sample
and convert to a list first:
>>> lst = list(s) # once, O(len(s))?
...
>>> e = random.sample(lst, 1)[0] # constant time
An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.
Try Logic Friday 1
It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.
The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.
Your expression simplifies to C
.
I had the same requirement and solved it using these components:
The table component ng-grid is capable of displaying hundreds of rows in a scrollable grid. If you have to deal with thousands of entries you are better off using ng-grid's paginator. The documentation of ng-grid is excellent and contains many examples. Sorting and searching are supported even in combination with pagination.
Here is a screenshot from a current project to give you an impression how it looks like:
[UPDATE July 2017]
After having ng-grid in production for a couple of years, I can still tell that there are no major issues with this component. Yes, plenty of minor bugs, but no show stoppers (at least in my use cases). Having said that, I would strongly advice against using this component if you start a project from the scratch. This component is a good option only if you are bound to AngularJS 1.0.x. If you are free to choose the Angular version, go for a newer component. A list of table components for Angular 4 was compiled by Sam Deering in this blog.
this will sort it for you
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but1=(Button)findViewById(R.id.button1);
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent int1= new Intent(MainActivity.this,xxactivity.class);
startActivity(int1);
}
});
}
You just need to amend the xxactivity to the name of your second activity
I got this problem after deleting the logs I resolved this by rebuilding the project
net stop w32time
w32tm /config /syncfromflags:manual /manualpeerlist:"0.it.pool.ntp.org 1.it.pool.ntp.org 2.it.pool.ntp.org 3.it.pool.ntp.org"
net start w32time
w32tm /config /update
w32tm /resync /rediscover
.BAT Sample File: https://gist.github.com/thedom85/dbeb58627adfb3d5c3af
I also recommend this program: http://www.timesynctool.com/
According to official Android information about dumpsys:
The dumpsys tool runs on the device and provides information about the status of system services.
To get a list of available services use
adb shell dumpsys -l
CLR, BCL and C#/VB.Net, ADO.NET, WinForms and/or ASP.NET. Most of the places that require additional .Net technologies, like WPF or WCF will call it out explicitly.
In CSS3 you have:
:nth-last-child(2)
See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
nth-last-child Browser Support:
- Chrome 2
- Firefox 3.5
- Opera 9.5, 10
- Safari 3.1, 4
- Internet Explorer 9
With the information you have provided, your best bet will be to use Python 3.x.
Your error suggests that the code may have been written for Python 3 given that it is trying to import urllib.parse
. If you've written the software and have control over its source code, you should change the import to:
from urlparse import urlparse
urllib
was split into urllib.parse
, urllib.request
, and urllib.error
in Python 3.
I suggest that you take a quick look at software collections in CentOS if you are not able to change the imports for some reason. You can bring in Python 3.3 like this:
yum install centos-release-SCL
yum install python33
scl enable python33
Check this page out for more info on SCLs
I am using this and it is working fine.
{{1288323623006 | date:'medium'}}: Oct 29, 2010 9:10:23 AM
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: 2010-10-29 09:10:23 +0530
{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: 10/29/2010 @ 9:10AM
{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: 10/29/2010 at 9:10AM
I think your best bet would be to use a combination of absolute and relative positioning.
Here's a fiddle: http://jsfiddle.net/PKVza/2/
given your html:
<div class="row">
<div class="col-sm-6">
<img src="~/Images/MyLogo.png" alt="Logo" />
</div>
<div class="bottom-align-text col-sm-6">
<h3>Some Text</h3>
</div>
</div>
use the following CSS:
@media (min-width: 768px ) {
.row {
position: relative;
}
.bottom-align-text {
position: absolute;
bottom: 0;
right: 0;
}
}
EDIT - Fixed CSS and JSFiddle for mobile responsiveness and changed the ID to a class.
As I just came across this topic I wanted to share the reason and solution why I got the message "invalid or corrupt jarfile":
I had updated the version of the "maven-jar-plugin" in my pom.xml from 2.1 to 3.1.2. Everything still went fine and a jar file was built. But somehow it obviously wouldn't run anymore.
As soon as i set the "maven-jar-plugin" version back to 2.1 again, the problem was gone.
With LINQ:
List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();
If you need foreach, then no need for ToList:
foreach (string s in l.Skip(1).Take(2)){}
Advantage of LINQ is that if you want to just skip some leading element,you can :
List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}
i.e. no need to take care of count/length, etc.
I had the same problem: I first downloaded my certificates to my small MacBook while on the run. When trying to install the certificates on my iMac... then I ran into the problems described on this page.
After spending hours pulling my hair out like many of you, I performed the following steps to fix it:
Close all your stuff except your webpage that should be logged into App Dev center.
Open Xcode. Click WINDOW > ORGANIZER. Then click the Devices tab and select "Provisioning Profiles" on the left. That should bring up your provisioning profiles. Highlight one by one (if more than 1), right click and delete profile. Yes, just do it! Delete them all! (I kept making a new one after a new one trying to make the thing work.)
From the first page you see after logging into the App Dev Center on the right side click "iOS PROVISIONING PORTAL" > (do not "launch assistant"). Instead click on the left side. Select CERTIFICATES. You will probably have just one line listed with your name/company - from there click on the right side REVOKE. Click OK to verify that's what you want to do.
On the same page click DEVICES. Click the box next to your device you are trying to provision and click REMOVE SELECTED. Again click OK to verify.
Wait about 2 minutes to let Apple do their thing.
Now click on "HOME" that is on the left side navigation.
Click "Launch Assistant"
create a new app ID - call it whatever you want. Just make sure it's unique enough to know that's the one you just created because the others you've been messing with all day will not be deleted from Apples Dev Center.
You should be able to follow the rest of the Assistant without troubles -- the main thing is you just had to delete your old provision profiles and start over.
Good Luck!
Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.
Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.
//
// ViewController.m
// AutoLayoutDynamicVerticalContainerHeight
//
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end
@implementation ViewController
- (void)viewDidLoad
{
// INVOKE SUPER
[super viewDidLoad];
// INIT ALL REQUIRED UI ELEMENTS
self.contentView = [[UIView alloc] init];
self.myLabel = [[UILabel alloc] init];
self.myOtherLabel = [[UILabel alloc] init];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);
// TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;
// ESTABLISH VIEW HIERARCHY
[self.view addSubview:self.contentView]; // View adds content view
[self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
[self.contentView addSubview:self.myOtherLabel];
// LAYOUT
// Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
// Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet
/* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
// ^To me this is what's weird... but okay once you understand...
// Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
// Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
// Note, this is the view that we are choosing to use to drive the height (and width) of our container...
// The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// COLOR VIEWS
self.view.backgroundColor = [UIColor purpleColor];
self.contentView.backgroundColor = [UIColor redColor];
self.myLabel.backgroundColor = [UIColor orangeColor];
self.myOtherLabel.backgroundColor = [UIColor greenColor];
// CONFIGURE VIEWS
// Configure MY LABEL
self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
self.myLabel.numberOfLines = 0; // Let it flow
// Configure MY OTHER LABEL
self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
self.myOtherLabel.numberOfLines = 0;
self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}
@end
brew install android-sdk --cask
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});
This code works if you want to reveal dropdowns on hover.
I just changed the .slideToggle
to .slideDown
& .slideUp
, and removed the (400)
timing
You can use the DATE_FORMAT function. Here's a page with examples, and the patterns you can use to select different date components.
I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.
I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = dict["mailgunAPIPath"] as? String
let emailRecipient = "[email protected]"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
// POST and report back with any errors and response codes
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?
Hope this helps offers a solution to someone trying to avoid using 3rd party code for their POST requests!
Try using Ctrl-click on the multiple places you want the cursors. Ctrl-D is for multiple incremental finds.
As per Brandon's answer. But if you're using ASP.NET MVC which uses unobtrusive validation, you can add the data-val attribute to the first one. I also like to have labels for each radio button for usability.
<span class="field-validation-valid" data-valmsg-for="color" data-valmsg-replace="true"></span>
<p><input type="radio" name="color" id="red" value="R" data-val="true" data-val-required="Please choose one of these options:"/> <label for="red">Red</label></p>
<p><input type="radio" name="color" id="green" value="G"/> <label for="green">Green</label></p>
<p><input type="radio" name="color" id="blue" value="B"/> <label for="blue">Blue</label></p>
SELECT * FROM tablename WHERE visible=1 ORDER BY CASE WHEN `position` = 0 THEN 'a' END , position ASC
The only way I think then to get the functionality you want would be to do something like
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("TestEverything");
//$JUnit-BEGIN$
suite.addTestSuite(TestOne.class);
suite.addTestSuite(TestTwo.class);
suite.addTestSuite(TestThree.class);
//$JUnit-END$
}
public static void main(String[] args)
{
AllTests test = new AllTests();
Test testCase = test.suite();
TestResult result = new TestResult();
setUp();
testCase.run(result);
tearDown();
}
public void setUp() {}
public void tearDown() {}
}
I use something like this in eclipse, so I'm not sure how portable it is outside of that environment
I like this solution for small applications:
class App:
__conf = {
"username": "",
"password": "",
"MYSQL_PORT": 3306,
"MYSQL_DATABASE": 'mydb',
"MYSQL_DATABASE_TABLES": ['tb_users', 'tb_groups']
}
__setters = ["username", "password"]
@staticmethod
def config(name):
return App.__conf[name]
@staticmethod
def set(name, value):
if name in App.__setters:
App.__conf[name] = value
else:
raise NameError("Name not accepted in set() method")
And then usage is:
if __name__ == "__main__":
# from config import App
App.config("MYSQL_PORT") # return 3306
App.set("username", "hi") # set new username value
App.config("username") # return "hi"
App.set("MYSQL_PORT", "abc") # this raises NameError
.. you should like it because:
App
, @property
, but that requires more variable handling code per item and is object-based.--Edit--: For large applications, storing values in a YAML (i.e. properties) file and reading that in as immutable data is a better approach (i.e. blubb/ohaal's answer). For small applications, this solution above is simpler.
I use the following syntax:
objTest = {"error": true, "message": "test message"};
get error:
var name = "error"
console.log(objTest[name]);
get message:
name = "message"
console.log(objTest[name]);
Usually, git creates a hidden directory in project's root directory (.git/)
When you're working on a CMS, its possible you install modules/plugins carrying .git/ directory with git's metadata for the specific module/plugin
Quickest solution is to find all .git directories and keep only your root git metadata directory. If you do so, git will not consider those modules as project submodules.
res = method.delay()
print(f"id={res.id}, state={res.state}, status={res.status} ")
print(res.get())
Add this to your class to import the DLL file:
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
const int SW_HIDE = 0;
const int SW_SHOW = 5;
And then if you want to hide it use this command:
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
And if you want to show the console:
var handle = GetConsoleWindow();
ShowWindow(handle, SW_SHOW);
You can run the ant task echoproperties
and look for "java.version" or ant -v
and look for "Java version", e.g. on my machine
ant echoproperties | grep java.version
shows
[echoproperties] java.version=11.0.9.1
and
ant -v | grep -i "java version"
shows
Detected Java version: 11 in: /opt/java/zulu11.43.55-ca-jdk11.0.9.1-linux_x64
There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask array is the easiest one (and iirc a much faster one):
>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[ 123, 24123, 32432],
[ 234, 24, 23]])
>>> b = y > 200
>>> b
array([[False, True, True],
[ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432, 234])
>>> len(y[b])
3
>>>> y[b].sum()
56789
Update:
As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:
>>>> (y>200).sum()
3
which is a simpler solution.
Speed comparison with filter
:
### use boolean/mask array ###
b = y > 200
%timeit y[b]
100000 loops, best of 3: 3.31 us per loop
%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop
### use filter ###
x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop
%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop
%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop
%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop
*** use numpy.where ***
nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop
%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
Here's a nice easy way I found:
h <- hist(g, breaks = 10, density = 10,
col = "lightgray", xlab = "Accuracy", main = "Overall")
xfit <- seq(min(g), max(g), length = 40)
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g))
yfit <- yfit * diff(h$mids[1:2]) * length(g)
lines(xfit, yfit, col = "black", lwd = 2)
Just be sure that you have include python to windows PATH variable, then run python -m ensurepip
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
For the integer value of the instantaneous week of the year try:
import datetime
datetime.datetime.utcnow().isocalendar()[1]
MP3 files have headers you need to respect.
You could ether use a library like Open Source Audio Library Project and write a tool around it. Or you can use a tool that understands mp3 files like Audacity.
A DATE
column does not have a format. You cannot specify a format for it.
You can use DateStyle
to control how PostgreSQL emits dates, but it's global and a bit limited.
Instead, you should use to_char
to format the date when you query it, or format it in the client application. Like:
SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;
e.g.
regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
to_char
------------
01/04/2014
(1 row)
Try to use this code example:
$("#TextAreaID1").bind('input propertychange', function () {
var maxLength = 4000;
if ($(this).val().length > maxLength) {
$(this).val($(this).val().substring(0, maxLength));
}
});
Setting overflow: hidden
hides the scrollbar. Set overflow: scroll
to make sure the scrollbar appears all the time.
To use the ::webkit-scrollbar
property, simply target .scroll
before calling it.
.scroll {
width: 200px;
height: 400px;
background: red;
overflow: scroll;
}
.scroll::-webkit-scrollbar {
width: 12px;
}
.scroll::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}
.scroll::-webkit-scrollbar-thumb {
border-radius: 10px;
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
?
See this live example
If the size of the subdirectory is not particularly huge, AND you wish to stay away from the CLI, here's a quick solution to manually reset the sub-directory:
Cheers. You just manually reset a sub-directory in your feature branch to be same as that of master branch !!
Another shortcut way to do this is press Ctrl+Shift+L and select which command you want to perform and hit enter
its best practice for beginner.
On Windows, search for Anaconda PowerShell Prompt. Right click the program and select Run as administrator. In the command prompt, execute the following command:
conda update -n base -c defaults conda
Your Anaconda should now update without admin related errors.
Inside the wsdl file look for the import element, which looks like this :
`<import namespace="nameSpaceValue" location="Users/myname/.../targetxsdName.xsd"/>`
Change the location attribute in the above element to the location of your xsd files stored locally, and it should work.
Your question is vague (are you always looking for the first part?), but you can get the exact output you asked for with string.Split
:
string[] substrings = a.Split(',');
b = substrings[0];
Console.WriteLine(b);
Output:
abc
I encountered this issue, but the solutions provided didn't directly help me, so I'm sharing how I got myself into a similar situation and temporarily resolved it.
I created a new project within an existing solution and copy & pasted the Header and CPP file from another project within that solution that I needed to include in my new project through the IDE. Intellisense displayed an error suggesting it could not resolve the reference to the header file and compiling the code failed with the same error too.
After reading the posts here, I checked the project folder with Windows File Explorer and only the main.cpp file was found. For some reason, my copy and paste of the header file and CPP file were just a reference? (I assume) and did not physically copy the file into the new project file.
I deleted the files from the Project view within Visual Studio and I used File Explorer to copy the files that I needed to the project folder/directory. I then referenced the other solutions posted here to "include files in project" by showing all files and this resolved the problem.
It boiled down to the files not being physically in the Project folder/directory even though they were shown correctly within the IDE.
Please Note I understand duplicating code is not best practice and my situation is purely a learning/hobby project. It's probably in my best interest and anyone else who ended up in a similar situation to use the IDE/project/Solution setup correctly when reusing code from other projects - I'm still learning and I'll figure this out one day!
Use the TRY_CONVERT function.
Create a user defined function. This will avoid the issues that Fedor Hajdu mentioned with regards to currency, fractional numbers, etc:
CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS int
AS
BEGIN
SET @Value = REPLACE(@Value, ',', '')
IF ISNUMERIC(@Value + 'e0') = 0 RETURN NULL
IF ( CHARINDEX('.', @Value) > 0 AND CONVERT(bigint, PARSENAME(@Value, 1)) <> 0 ) RETURN NULL
DECLARE @I bigint =
CASE
WHEN CHARINDEX('.', @Value) > 0 THEN CONVERT(bigint, PARSENAME(@Value, 2))
ELSE CONVERT(bigint, @Value)
END
IF ABS(@I) > 2147483647 RETURN NULL
RETURN @I
END
GO
-- Testing
DECLARE @Test TABLE(Value nvarchar(50)) -- Result
INSERT INTO @Test SELECT '1234' -- 1234
INSERT INTO @Test SELECT '1,234' -- 1234
INSERT INTO @Test SELECT '1234.0' -- 1234
INSERT INTO @Test SELECT '-1234' -- -1234
INSERT INTO @Test SELECT '$1234' -- NULL
INSERT INTO @Test SELECT '1234e10' -- NULL
INSERT INTO @Test SELECT '1234 5678' -- NULL
INSERT INTO @Test SELECT '123-456' -- NULL
INSERT INTO @Test SELECT '1234.5' -- NULL
INSERT INTO @Test SELECT '123456789000000' -- NULL
INSERT INTO @Test SELECT 'N/A' -- NULL
SELECT Value, dbo.TryConvertInt(Value) FROM @Test
Reference: I used this page extensively when creating my solution.
For Sql server you can try this one.
SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE
Keep in mind that with Visual Studio 2010 you may not need/want any addon. A lot of the ReSharper features were added into the Visual Studio 2010 core features. ReSharper, CodeRush, etc. have other features above and beyond Visual Studio for sure, but see what's been added vs. what you need. It could be that the core install takes care of what you are interested in now.
I personally use ReSharper 5 still as it has many uses, for me. What each coder finds most important though varies widely. You'll have to test each for yourself, but luckily all the alternatives have trial periods as well.
I use ruamel.yaml. Details & debate here.
from ruamel import yaml
with open(filename, 'r') as fp:
read_data = yaml.load(fp)
Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use
from ruamel import yaml
instead of
import yaml
and it will fix most of your problems.
EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.
I haven't done anything with rank, but I discovered this today with row_number().
select item, name, sold, row_number() over(partition by item order by sold) as row from table_name
This will result in some repeating row numbers since in my case each name holds all items. Each item will be ordered by how many were sold.
+--------+------+-----+----+
|glasses |store1| 30 | 1 |
|glasses |store2| 35 | 2 |
|glasses |store3| 40 | 3 |
|shoes |store2| 10 | 1 |
|shoes |store1| 20 | 2 |
|shoes |store3| 22 | 3 |
+--------+------+-----+----+
Using null
is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.
As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:
if (x==2) doSomething;
else doSomethingElse
or, in your case,
if (x==2) doSomething;
Bootstrap 3.x.x
<!-- Modal -->
<div class="modal fade" id="employeeBasicDetails" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm employeeModal" role="document">
<form>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal Title</h4>
</div>
<div class="modal-body row">
Modal Body...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Notice I added .employeeModal class in second div. Then style that class.
.employeeModal{
width: 700px;
}
Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer
In my instance at least this seems to be a harmless "not ready" condition that the API retries until it succeeds.
I get anywhere from two to nine of these (on my worst-case-tester, a 2009 FossilBook with 20 tabs open via cellular hotspot).... but then the video functions properly. Once it's running my postMessage-based calls to seekTo definitely work, haven't tested others.
Your algorithm is correct. But we can do optimization as follows: While reversing, You may try keeping another variable to reduce backward counter since computing of array.length-(i+1) may take time! And also move declaration of temp outside so that everytime it needs not to be allocated
double temp;
for(int i=0,j=array.length-1; i < (array.length/2); i++, j--) {
// swap the elements
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.
@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL
This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.
The file that you downloaded (http://curl.haxx.se/ca/cacert.pem) is a bundle of the root certificates from the major trusted certificate authorities. You said that the remote host has a self-signed SSL certificate, so it didn't use a trusted certificate. The openssl.cafile
setting needs to point to the CA certificate that was used to sign the SSL certificate on the remote host. PHP 5.6 has been improved over previous versions of PHP to now verify peer certificates and host names by default (http://php.net/manual/en/migration56.openssl.php)
You'll need to locate the CA certificate that was generated on the server that signed the SSL certificate and copy it to this server. The only other option is to disable verifying the peer, but that defeats the SSL security. If you DO want to try disabling verification, try this array with the code from my previous answer:
$contextOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false
)
);
Either way, if you're using self-signed certificates, you'll need to add the CA cert that was used to sign the remote host's SSL certificate to the trusted store on the server you're connecting from OR use stream contexts to use that certificate for each individual request. Adding it to the trusted certificates is the simplest solution. Just add the contents of the remote host's CA cert to the end of the cacert.pem file you downloaded.
Previous:
fsockopen doesn't support stream contexts, so use stream_socket_client instead. It returns a resource that can be used with all the commands that fsockopen resources can.
This should be a drop in replacement for the snippet you have in your question:
<?php
$contextOptions = array(
'ssl' => array(
'verify_peer' => true, // You could skip all of the trouble by changing this to false, but it's WAY uncool for security reasons.
'cafile' => '/etc/ssl/certs/cacert.pem',
'CN_match' => 'example.com', // Change this to your certificates Common Name (or just comment this line out if not needed)
'ciphers' => 'HIGH:!SSLv2:!SSLv3',
'disable_compression' => true,
)
);
$context = stream_context_create($contextOptions);
$fp = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $context);
if (!$fp) {
echo "$errstr ({$errno})<br />\n";
}else{
$this->request = 'POST '.substr($this->url, strlen($this->host)).' HTTP/1.1'.$crlf
.'Host: '.$this->host.$crlf
.'Content-Length: '.$content_length.$crlf
.'Connection: Close'.$crlf.$crlf
.$body;
fwrite($fp, $this->request);
while (!feof($fp)) {
$this->response .= fgets($fp);
}
fclose($fp);
}
Done.
All answers were just a suggested solutions or workarounds. But still don't get answer to the question: why margin:auto works with position:relative but does not with position:absolute.
Following explanation was helpful for me:
"Margins make little sense on absolutely positioned elements since such elements are removed from the normal flow, thus they cannot push away any other elements on the page. Using margins like this can only affect the placement of the element to which the margin is applied, not any other element." http://www.justskins.com/forums/css-margins-and-absolute-82168.html
def merge(d1, d2, merge):
result = dict(d1)
for k,v in d2.iteritems():
if k in result:
result[k] = merge(result[k], v)
else:
result[k] = v
return result
d1 = {'a': 1, 'b': 2}
d2 = {'a': 1, 'b': 3, 'c': 2}
print merge(d1, d2, lambda x, y:(x,y))
{'a': (1, 1), 'c': 2, 'b': (2, 3)}
You can't add them directly, you have to make a new array and then copy each of the arrays into the new one. System.arraycopy is a method you can use to perform this copy.
int[] array1and2 = new int[array1.length + array2.length];
System.arraycopy(array1, 0, array1and2, 0, array1.length);
System.arraycopy(array2, 0, array1and2, array1.length, array2.length);
This will work regardless of the size of array1 and array2.
HTML does not support a dropdown list with checkboxes. You can have a dropdown list, or a checkbox list. You could possibly fake a dropdowncheckbox list using javascript and hiding divs, but that would be less reliable than just a standard checkbox list.
There are of course 3rd party controls that look like a dropdown checkboxlist, but they are using the div tricks.
you could also use a double listbox, which handles multi select by moving items back and forth between two lists. This has the added benefit of being easily to see all the selected items at once, even though the list of total items is long
(Imagine a list of every city in the world, with only the first and last selected)
I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully
1 Customers
2 Invoices
Formula Used :
=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")
Result :
listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");
<parent>
<groupId>com.dummy.bla</groupId>
<artifactId>parent</artifactId>
<version>0.1-SNAPSHOT</version>
</parent>
<groupId>com.dummy.bla.sub</groupId>
<artifactId>kid</artifactId>
You mean you want to remove the version from parent block of B's pom, I think you can not do it, the groupId, artifactId, and version specified the parent's pom coordinate's, what you can omit is child's version.
There is a workaround by using the history API on modern browsers with fallback on old ones:
if(history.pushState) {
history.pushState(null, null, '#myhash');
}
else {
location.hash = '#myhash';
}
Credit goes to Lea Verou
If you want one line:
list_of_dict = [{} for i in range(list_len)]
Assuming nodeList = document.querySelectorAll("div")
, this is a concise form of converting nodelist
to array.
var nodeArray = [].slice.call(nodeList);
See me use it here.
None of the above solutions worked for me.
I didn't have a toolbar in my project, but got the same error.
I cleaned up the project, uninstalled the app. Then I ran a gradlew build --refresh-dependencies, and found out there were some onclick events without corresponding code in the xml files.
I removed them, rebuilt the project, and it worked.
The dependencies didn't seem like were updated, but that's another story.
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
If we want to rename a specific key in hash then we can do it as follows:
Suppose my hash is my_hash = {'test' => 'ruby hash demo'}
Now I want to replace 'test' by 'message', then:
my_hash['message'] = my_hash.delete('test')
Create a temporary element (e. g. DIV
), assign your HTML code to its innerHTML
property, and then append its child nodes to the HEAD
element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD
contents via its innerHTML
, this wouldn’t affect existing child elements of the HEAD
element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval()
.
You can .split()
to get an array of strings, then loop through to convert them to numbers, like this:
var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; }
//use myArray, it's an array of numbers
The +myArray[i]
is just a quick way to do the number conversion, if you're sure they're integers you can just do:
for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); }
Add "name" attribute and keep the name same for all the radio buttons in a form.
i.e.,
<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3
Hope that would help.
Since PostgreSQL 9.4 there's the FILTER
clause, which allows for a very concise query to count the true values:
select count(*) filter (where myCol)
from tbl;
The above query is a bad example in that a simple WHERE clause would suffice, and is for demonstrating the syntax only. Where the FILTER clause shines is that it is easy to combine with other aggregates:
select count(*), -- all
count(myCol), -- non null
count(*) filter (where myCol) -- true
from tbl;
The clause is especially handy for aggregates on a column that uses another column as the predicate, while allowing to fetch differently filtered aggregates in a single query:
select count(*),
sum(otherCol) filter (where myCol)
from tbl;
For camera access use:
<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>
I have same problem with the most basic situation and my problem was solved with inserting this meta in the head:
<meta charset="UTF-8">
the character encoding (which is actually UTF-8) of the html document was not declared
You have to rebuild the table. Luckily, the order of the columns doesn't matter at all!
Watch as I magically reorder your columns:
SELECT ID, Newfield, FieldA, FieldB FROM MyTable
Also this has been asked about a bazillion times before.
for a in range(1):
for b in range(3):
a = b*2
print(a)
As per your question, you want to iterate the outer loop with help of the inner loop.
In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.
Output:
0
2
4
Just put these parameters in your TextView. It works :)
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit ="marquee_forever"
android:scrollHorizontally="true"
android:focusable="true"
android:focusableInTouchMode="true"
`
Use LPAD(TIME_FORMAT(TIMEDIFF(NOW(), UTC_TIMESTAMP),’%H:%i’),6,’+')
to get a value in MySQL's timezone format that you can conveniently use with CONVERT_TZ()
. Note that the timezone offset you get is only valid at the moment in time where the expression is evaluated since the offset may change over time if you have daylight savings time. Yet the expression is useful together with NOW()
to store the offset with the local time, which disambiguates what NOW()
yields. (In DST timezones, NOW()
jumps back one hour once a year, thus has some duplicate values for distinct points in time).
ListView
is the ancestor to RecyclerView
. There were many things that ListView
either didn't do, or didn't do well. If you were to gather the shortcomings of the ListView
and solved the problem by abstracting the problems into different domains you'd end up with something like the recycler view. Here are the main problem points with ListViews:
Didn't enforce View
Reuse for same item types (look at one of the adapters that are used in a ListView
, if you study the getView method you will see that nothing prevents a programmer from creating a new view for every row even if one is passed in via the convertView
variable)
Didn't prevent costly findViewById
uses(Even if you were recycling views as noted above it was possible for devs to be calling findViewById
to update the displayed contents of child views. The main purpose of the ViewHolder
pattern in ListViews
was to cache the findViewById
calls. However this was only available if you knew about it as it wasn't part of the platform at all)
Only supported Vertical Scrolling with Row displayed Views (Recycler view doesn't care about where views are placed and how they are moved, it's abstracted into a LayoutManager
. A Recycler can therefore support the traditional ListView
as shown above, as well as things like the GridView
, but it isn't limited to that, it can do more, but you have to do the programming foot work to make it happen).
Animations to added/removed was not a use case that was considered. It was completely up to you to figure out how go about this (compare the RecyclerView. Adapter classes notify* method offerings v. ListViews to get an idea).
In short RecyclerView
is a more flexible take on the ListView
, albeit more coding may need to be done on your part.
If you want to get the key name of myVar
object then you can use Object.keys()
for this purpose.
var result = Object.keys(myVar);
alert(result[0]) // result[0] alerts typeA
A float has 23 bits of precision, and a double has 52.
Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:
Public Sub SubA()
On Error Goto ProcError
Connection.Open
Open File for Writing
SomePreciousResource.GrabIt
ProcExit:
Connection.Close
Connection = Nothing
Close File
SomePreciousResource.Release
Exit Sub
ProcError:
MsgBox Err.Description
Resume ProcExit
End Sub
See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6
You can only do this in Javascript/JQuery, you can do it with the following JQuery (assuming you've gave your select an id of multiselect):
$(function () {
$("#multiSelect").css("height", parseInt($("#multiSelect option").length) * 20);
});
You can set its before
and after
to force a constant width-to-height ratio
HTML:
<div class="squared"></div>
CSS:
.squared {
background: #333;
width: 300px;
}
.squared::before {
content: '';
padding-top: 100%;
float: left;
}
.squared::after {
content: '';
display: block;
clear: both;
}
To detect both positive and negative peaks, PeakDetect is helpful.
from peakdetect import peakdetect
peaks = peakdetect(data, lookahead=20)
# Lookahead is the distance to look ahead from a peak to determine if it is the actual peak.
# Change lookahead as necessary
higherPeaks = np.array(peaks[0])
lowerPeaks = np.array(peaks[1])
plt.plot(data)
plt.plot(higherPeaks[:,0], higherPeaks[:,1], 'ro')
plt.plot(lowerPeaks[:,0], lowerPeaks[:,1], 'ko')
If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:
build: ./dir
image: webapp:tag
This results in an image named webapp
and tagged tag
, built from ./dir
.
You can create "everywhere" custom search engine right from the Google Custom Search homepage ( http://www.google.com/cse/ ). You should just click 'advanced', during adding new engine. There you can provide Schema.org site type. 'Thing' is most generic type, which covers all the web.
How would you like to differentiate between forms? You can use different IDs, and then use this function:
function getInputElements(formId) {
var form = document.getElementById(formId);
if (form === null) {
return null;
}
return form.getElementsByTagName('input');
}
git config
allows to specify a config file.
And .gitmodules
is a config file.
So, with the help of "use space as a delimiter with cut command":
git config --file=.gitmodules --get-regexp ^^submodule.*\.path$ | cut -d " " -f 2
That will list only the paths, one per declared submodule.
As Tino points out in the comments:
- This fails for submodules with spaces in it.
submodule paths may contain newlines, as in
git submodule add https://github.com/hilbix/bashy.git "sub module" git mv 'sub module' $'sub\nmodule'
As a more robust alternative, Tino proposes:
git config -z --file .gitmodules --get-regexp '\.path$' | \ sed -nz 's/^[^\n]*\n//p' | \ tr '\0' '\n'
For paths with newlines in them (they can be created with
git mv
), leave away the| tr '\0' '\n'
and use something like... | while IFS='' read -d '' path; do ...
for further processing with bash.
This needs a modern bash which understandsread -d ''
(do not forget the space between-d and ''
).
Try the following configuration:
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false
log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false
Then configure the loggers in the Java code accordingly:
static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");
Do you want output to go to stdout
? If not, change the first line of log4j.properties
to:
log4j.rootLogger=OFF
and get rid of the stdout
lines.
You can do that without an I/O redirection:
sed -i 's/$/\n/' filename
You can also use this command to append a newline to a list of files:
find dir -name filepattern | xargs sed -i 's/$/\n/' filename
For echo
, some shells implement it as a shell builtin command. It might not accept the -e
option. If you still want to use echo
, try to find where the echo
binary file is, using which echo
. In most cases, it is located in /bin/echo
, so you can use /bin/echo -e "\n"
to echo a new line.
You could print the backspace character '\b' as many times as necessary to delete the line before printing the updated progress bar.
Programmatic version:
int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {color_for_state_checked, color_for_state_normal}
CompoundButtonCompat.setButtonTintList(checkbox, new ColorStateList(states, colors));
I have the same problem while integrating the Facebook SDK for login.
I'm suggesting below approach for development mode > you can test all things if you are login with same account, which is used for 'developers.facebook.com' and if you want to use another accounts then you need to add Roles for that particular app, for that you can add developer or testers by using fid or facebook username.
Eg: - Select the particular app > Roles and then add developer or testers.
You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:
1 In Web.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
Internet or network address: your proxy address
User name: your user name
Password: you pass
This configuration worked for me, without change the code.
I asked the same question some time ago and had to answer it myself. Here's what I came up with:
It seems, my first thought [that it comes from its JavaScript roots] was correct.
'\/' === '/'
in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like\z
) not allowed in JSON?The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.
You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.
Jython does offers support for JSR-223 which basically lets you run a Python script from Java.
You can use a ScriptContext
to configure where you want to send your output of the execution.
For instance, let's suppose you have the following Python script in a file named numbers.py
:
for i in range(1,10):
print(i)
So, you can run it from Java as follows:
public static void main(String[] args) throws ScriptException, IOException {
StringWriter writer = new StringWriter(); //ouput will be stored here
ScriptEngineManager manager = new ScriptEngineManager();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer); //configures output redirection
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader("numbers.py"), context);
System.out.println(writer.toString());
}
And the output will be:
1
2
3
4
5
6
7
8
9
As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.
If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.
If you have an instance, and you want to ensure it's not null, simply check for null:
if (value != null)
{
// it's not null.
}
A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
pil_im = Image.open('image.jpg')
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
I found this somewhere else. I like this answer!
SELECT [Hourly], COUNT(*) as [Count]
FROM
(SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
FROM table) idat
GROUP BY [Hourly]
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open()
because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send()
. Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml
file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add .
and then git commit
and the master branch will be created.
Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.
For me works fine:
@RequestMapping (value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
URI uri = new URI("http://www.google.com");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(uri);
return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}
Because the SET NOCOUNT option is set to on. Remove the line "SET NOCOUNT ON;" in your query or stored procedure.
See more at SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete.
There are 10 events in ASP.NET page life cycle, and the sequence is:
Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.
Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010
Here is one more way to specify event.target
:
import { Component, EventEmitter, Output } from '@angular/core';_x000D_
_x000D_
@Component({_x000D_
selector: 'text-editor',_x000D_
template: `<textarea (keyup)="emitWordCount($event)"></textarea>`_x000D_
})_x000D_
export class TextEditorComponent {_x000D_
_x000D_
@Output() countUpdate = new EventEmitter<number>();_x000D_
_x000D_
emitWordCount({ target = {} as HTMLTextAreaElement }) { // <- right there_x000D_
_x000D_
this.countUpdate.emit(_x000D_
// using it directly without `event`_x000D_
(target.value.match(/\S+/g) || []).length);_x000D_
}_x000D_
}
_x000D_
After looking over answers to several similar questions, this seems to be the best solution for me:
def floatToString(inputValue):
return ('%.15f' % inputValue).rstrip('0').rstrip('.')
My reasoning:
%g
doesn't get rid of scientific notation.
>>> '%g' % 0.000035
'3.5e-05'
15 decimal places seems to avoid strange behavior and has plenty of precision for my needs.
>>> ('%.15f' % 1.35).rstrip('0').rstrip('.')
'1.35'
>>> ('%.16f' % 1.35).rstrip('0').rstrip('.')
'1.3500000000000001'
I could have used format(inputValue, '.15f').
instead of '%.15f' % inputValue
, but that is a bit slower (~30%).
I could have used Decimal(inputValue).normalize()
, but this has a few issues as well. For one, it is A LOT slower (~11x). I also found that although it has pretty great precision, it still suffers from precision loss when using normalize()
.
>>> Decimal('0.21000000000000000000000000006').normalize()
Decimal('0.2100000000000000000000000001')
>>> Decimal('0.21000000000000000000000000006')
Decimal('0.21000000000000000000000000006')
Most importantly, I would still be converting to Decimal
from a float
which can make you end up with something other than the number you put in there. I think Decimal
works best when the arithmetic stays in Decimal
and the Decimal
is initialized with a string.
>>> Decimal(1.35)
Decimal('1.350000000000000088817841970012523233890533447265625')
>>> Decimal('1.35')
Decimal('1.35')
I'm sure the precision issue of Decimal.normalize()
can be adjusted to what is needed using context settings, but considering the already slow speed and not needing ridiculous precision and the fact that I'd still be converting from a float and losing precision anyway, I didn't think it was worth pursuing.
I'm not concerned with the possible "-0" result since -0.0 is a valid floating point number and it would probably be a rare occurrence anyway, but since you did mention you want to keep the string result as short as possible, you could always use an extra conditional at very little extra speed cost.
def floatToString(inputValue):
result = ('%.15f' % inputValue).rstrip('0').rstrip('.')
return '0' if result == '-0' else result
Your great great great great great great great grandfather should upgrade to SQL Server 2008 and use the DateTime2 data type, which supports dates in the range: 0001-01-01 through 9999-12-31.
Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).
you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below
javac -target 1.7 *.java
if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.
Jihene Stambouli answered OP question most directly... Question was; why does
for(int i = low; i <= high; ++i)
{
res = runalg(i);
if (res > highestres)
{
highestres = res;
}
}
produce the error;
3np1.c:15: error: 'for' loop initial declaration used outside C99 mode
for which the answer is
for(int i = low...
should be
int i;
for (i=low...