Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.
CSS:
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
}
Attribute position: fixed
will keep it stuck, while other content will be scrollable. Don't forget to set width:100%
to make it fill fully to the right.
I am not the OP of this answer but it helped me so:
I wanted to change the color of the next/previous buttons of the bootstrap carousel on my homepage.
Solution: Copy the selector names from bootstrap.css and move them to your own style.css (with your own prefrences..) :
.carousel-control-prev-icon,
.carousel-control-next-icon {
height: 100px;
width: 100px;
outline: black;
background-size: 100%, 100%;
border-radius: 50%;
border: 1px solid black;
background-image: none;
}
.carousel-control-next-icon:after
{
content: '>';
font-size: 55px;
color: red;
}
.carousel-control-prev-icon:after {
content: '<';
font-size: 55px;
color: red;
}
_x000D_
WARNING: This functionality is deprecated. See warning below in comments.
Have a look at this question: Direct download from Google Drive using Google Drive API
Basically you have to create a public directory and access your files by relative reference with something like
wget https://googledrive.com/host/LARGEPUBLICFOLDERID/index4phlat.tar.gz
Alternatively, you can use this script: https://github.com/circulosmeos/gdown.pl
display: flex;
display: -webkit-box;
did it for me. Also there were two display: flex;
on the same element from different classes. So I removed the other one.
There are new units that you can use:
vw
- viewport width
vh
- viewport height
#neo_main_container1
{
width: 100%; //fallback
width: 100vw;
}
Opera Mini does not support this, but you can use it in all other modern browsers.
WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.
This solution belongs to @Arseniy-II, I have just simplified it into a function.
function _scrollTo(selector, yOffset = 0){
const el = document.querySelector(selector);
const y = el.getBoundingClientRect().top + window.pageYOffset + yOffset;
window.scrollTo({top: y, behavior: 'smooth'});
}
Usage (you can open up the console right here in StackOverflow and test it out):
_scrollTo('#question-header', 0);
I'm currently using this in production and it is working just fine.
Problem solved
php artisan cache:clear
sudo chmod -R 777 vendor storage
this enables the write permission to app , framework, logs Hope this will Help
The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:
HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))
Format..., select formatting, OK, OK.
where I have filled yellow the cells that are triggering the red fill result.
You can use Intel XDK IDE to develop and debug on emulator or on real device
I also found Visual Studio 2015 RC tools for cordova very good, with it's ripple emulator
In case someone is still searching for a query to display the difference in hr min and sec format: (This will display the difference in this format: 2 hr 20 min 22 secs)
SELECT
CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ' hrs ' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20)) + ' mins' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)% 60 as nvarchar(20)) + ' secs'
OR can be in the format as in the question:
CAST(DATEDIFF(minute, StartDateTime, EndDateTime)/ 60 as nvarchar(20)) + ':' + CAST(DATEDIFF(second, StartDateTime, EndDateTime)/60 as nvarchar(20))
Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do
select dbo.fun_functional_score('01091400003') as [er]
I used the Visual Studio 2008 Uninstall tool and it worked fine for me.
You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).
Found here, on the MSDN Forum: MSDN forum topic.
I found this answer here
Be sure you run the tool with admin-rights.
<!-- HTML4 and (x)HTML -->
<script type="text/javascript"></script>
<!-- HTML5 -->
<script></script>
type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript. If this attribute is absent, the script is treated as JavaScript.
Ref: https://developer.mozilla.org/en/docs/Web/HTML/Element/script
You can copy-paste data from en excel-sheet to an SQL-table by doing so:
Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.
Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).
One cannot disable the browser back button functionality. The only thing that can be done is prevent them.
The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:
<script>
function preventBack() {
window.history.forward();
}
setTimeout("preventBack()", 0);
window.onunload = function() {
null
};
</script>
Suppose there are two pages Page1.php
and Page2.php
and Page1.php
redirects to Page2.php
.
Hence to prevent user from visiting Page1.php
using the back button you will need to place the above script in the head section of Page1.php
.
For more information: Reference
EDIT: I've added one more option for bootstrap sidebars.
There are actually three manners in which you can make a bootstrap 3 sidebar. I tried to keep the code as simple as possible.
Here you can see a demo of a simple fixed sidebar I've developed with the same height as the page
I've also developed a rather simple column sidebar that works in a two or three column page inside a container. It takes the length of the longest column. Here you can see a demo
If you google bootstrap dashboard, you can find multiple suitable dashboard, such as this one. However, most of them require a lot of coding. I've developed a dashboard that works without additional javascript (next to the bootstrap javascript). Here is a demo
For all three examples you off course have to include the jquery, bootstrap css, js and theme.css files.
If you want the sidebar to hide on pressing a button this is also possible with only a little javascript.Here is a demo
FragmentPagerAdapter
stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter
takes the new value from the adapter everytime it is executed.
You can use this
var fs = require('fs');
var myCss = {
style : fs.readFileSync('./style.css','utf8');
};
app.get('/', function(req, res){
res.render('index.ejs', {
title: 'My Site',
myCss: myCss
});
});
put this on template
<%- myCss.style %>
just build style.css
<style>
body {
background-color: #D8D8D8;
color: #444;
}
</style>
I try this for some custom css. It works for me
I ran into the same problem a few minutes ago, the problem was when I uploaded my local theme I had a bunch of tags separating each function I had in there I solved this by putting all the functions in one php tag... Hope this helps.
Bitten by this once again, missing library source links. Google Hosted Libraries Similar link
Mobile browsers generally ignore this attribute to prevent consuming data until user explicitly starts the download.
UPDATE: newer version of mobile browser on Android and iOS do support autoplay function. But it only works if the video is muted or has no audio channel:
Some additional info: https://webkit.org/blog/6784/new-video-policies-for-ios/
#include"stdio.h"//rmv coding for randam number access
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int rmvivek;
srand(time(&t));
rmvivek=1;
while(rmvivek<=5)
{
printf("%c\t",rand()%10);
rmvivek++;
}
getch();
}
Divs stack vertically by default, so there is no need for special handling of "rows" within a column.
div {_x000D_
height:50px;_x000D_
}_x000D_
.short-div {_x000D_
height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
<h1>Responsive Bootstrap</h1>_x000D_
<div class="row">_x000D_
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
<div class="short-div" style="background-color:green">Span 2</div>_x000D_
<div class="short-div" style="background-color:purple">Span 2</div>_x000D_
</div>_x000D_
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
<div class="row-fluid">_x000D_
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
<div class="short-div" style="background-color:#999">Span 6</div>_x000D_
<div class="short-div">Span 6</div>_x000D_
</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
</div>_x000D_
</div>
_x000D_
Here's the fiddle.
opacity
will make both text and background transparent. Use a semi-transparent background-color instead, by using a rgba()
value for example. Works on IE8+
I've custom OAuth2 authorization and request.getHeader("Referer")
is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication
:
protected void sendStartAuthentication(HttpServletRequest request,...
...
requestCache.saveRequest(request, response);
So, all what we need is share requestCache
as Spring bean:
@Bean
public RequestCache requestCache() {
return new HttpSessionRequestCache();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
...
.requestCache().requestCache(requestCache()).and()
...
}
and use it wheen authorization is finished:
@Autowired
private RequestCache requestCache;
public void authenticate(HttpServletRequest req, HttpServletResponse resp){
....
SavedRequest savedRequest = requestCache.getRequest(req, resp);
resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?
savedRequest.getRedirectUrl() : "defaultURL");
}
I had a similar problem where I didn't want to change the Python module search path and needed to load a module relatively from a script (in spite of "scripts can't import relative with all" as BrenBarn explained nicely above).
So I used the following hack. Unfortunately, it relies on the imp
module that
became deprecated since version 3.4 to be dropped in favour of importlib
.
(Is this possible with importlib
, too? I don't know.) Still, the hack works for now.
Example for accessing members of moduleX
in subpackage1
from a script residing in the subpackage2
folder:
#!/usr/bin/env python3
import inspect
import imp
import os
def get_script_dir(follow_symlinks=True):
"""
Return directory of code defining this very function.
Should work from a module as well as from a script.
"""
script_path = inspect.getabsfile(get_script_dir)
if follow_symlinks:
script_path = os.path.realpath(script_path)
return os.path.dirname(script_path)
# loading the module (hack, relying on deprecated imp-module)
PARENT_PATH = os.path.dirname(get_script_dir())
(x_file, x_path, x_desc) = imp.find_module('moduleX', [PARENT_PATH+'/'+'subpackage1'])
module_x = imp.load_module('subpackage1.moduleX', x_file, x_path, x_desc)
# importing a function and a value
function = module_x.my_function
VALUE = module_x.MY_CONST
A cleaner approach seems to be to modify the sys.path used for loading modules as mentioned by Federico.
#!/usr/bin/env python3
if __name__ == '__main__' and __package__ is None:
from os import sys, path
# __file__ should be defined in this case
PARENT_DIR = path.dirname(path.dirname(path.abspath(__file__)))
sys.path.append(PARENT_DIR)
from subpackage1.moduleX import *
Or maybe you missed keyword "Controller" at the end of controller name ;)
Sometimes you can play with padding and margin top, add line-height, etc.
See fiddle.
Style and text forked from @aspirinemaga
.parent
{
width:300px;
line-height:30px;
border:1px solid red;
padding-top:20px;
}
It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).
In the MySQL Workbech version 6.2 don't exits the PreferenceSQLQueries
options.
SET SQL_SAFE_UPDATES=0;
Try putting your text in another div inside your span:
i.e.
<span><div>some text</div></span>
It can be something like this:
a.register:link { color:#FFF; text-decoration:none; font-weight:normal; }
a.register:visited { color: #FFF; text-decoration:none; font-weight:normal; }
a.register:hover { color: #FFF; text-decoration:underline; font-weight:normal; }
a.register:active { color: #FFF; text-decoration:none; font-weight:normal; }
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
Hey define color #000
into as like you and modify your css as like this
.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }
or this
li a { text-decoration: none; color:#000; }
li a:visited { text-decoration: none; color:#000; }
li a:hover { text-decoration: none; color:#000; }
li a:focus { text-decoration: none; color:#000; }
li a:hover, .navBtn:active { text-decoration: none; color:#000; }
I've also found this error can be caused when writing json_encoded() data to MySQL. To get around it I base64_encode() the JSON. Please not that when decoded, the JSON encoding can change values. Nb. 24 can become 24.00
DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml
it doesn't has any means? you may be just need to add like this!
<IfModule dir_module>
DirectoryIndex index.php index.html index.htm
</IfModule>
In the absense of cache control directives that specify otherwise, a 301 redirect defaults to being cached without any expiry date.
That is, it will remain cached for as long as the browser's cache can accommodate it. It will be removed from the cache if you manually clear the cache, or if the cache entries are purged to make room for new ones.
You can verify this at least in Firefox by going to about:cache
and finding it under disk cache. It works this way in other browsers including Chrome and the Chromium based Edge, though they don't have an about:cache
for inspecting the cache.
In all browsers it is still possible to override this default behavior using caching directives, as described below:
If you don't want the redirect to be cached
This indefinite caching is only the default caching by these browsers in the absence of headers that specify otherwise. The logic is that you are specifying a "permanent" redirect and not giving them any other caching instructions, so they'll treat it as if you wanted it indefinitely cached.
The browsers still honor the Cache-Control and Expires headers like with any other response, if they are specified.
You can add headers such as Cache-Control: max-age=3600
or Expires: Thu, 01 Dec 2014 16:00:00 GMT
to your 301 redirects. You could even add Cache-Control: no-cache
so it won't be cached permanently by the browser or Cache-Control: no-store
so it can't even be stored in temporary storage by the browser.
Though, if you don't want your redirect to be permanent, it may be a better option to use a 302 or 307 redirect. Issuing a 301 redirect but marking it as non-cacheable is going against the spirit of what a 301 redirect is for, even though it is technically valid. YMMV, and you may find edge cases where it makes sense for a "permanent" redirect to have a time limit. Note that 302 and 307 redirects aren't cached by default by browsers.
If you previously issued a 301 redirect but want to un-do that
If people still have the cached 301 redirect in their browser they will continue to be taken to the target page regardless of whether the source page still has the redirect in place. Your options for fixing this include:
A simple solution is to issue another redirect back again.
If the browser is directed back to a same URL a second time during a redirect, it should fetch it from the origin again instead of redirecting again from cache, in an attempt to avoid a redirect loop. Comments on this answer indicate this now works in all major browsers - but there may be some minor browsers where it doesn't.
If you don't have control over the site where the previous redirect target went to, then you are out of luck. Try and beg the site owner to redirect back to you.
Prevention is better than cure - avoid a 301 redirect if you are not sure you want to permanently de-commission the old URL.
if you state a.redLink{color:red;}
then to keep this on hover and such add a.redLink:hover{color:red;}
This will make sure no other hover states will change the color of your links
You probably want an extra wrapper. use a div for the background and position it below your content..
http://jsfiddle.net/pixelass/42F2j/
HTML
<div id="background-image"></div>
<div id="content">
Here is the content at opacity 1
<img src="http://lorempixel.com/100/50/fashion/1/">
</div>
CSS
#background-image {
background-image: url(http://lorempixel.com/400/200/sports/1/);
opacity:0.4;
position:absolute;
top:0;
left:0;
height:200px;
width:400px;
z-index:0;
}
#content {
z-index:1;
position:relative;
}
.services-list .fa {
transition: 0.5s;
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
color: blue;
}
/* For me, @media query is the easiest way for disabling hover on mobile devices */
@media only screen and (min-width: 981px) {
.services-list .fa:hover {
color: #faa152;
transition: 0.5s;
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
/* You can actiate hover on mobile with :active */
.services-list .fa:active {
color: #faa152;
transition: 0.5s;
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
.services-list .fa-car {
font-size:20px;
margin-right:15px;
}
.services-list .fa-user {
font-size:48px;
margin-right:15px;
}
.services-list .fa-mobile {
font-size:60px;
}
_x000D_
<head>
<title>Hover effects on mobile browsers</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="services-list">
<i class="fa fa-car"></i>
<i class="fa fa-user"></i>
<i class="fa fa-mobile"></i>
</div>
</body>
_x000D_
For example: https://jsfiddle.net/lesac4/jg9f4c5r/8/
In order to avoid duplicate code, I recommend you to define the color once, for both states:
a, a:visited{
color: /* some color */;
}
This, indeeed, will mantain your <a>
color (whatever this color is) even when the link has been visited.
Notice that, if the color of the element inside of the <a>
is being inherited (e.g. the color is set in the body
), you could do the following trick:
a, a:visited {
color: inherit;
}
a {
color: orange !important;
}
!important
has the effect that the property in question cannot be overridden unless another !important
is used. It is generally considered bad practice to use !important
unless absolutely necessary; however, I can't think of any other way of ‘disabling’ :visited
using CSS only.
SELECT SUBDATE(NOW(),1);
where now() function returs current date and time of system in Timestamp...
you can use:
SELECT SUBDATE(CURDATE(),1)
div
's will naturally resize in accordance with their content.
If you set no height on your div, it will expand to contain its conent.
An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.
Here's some ways to do this:
#wrapper{
overflow:hidden;
}
Or
#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
CSS does not have an onlclick event handler. You have to use Javascript.
See more info here on CSS Pseudo-classes: http://www.w3schools.com/css/css_pseudo_classes.asp
a:link {color:#FF0000;} /* unvisited link - link is untouched */
a:visited {color:#00FF00;} /* visited link - user has already been to this page */
a:hover {color:#FF00FF;} /* mouse over link - user is hovering over the link with the mouse or has selected it with the keyboard */
a:active {color:#0000FF;} /* selected link - the user has clicked the link and the browser is loading the new page */
Write a:hover::before
instead of a::before:hover
: example.
You can flip both vertical and horizontal at the same time
-moz-transform: scaleX(-1) scaleY(-1);
-o-transform: scaleX(-1) scaleY(-1);
-webkit-transform: scaleX(-1) scaleY(-1);
transform: scaleX(-1) scaleY(-1);
And with the transition property you can get a cool flip
-webkit-transition: transform .4s ease-out 0ms;
-moz-transition: transform .4s ease-out 0ms;
-o-transition: transform .4s ease-out 0ms;
transition: transform .4s ease-out 0ms;
transition-property: transform;
transition-duration: .4s;
transition-timing-function: ease-out;
transition-delay: 0ms;
Actually it flips the whole element, not just the background-image
SNIPPET
function flip(){_x000D_
var myDiv = document.getElementById('myDiv');_x000D_
if (myDiv.className == 'myFlipedDiv'){_x000D_
myDiv.className = '';_x000D_
}else{_x000D_
myDiv.className = 'myFlipedDiv';_x000D_
}_x000D_
}
_x000D_
#myDiv{_x000D_
display:inline-block;_x000D_
width:200px;_x000D_
height:20px;_x000D_
padding:90px;_x000D_
background-color:red;_x000D_
text-align:center;_x000D_
-webkit-transition:transform .4s ease-out 0ms;_x000D_
-moz-transition:transform .4s ease-out 0ms;_x000D_
-o-transition:transform .4s ease-out 0ms;_x000D_
transition:transform .4s ease-out 0ms;_x000D_
transition-property:transform;_x000D_
transition-duration:.4s;_x000D_
transition-timing-function:ease-out;_x000D_
transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
-moz-transform:scaleX(-1) scaleY(-1);_x000D_
-o-transform:scaleX(-1) scaleY(-1);_x000D_
-webkit-transform:scaleX(-1) scaleY(-1);_x000D_
transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
Use the $_SERVER['HTTP_REFERER']
header, but bear in mind anybody can spoof it at anytime regardless of whether they clicked on a link.
Perhaps you can use something like Gaussian Mixture Models. Here's a Python package for doing GMMs (just did a Google search) http://www.ar.media.kyoto-u.ac.jp/members/david/softwares/em/
memset could be inlined by compiler as a series of efficient opcodes, unrolled for a few cycles. For very large memory blocks, like 4000x2000 64bit framebuffer, you can try optimizing it across several threads (which you prepare for that sole task), each setting its own part. Note that there is also bzero(), but it is more obscure, and less likely to be as optimized as memset, and the compiler will surely notice you pass 0.
What compiler usually assumes, is that you memset large blocks, so for smaller blocks it would likely be more efficient to just do *(uint64_t*)p = 0
, if you init large number of small objects.
Generally, all x86 CPUs are different (unless you compile for some standardized platform), and something you optimize for Pentium 2 will behave differently on Core Duo or i486. So if you really into it and want to squeeze the last few bits of toothpaste, it makes sense to ship several versions your exe compiled and optimized for different popular CPU models. From personal experience Clang -march=native boosted my game's FPS from 60 to 65, compared to no -march.
CookieManager.getInstance().setAcceptCookie(true);
Normally it should work if your webview is already initialized
or try this:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
First, learn the core concepts of Node.js:
Then, you're going to want to see what the community has to offer:
The gold standard for Node.js package management is NPM.
It is a command line tool for managing your project's dependencies.
NPM is also a registry of pretty much every Node.js package out there
Finally, you're going to want to know what some of the more popular packages are for various tasks:
Useful Tools for Every Project:
Unit Testing:
Web Frameworks:
Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.
Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.
Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.
Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.
Web Framework Tools:
Networking:
Command Line Interaction:
Code Generators:
Work with streams:
In my eclipse Luna faced the same issue because of this URL https://sourceforge.net/projects/restfulplugin/files/site/
So i just Disabled the URL that was Shown in the Error From the Available Software Sites.
You may Check the URL or Try with the Updated URL reg to that Exception :)
If you are not concerned with unit testing then you can simply write:
return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
I would use css tables to achieve a 100% sidebar height.
The basic idea is to wrap the sidebar and main divs in a container.
Give the container a display:table
And give the 2 child divs (sidebar and main) a display: table-cell
Like so..
#container {
display: table;
}
#main {
display: table-cell;
vertical-align: top;
}
#sidebar {
display: table-cell;
vertical-align: top;
}
Take a look at this LIVE DEMO where I have modified your initial markup using the above technique (I have used background colors for the different divs so that you can see which ones are which)
Like the answers to many other questions in life, it depends. It depends on what your programming interests and goals are. If you want to program desktop applications, perhaps with a GUI, then C++ (and OOP) is probably a better way to go. If you're interested in hardware programming on something other than an x86 chipset, then C is often a better choice, usually for its speed. If you want to create a new media player or write a business app, I'd choose C++. If you want to do scientific simulations of galaxy collisions or fluid dynamics, behold the power of C.
Not very elegant solution, but "works":
a
{
color: #fff;
}
a:hover
{
text-shadow: -1px 0 #fff, 0 1px #fff, 1px 0 #fff, 0 -1px #fff;
}
I just include the latest version from the jQuery site: http://code.jquery.com/jquery-latest.pack.js It suits my needs and I never have to worry about updating.
EDIT:For a major web app, certainly control it; download it and serve it yourself. But for my personal site, I could not care less. Things don't magically disappear, they are usually deprecated first. I keep up with it enough to know what to change for future releases.
public static String slurp (final File file)
throws IOException {
StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
char[] buf = new char[1024];
int r = 0;
while ((r = reader.read(buf)) != -1) {
result.append(buf, 0, r);
}
}
finally {
reader.close();
}
return result.toString();
}
Actually the "Remote" option in Configuration Menu for Plug-In works by me (Win7 64, ie8 with all updates), however:
Also the previous comment about browsing-history->view objects was also useful if plug-in was installed right now.
Regards!
my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.
$file_name = "a.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) == "txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);
To add previous iOS simulator to Xcode 4.2, you need old xcode_3.2.6_and_ios_sdk_4.3.dmg (or similar version) installer file and do as following:
Now there are a list of your installed simulator.
In Python, you can use urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.
Simply enough:
import urllib2
f = urllib2.urlopen(url)
print f.read()
Will print the received HTTP response.
To pass GET/POST parameters the urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 Tutorial
In order to download a file to Download or Music Folder In SDCard
File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES
And dont forget to add these permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping
as a meta-annotation. So:
Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:
@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)
Yes, there is such a way. You can create a meta annotation like following:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
@AliasFor(annotation = RequestMapping.class, attribute = "value")
String[] value() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "method")
RequestMethod[] method() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "params")
String[] params() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "headers")
String[] headers() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "consumes")
String[] consumes() default {};
@AliasFor(annotation = RequestMapping.class, attribute = "produces")
String[] produces() default {};
}
Then you can use the default settings or even override them as you want:
@JsonRequestMapping(method = POST)
public String defaultSettings() {
return "Default settings";
}
@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
return json;
}
You can read more about AliasFor
in spring's javadoc and github wiki.
Questions : how to check File is empty or not?
Ans: I have slove this issue using this Jquery code
//If your file Is Empty : _x000D_
if (jQuery('#videoUploadFile').val() == '') {_x000D_
$('#message').html("Please Attach File");_x000D_
}else {_x000D_
alert('not work');_x000D_
}_x000D_
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="videoUploadFile">_x000D_
<br>_x000D_
<br>_x000D_
<div id="message"></div>
_x000D_
class Class1(object):
pass
class Class2(Class1):
pass
Class2 is a sub-class of Class1
Your code is fine. There's no problem with returning Strings
in this manner.
In Java, a String
is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String
around without worrying that it would disapper on you, or that someone somewhere would modify it.
If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:
public String time_to_string(long t) // time in milliseconds
{
if (t < 0)
{
return "-";
}
else
{
int secs = (int)(t/1000);
int mins = secs/60;
secs = secs - (mins * 60);
return String.format("%d:%02d", mins, secs);
}
}
As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans
and have replaced the mix of string concatenation and String.format()
with a single call to String.format()
.
The best way to use is white-space: nowrap;
This will align the text to one line.
Also, be wary of additional top level domains that aren't included in some of the answers above.
For example .info, .biz, .ru, .online will throw some sentence parsers but aren't included above.
Here's some info on frequency of top level domains: https://www.westhost.com/blog/the-most-popular-top-level-domains-in-2017/
That could be addressed by editing the code above to read:
alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov|ai|edu|co.uk|ru|info|biz|online)"
The required SQL will be some like:-
SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....
Hope it helps.
For deleting branch from Bitbucket,
You're saying you have this:
char array[20]; char string[100];
array[0]='1';
array[1]='7';
array[2]='8';
array[3]='.';
array[4]='9';
And you'd like to have this:
string[0]= "178.9"; // where it was stored 178.9 ....in position [0]
You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).
Now if you want to copy the first x characters out of array
to string
you can do that with memcpy()
:
memcpy(string, array, x);
string[x] = '\0';
make sure you have mapped the y: drive, or copy all the files to local dir c:/local
c:/local> copy *.* c:/newfile.txt
The alert method blocks execution until the user closes it:
use the confirm function:
if (confirm('Some message')) {
alert('Thanks for confirming');
} else {
alert('Why did you press cancel? You should have confirmed');
}
And many lines may look like this. The html here is sample only.
var div = document.createElement("div");
div.innerHTML =
'<div class="slideshow-container">\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">1 / 3</div>\n' +
'<img src="image1.jpg" style="width:100%">\n' +
'<div class="text">Caption Text</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">2 / 3</div>\n' +
'<img src="image2.jpg" style="width:100%">\n' +
'<div class="text">Caption Two</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">3 / 3</div>\n' +
'<img src="image3.jpg" style="width:100%">\n' +
'<div class="text">Caption Three</div>\n' +
'</div>\n' +
'<a class="prev" onclick="plusSlides(-1)">❮</a>\n' +
'<a class="next" onclick="plusSlides(1)">❯</a>\n' +
'</div>\n' +
'<br>\n' +
'<div style="text-align:center">\n' +
'<span class="dot" onclick="currentSlide(1)"></span> \n' +
'<span class="dot" onclick="currentSlide(2)"></span> \n' +
'<span class="dot" onclick="currentSlide(3)"></span> \n' +
'</div>\n';
document.body.appendChild(div);
One way:
var1="1:2:3:4:5"
var2=${var1##*:}
Another, using an array:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
var2=${var2[@]: -1}
Yet another with an array:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
count=${#var2[@]}
var2=${var2[$count-1]}
Using Bash (version >= 3.2) regular expressions:
var1="1:2:3:4:5"
[[ $var1 =~ :([^:]*)$ ]]
var2=${BASH_REMATCH[1]}
In case you don't want to mess with the ~/.ssh/config
file mentioned here, you could instead run git config core.sshCommand "ssh -i ~/.ssh/custom_id_rsa"
in the repo where you want to commit from a different account.
The rest of the setup is the same:
Create a new SSH key for the second account with ssh-keygen -t rsa -f ~/.ssh -f ~/.ssh/custom_id_rsa
Sign in to github with your other account, go to https://github.com/settings/keys , and paste the contents of ~/.ssh/custom_id_rsa.pub
Make sure you're using SSH instead of HTTPS as remote url: git remote set-url origin [email protected]:upstream_project_teamname/upstream_project.git
Below is the simple way to create blank line with line size. Here we can adjust size of the blank line. Try this one.
<TextView
android:id="@id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="5dp"/>
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
I found a workaround.
This will get good results for edges and aliasing, whilst retaining a good color for the see-
There are quite a few elements of the $.Ajax()
that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
For future readers.
I wanted specific control over this issue, so this is what I did:
From a fragment or activity, hide your other views (that aren't needed while the keyboard is up), then restore them to solve this problem:
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
//ok now we know the keyboard is up...
view_one.setVisibility(View.GONE);
view_two.setVisibility(View.GONE);
}else{
//ok now we know the keyboard is down...
view_one.setVisibility(View.VISIBLE);
view_two.setVisibility(View.VISIBLE);
}
}
});
This was previously asked on R-Help, so that's worth reviewing.
One suggestion there was to use readChar()
and then do string manipulation on the result with strsplit()
and substr()
. You can see the logic involved in readChar is much less than read.table.
I don't know if memory is an issue here, but you might also want to take a look at the HadoopStreaming package. This uses Hadoop, which is a MapReduce framework designed for dealing with large data sets. For this, you would use the hsTableReader function. This is an example (but it has a learning curve to learn Hadoop):
str <- "key1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey1\t3.9\nkey1\t8.9\nkey1\t1.2\nkey2\t9.9\nkey2\"
cat(str)
cols = list(key='',val=0)
con <- textConnection(str, open = "r")
hsTableReader(con,cols,chunkSize=6,FUN=print,ignoreKey=TRUE)
close(con)
The basic idea here is to break the data import into chunks. You could even go so far as to use one of the parallel frameworks (e.g. snow) and run the data import in parallel by segmenting the file, but most likely for large data sets that won't help since you will run into memory constraints, which is why map-reduce is a better approach.
A Generic Answer for all browsers and precisions:
function round(num, places) {
if(!places){
return Math.round(num);
}
var val = Math.pow(10, places);
return Math.round(num * val) / val;
}
round(num, 2);
Why not just pass the window as a command parameter?
C#:
private void Cancel( Window window )
{
window.Close();
}
private ICommand _cancelCommand;
public ICommand CancelCommand
{
get
{
return _cancelCommand ?? ( _cancelCommand = new Command.RelayCommand<Window>(
( window ) => Cancel( window ),
( window ) => ( true ) ) );
}
}
XAML:
<Window x:Class="WPFRunApp.MainWindow"
x:Name="_runWindow"
...
<Button Content="Cancel"
Command="{Binding Path=CancelCommand}"
CommandParameter="{Binding ElementName=_runWindow}" />
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
Thanks everybody. Lots of good ideas. This is my first application in Spring and Hibernate.. so a little more patience when dealing with "novices" like me..
Please read Tom Anderson and Roman C.'s answers. They explained very well the problem. And all of you helped me.I replaced
SELECT COUNT(*) FROM Books
with
select count(book.id) from Book book
And of course, I have this Spring config:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="extjs.model"/>
Thank you all again!
in VB 2008 (VB 9.0) and later, prefix Right() as Microsoft.VisualBasic.Right(string, number of characters)
Dim str as String = "Hello World"
Msgbox(Microsoft.VisualBasic.Right(str,5))
'World"
Same goes for Left() too.
You can use the Clone
method if you want to iterate through strings along with the string builder... It returns an object so you can convert to a string using the ToString method...:)
Clone the container object and write 2 letters and calculate the height. This return the real height with all style applied, line height, etc. Now, calculate the height object / the size of a letter. In Jquery, the height excelude the padding, margin and border, it is great to calculate the real height of each line:
other = obj.clone();
other.html('a<br>b').hide().appendTo('body');
size = other.height() / 2;
other.remove();
lines = obj.height() / size;
If you use a rare font with different height of each letter, this does not works. But works with all normal fonts, like Arial, mono, comics, Verdana, etc. Test with your font.
Example:
<div id="content" style="width: 100px">hello how are you? hello how are you? hello how are you?</div>
<script type="text/javascript">
$(document).ready(function(){
calculate = function(obj){
other = obj.clone();
other.html('a<br>b').hide().appendTo('body');
size = other.height() / 2;
other.remove();
return obj.height() / size;
}
n = calculate($('#content'));
alert(n + ' lines');
});
</script>
Result: 6 Lines
Works in all browser without rare functions out of standards.
You can also do this without cat
, though honestly cat
is more readable:
>> file1 < file2
The >>
appends STDIN to file1
and the <
dumps file2
to STDIN.
In my bash shell the following worked like a charm:
cat input_file | xargs -I % sh -c 'command1 %; command2 %; command3 %;'
where input_file is
arg1
arg2
arg3
As evident, this allows you to execute multiple commands with each line from input_file, a nice little trick I learned here.
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
Using multiple comment/answers in this thread, here is my solution :
import hashlib
def md5_for_file(path, block_size=256*128, hr=False):
'''
Block size directly depends on the block size of your filesystem
to avoid performances issues
Here I have blocks of 4096 octets (Default NTFS)
'''
md5 = hashlib.md5()
with open(path,'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
if hr:
return md5.hexdigest()
return md5.digest()
And finally,
- This has been built by a community, thanks all for your advices/ideas.
Use char instead of byte:
System.out.println("string " + (char)0x63);
Or if you want to be a Unicode puritan, you use codepoints:
System.out.println("string " + new String(new int[]{ 0x63 }, 0, 1));
And if you like the old skool US-ASCII "every byte is a character" idea:
System.out.println("string " + new String(new byte[]{ (byte)0x63 },
StandardCharsets.US_ASCII));
Avoid using the String(byte[])
constructor recommended in other answers; it relies on the default charset. Circumstances could arise where 0x63
actually isn't the character c.
So, I've figured out the issue and it was a combination of bad logic and not being totally familiar with the automake/autotools world. I was adding the correct files to my Makefile.am template, but I wasn't sure which step in our build process actually created the makefile itself. So, I was compiling with an old makefile that had no idea about my new files whatsoever.
Thanks for the responses and the link to the GCC FAQ. I will be sure to read that to avoid this problem occurring for a real reason.
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2
You can get it with .outerHeight()
.
Sometimes, it will return 0
. For the best results, you can call it in your div
's ready event.
To be safe, you should not set the height of the div
to x
. You can keep its height auto
to get content populated properly with the correct height.
$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})
You can find a detailed post here.
Both of the following work (as discussed here).
exec sp_rename 'ENG_TEst.[[ENG_Test_A/C_TYPE]]]' ,
'ENG_Test_A/C_TYPE', 'COLUMN'
exec sp_rename 'ENG_TEst."[ENG_Test_A/C_TYPE]"' ,
'ENG_Test_A/C_TYPE', 'COLUMN'
eg:
MyPackageName is com.example.demo
MyActivityName is com.example.test.MainActivity
adb shell am start -n com.example.demo/com.example.test.MainActivity
Open below file C:\xampp\htdocs\project\common\config\params-local.php
Before your code:
<?php
return [
];
after your code:
<?php
yii::setAlias('@path1', 'localhost/foodbam/backend/web');
return [
];
In my case I was using uwsgi, added the property http-timeout for more then 60 seconds but it was not working because of some extra space and config file was not getting loaded properly.
This is a follow-up to Update (July 2018). I am on 64 bit Windows 10 but am set up to build r packages from source for both 32 and 64 bit with Rtools. My 64 bit jdk is jdk-11.0.2. When I can, I do everything in RStudio. As of March 2019, rjava is tested with <=jdk11, see github issue #157.
Sys.setenv(JAVA_HOME="C:/Program Files/Java/jdk-11.0.2")
Sys.getenv("JAVA_HOME")
install.packages("rJava",,"http://rforge.net")
FYI, the rstudio scripting console doesn't like the double commas... but it works!
Its works 100% ng build --prod --aot --build-optimizer --vendor-chunk=true
I have implemented this way and it works.It is much easier than all that is reported.
We have two activities : one is the main and another is the secondary.
In secondary activity, which is where we want to end the main activity , define the following variable:
public static Activity ACTIVIDAD;
And then the following method:
public static void enlaceActividadPrincipal(Activity actividad)
{
tuActividad.ACTIVIDAD=actividad;
}
Then, in your main activity from the onCreate
method , you make the call:
actividadSecundaria.enlaceActividadPrincipal(this);
Now, you're in control. Now, from your secondary activity, you can complete the main activity. Finish calling the function, like this:
ACTIVIDAD.finish();
Armin's answer is so useful, thank you. #2 is what's most important to know when trying to set up unload events that work in most browsers: you cannot alert() or confirm(), but returning a string will generate a confirm modal.
But I found that even with just returning a string, I had some cross-browser issues specific to Mootools (using version 1.4.5 in this instance). This Mootools-specific implementation worked great in Firefox, but did not result in a confirm popup in Chrome or Safari:
window.addEvent("beforeunload", function() {
return "Are you sure you want to leave this page?";
});
So in order to get my onbeforeonload event to work across browsers, I had to use the JavaScript native call:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page?";
}
Not sure why this is the case, or if it's been fixed in later versions of Mootools.
To put it all together, this is what it should look like:
In the controller:
List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;
Then in the view:
@foreach (var item in ViewBag.Funds)
{
<span> @item.FundName </span>
}
Use commons-io IOUtils.toByteArray(URL):
String url = "http://localhost:8080/images/anImage.jpg";
byte[] fileContent = IOUtils.toByteArray(new URL(url));
Maven dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
On Lubuntu, I just tried apt-get purge ruby* and as well as removing ruby, it looks like this command tried to remove various things to do with GRUB, which is a bit worrying for next time I want to reboot my computer. I can't yet say if any damage has really been done.
The BIT
datatype is generally used to store boolean
values (0
for false
, 1
for true
).
I had the same issue that occurred when I was working with the VS GUI tool. What I did to fix it was I deleted the local repository and pulled it down from my git source - thank you git!! :)
This may not be the solution in all instances,. but by deleting all of the local files and recompiling, I was able to get it working again!
Given your edited problem description, I'd suggest using COALESCE()
instead of that unwieldy CASE
expression:
SELECT FullName
FROM (
SELECT COALESCE(LastName+', '+FirstName, FirstName) AS FullName
FROM customers
) c
GROUP BY FullName;
COUNTIF
works well for quick difference-checking. And it's easier to remember and simpler to work with than VLOOKUP
.
=COUNTIF([Book1]Sheet1!$A:$A, A1)
will give you a column showing 1 if there's match and zero if there's no match (with the bonus of showing >1 for duplicates within the list itself).
To expand on @PhiLho answer, you can center a very large image (or any size image) on a page with:
{
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
Or you could use a smaller image with a background color that matches the background of the image (if it is a solid color). This may or may not suit your purposes.
{
background-color: green;
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
<form action="{{url('/url_part_in_route').'/'.$parameter_of_update_function_of_resource_controller}}" method="post">
@csrf
<input type="hidden" name="_method" value="PUT"> // or @method('put')
.... // remained instructions
<form>
I don't know if this helps but I just installed Server 2008 Express and was disappointed when I couldn't find the query analyzer but I was able to use the command line 'sqlcmd' to access my server. It is a pain to use but it works. You can write your code in a text file then import it using the sqlcmd command. You also have to end your query with a new line and type the word 'go'.
Example of query file named test.sql:
use master;
select name, crdate from sysdatabases where xtype='u' order by crdate desc;
go
Example of sqlcmd:
sqlcmd -S %computername%\RLH -d play -i "test.sql" -o outfile.sql & notepad outfile.sql
Try this:
scanf("%[^\n]s",name);
\n
just sets the delimiter for the scanned string.
A popular Linux library which has similar functionality would be ncurses.
I know this is late, but this command searches the /usr/ directory to find java for you
sudo find /usr/ -name *jdk
Results to
/usr/lib/jvm/java-6-openjdk
/usr/lib/jvm/java-1.6.0-openjdk
FYI, if you are on a Mac, currently JAVA_HOME is located at
/System/Library/Frameworks/JavaVM.framework/Home
Create a foreign key to the existing SQLLite table:
There is no direct way to do that for SQL LITE. Run the below query to recreate STUDENTS table with foreign keys. Run the query after creating initial STUDENTS table and inserting data into the table.
CREATE TABLE STUDENTS (
STUDENT_ID INT NOT NULL,
FIRST_NAME VARCHAR(50) NOT NULL,
LAST_NAME VARCHAR(50) NOT NULL,
CITY VARCHAR(50) DEFAULT NULL,
BADGE_NO INT DEFAULT NULL
PRIMARY KEY(STUDENT_ID)
);
Insert data into STUDENTS table.
Then Add FOREIGN KEY : making BADGE_NO as the foreign key of same STUDENTS table
BEGIN;
CREATE TABLE STUDENTS_new (
STUDENT_ID INT NOT NULL,
FIRST_NAME VARCHAR(50) NOT NULL,
LAST_NAME VARCHAR(50) NOT NULL,
CITY VARCHAR(50) DEFAULT NULL,
BADGE_NO INT DEFAULT NULL,
PRIMARY KEY(STUDENT_ID) ,
FOREIGN KEY(BADGE_NO) REFERENCES STUDENTS(STUDENT_ID)
);
INSERT INTO STUDENTS_new SELECT * FROM STUDENTS;
DROP TABLE STUDENTS;
ALTER TABLE STUDENTS_new RENAME TO STUDENTS;
COMMIT;
we can add the foreign key from any other table as well.
Code based on the following pull request:
datapoint.color = 'hsl(' + (360 * index / data.length) + ', 100%, 50%)';
If the code has already been checked out by the user that if offline and they have the latest version on their local hd, then they just need to browse to the solution location and open the solution by double clicking sln file. The solution will open in disconnected mode.
Here's a weird one, make sure you have consistent spacing in the config file.
For example:
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: 'enabled'
If the authorization key has 4 spaces before it, like above and the rest are 2 spaces then it won't work.
clean_list = []
for ele in raw_list:
if 'b' in ele or 'a' in ele:
pass
else:
clean_list.append(ele)
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
The problem is that readlines
is a list of strings, each of which is a line of filename
. Perhaps you meant:
for line in readlines:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
I got this error because I was using require('https')
where I should have been using require('http')
.
Open a PL/SQL object in the Editor.
Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.
Compile the object on the database.
Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor
You and your friend both use closures:
A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.
MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures
In your friend's code function function(){ console.log(i2); }
defined inside closure of anonymous function function(){ var i2 = i; ...
and can read/write local variable i2
.
In your code function function(){ console.log(i2); }
defined inside closure of function function(i2){ return ...
and can read/write local valuable i2
(declared in this case as a parameter).
In both cases function function(){ console.log(i2); }
then passed into setTimeout
.
Another equivalent (but with less memory utilization) is:
function fGenerator(i2){
return function(){
console.log(i2);
}
}
for(var i = 0; i < 10; i++) {
setTimeout(fGenerator(i), 1000);
}
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);
Try putting
Display:inline;
In the CSS.
I know this q is quite old but it might me useful:
http://blogs.nvidia.com/2013/02/nvidia-introduces-nsight-tegra-to-assist-android-developers/
I had this problem running WSL 2
the solution was the command
$ sudo dockerd
if after that you still have a problem with permission, run the command:
$ sudo usermod -aG docker your-user
why don't you try this?
password="your password"
username="username"
Ip="<IP>"
sshpass -p "$password" scp /<PATH>/final.txt $username@$Ip:/root/<PATH>
I think I know where your question is headed. And since this question is the one that pop ups in google's search main results, I can give a plain answer on what the @Valid annotation does.
I'll present 3 scenarios on how I've used @Valid
Model:
public class Employee{
private String name;
@NotNull(message="cannot be null")
@Size(min=1, message="cannot be blank")
private String lastName;
//Getters and Setters for both fields.
//...
}
JSP:
...
<form:form action="processForm" modelAttribute="employee">
<form:input type="text" path="name"/>
<br>
<form:input type="text" path="lastName"/>
<form:errors path="lastName"/>
<input type="submit" value="Submit"/>
</form:form>
...
Controller for scenario 1:
@RequestMapping("processForm")
public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
return "employee-confirmation-page";
}
In this scenario, after submitting your form with an empty lastName field, you'll get an error page since you're applying validation rules but you're not handling it whatsoever.
Example of said error: Exception page
Controller for scenario 2:
@RequestMapping("processForm")
public String processFormData(@Valid @ModelAttribute("employee") Employee employee,
BindingResult bindingResult){
return bindingResult.hasErrors() ? "employee-form" : "employee-confirmation-page";
}
In this scenario, you're passing all the results from that validation to the bindingResult, so it's up to you to decide what to do with the validation results of that form.
Controller for scenario 3:
@RequestMapping("processForm")
public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
return "employee-confirmation-page";
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> invalidFormProcessor(MethodArgumentNotValidException ex){
//Your mapping of the errors...etc
}
In this scenario you're still not handling the errors like in the first scenario, but you pass that to another method that will take care of the exception that @Valid triggers when processing the form model. Check this see what to do with the mapping and all that.
To sum up: @Valid on its own with do nothing more that trigger the validation of validation JSR 303 annotated fields (@NotNull, @Email, @Size, etc...), you still need to specify a strategy of what to do with the results of said validation.
Hope I was able to clear something for people that might stumble with this.
I was facing the same issue and just updated the JAVA_HOME worked for me.
previously it was like this: C:\Program Files\Java\jdk1.6.0_45\bin Just removed the \bin and it worked for me.
A super key of an entity set is a set of one or more attributes whose values uniquely determine each entity.
A candidate key of an entity set is a minimal super key.
Let's go on with customer, loan and borrower sets that you can find an image from the link == 1
customer_id is the candidate key of the customer set, loan_number is the candidate key of the loan set.
Although several candidate keys may exist, one of the candidate keys is selected to be the primary key.
Borrower set is formed customer_id and loan_number as a relationship set.
You can also link your .ssh directory between the host and the container, I don't know if this method has any security implications but it may be the easiest method. Something like this should work:
$ sudo docker run -it -v /root/.ssh:/root/.ssh someimage bash
Remember that docker runs with sudo (unless you don't), if this is the case you'll be using the root ssh keys.
Maybe YAML.load ?
Remove the *
from your query and use individual column names, like this:
SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;
Using *
means, in your results you want all the columns of the table. In your case *
will also include FIRSTNAME
. You are then concatenating some columns and using alias of FIRSTNAME
. This creates 2 columns with same name.
If using Cpanel/WHM the location of file config.default.php
is under
/usr/local/cpanel/base/3rdparty/phpMyAdmin/libraries
and you should change the $cfg['ExecTimeLimit'] = 300;
to $cfg['ExecTimeLimit'] = 0;
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
Django has support for this, check get_or_create
person, created = Person.objects.get_or_create(name='abc')
if created:
# A new person object created
else:
# person object already exists
Swift version:
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = 0.5
as.character()
would be the general way rather than use paste()
for its side effect
> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"
(I presume this is a simple example and something like this:
v <- "20081101"
isn't possible?)
The Union method might address your needs. You didn't specify whether order or duplicates was important.
Take two IEnumerables and perform a union as seen here:
int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };
IEnumerable<int> union = ints1.Union(ints2);
// yields { 5, 3, 9, 7, 8, 6, 4, 1, 0 }
You can copy your div like this
$(".package").html($(".button").html())
For N bins, the bin edges are specified by list of N+1 values where the first N give the lower bin edges and the +1 gives the upper edge of the last bin.
Code:
from numpy import np; from pylab import *
bin_size = 0.1; min_edge = 0; max_edge = 2.5
N = (max_edge-min_edge)/bin_size; Nplus1 = N + 1
bin_list = np.linspace(min_edge, max_edge, Nplus1)
Note that linspace produces array from min_edge to max_edge broken into N+1 values or N bins
An optional is to use pyvirtualdisplay
like this:
from pyvirtualdisplay import Display
display = Display(visible=0, size=[800, 600])
display.start()
#do selenium job here
display.close()
A shorter version is:
with Display() as display:
# selenium job here
This is generally a python encapsulate of xvfb
, and more convinient somehow.
By the way, although PhantomJS
is a headless browser and no window will be open if you use it, it seems that PhantomJS
still needs a gui environment to work.
I got Error Code -6 when I use PhantomJS()
instead of Firefox()
in headless mode (putty-connected console). However everything is ok in desktop environment.
Writing from phone, but curvycorners is really good, since it adds it's own borders only if browser doesn't support it by default. In other words, browsers which already support some CSS3 will use their own system to provide corners.
https://code.google.com/p/curvycorners/
You probably want an extra wrapper. use a div for the background and position it below your content..
http://jsfiddle.net/pixelass/42F2j/
HTML
<div id="background-image"></div>
<div id="content">
Here is the content at opacity 1
<img src="http://lorempixel.com/100/50/fashion/1/">
</div>
CSS
#background-image {
background-image: url(http://lorempixel.com/400/200/sports/1/);
opacity:0.4;
position:absolute;
top:0;
left:0;
height:200px;
width:400px;
z-index:0;
}
#content {
z-index:1;
position:relative;
}
You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.
Rather than using plt.axis('off')
you should use ax.axis('off')
where ax
is a matplotlib.axes
object. To do this for your code you simple need to add axarr[0,0].axis('off')
and so on for each of your subplots.
The code below shows the result (I've removed the prune_matrix
part because I don't have access to that function, in the future please submit fully working code.)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("stewie.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')
axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')
axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')
axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')
plt.show()
Note: To turn off only the x or y axis you can use set_visible()
e.g.:
axarr[0,0].xaxis.set_visible(False) # Hide only x axis
[String:Any]
For the fellows using [String:Any]
instead of Dictionary
below is the extension
extension Dictionary where Key == String, Value == Any {
mutating func append(anotherDict:[String:Any]) {
for (key, value) in anotherDict {
self.updateValue(value, forKey: key)
}
}
}
sthing like ?
SELECT DISTINCT .... FROM table WHERE condition
http://www.felixgers.de/teaching/sql/sql_distinct.html
note: Homework question ? and god bless google..
Select your unknown class file, open file inspector tab, check your target name in Target Membership
. There you go.
Testing for name pointing to None
and name existing are two semantically different operations.
To check if val
is None:
if val is None:
pass # val exists and is None
To check if name exists:
try:
val
except NameError:
pass # val does not exist at all
Download all actual dependencies of your projects
find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
Move your local maven repository to temporary location
mv ~/.m2 ~/saved-m2
Rename all files maven-metadata-central.xml* from saved repository into maven-metadata.xml*
find . -type f -name "maven-metadata-central.xml*" -exec rename -v -- 's/-central//' '{}' \;
To setup the modified copy of the local repository as a mirror, create the directory ~/.m2 and the file ~/.m2/settings.xml with the following content (replacing user with your username):
<settings>
<mirrors>
<mirror>
<id>mycentral</id>
<name>My Central</name>
<url>file:/home/user/saved-m2/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
</settings>
Resolve your projects dependencies again:
find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
Now you have local maven repository with minimal of necessary artifacts. Remove local mirror from config file and from file system.
Note that the Perldebugger can also be invoked from the scripts shebang line, which is how I mostly use the -x
flag you refer to, to debug shell scripts.
#! /usr/bin/perl -d
To make it fixed: Try this way,
jsFiddleLink: http://jsfiddle.net/PERtY/
<div class="body">This is a sample body This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample bodyThis is a sample bodyThis is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
v
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
<div class="watermark">
Sample Watermark
</div>
This is a sample body
This is a sample bodyThis is a sample bodyThis is a sample body
</div>
.watermark {
opacity: 0.5;
color: BLACK;
position: fixed;
top: auto;
left: 80%;
}
To use absolute:
.watermark {
opacity: 0.5;
color: BLACK;
position: absolute;
bottom: 0;
right: 0;
}
jsFiddle: http://jsfiddle.net/6YSXC/
In your HTML you have set a "base" tag:
<base href="http://www.cyclistinsuranceaustralia.com.au/">
is this what you want?
var grouped = CustomerList.GroupBy(m => m.GroupID).Select((n) => new { GroupId = n.Key, Items = n.ToList() });
I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).
Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:
<link rel="shortcut icon" href="myIcon.ico" type="image/x-icon" />
And this worked!
It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?
In that scenario use map, you don't need a new Observable for it.
you should use Exceptions.propagate, which is a wrapper so you can send those checked exceptions to the rx mechanism
Observable<String> obs = Observable.from(jsonFile).map(new Func1<File, String>() {
@Override public String call(File file) {
try {
return new Gson().toJson(new FileReader(file), Object.class);
} catch (FileNotFoundException e) {
throw Exceptions.propagate(t); /will propagate it as error
}
}
});
You then should handle this error in the subscriber
obs.subscribe(new Subscriber<String>() {
@Override
public void onNext(String s) { //valid result }
@Override
public void onCompleted() { }
@Override
public void onError(Throwable e) { //e might be the FileNotFoundException you got }
};);
There is an excellent post for it: http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/
With jQuery 3.x use something like:
$('<img src="'+ imgPath +'">').on('load', function() {
$(this).width(some).height(some).appendTo('#some_target');
});
Who can't control backend for Options 405 Method Not Allowed
.
Workaround for Chrome browser.
execute in command line:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="path_to_profile"
Example:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\Users\vital\AppData\Local\Google\Chrome\User Data\Profile 2"
I found this to be the best way of doing this (I had an issue with my server not letting me delete).
On the server that hosts the origin
repository, type the following from a directory inside the repository:
git config receive.denyDeleteCurrent ignore
On your workstation:
git branch -m master vabandoned # Rename master on local
git branch -m newBranch master # Locally rename branch newBranch to master
git push origin :master # Delete the remote's master
git push origin master:refs/heads/master # Push the new master to the remote
git push origin abandoned:refs/heads/abandoned # Push the old master to the remote
Back on the server that hosts the origin
repository:
git config receive.denyDeleteCurrent true
Credit to the author of blog post http://www.mslinn.com/blog/?p=772
public class DeadLock {
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
mainThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread1.join();
}
}
For Windows, I've created a build.cmd
file:
(replace the keystore path and alias)
For Cordova:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
And for Ionic:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
Save it in the ptoject's directory, you can double click or open it with cmd.
.html
<form [formGroup]="contactForm">
<button [disabled]="contactForm.invalid" (click)="onSubmit()">SEND</button>
.ts
contactForm: FormGroup;
Having a table with a foreign key to itself does make sense to me.
You can then use a common table expression in SQL or the connect by prior statement in Oracle to build your tree.
The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.
15.1.2 UAS Behavior==> BYE Handling in RFC 3261
The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.
For forms, use the [FromForm]
attribute instead of the [FromBody]
attribute.
The below controller works with ASP.NET Core 1.1:
public class MyController : Controller
{
[HttpPost]
public async Task<IActionResult> Submit([FromForm] MyModel model)
{
//...
}
}
Note: [FromXxx]
is required if your controller is annotated with [ApiController]
. For normal view controllers it can be omitted.
git rm
will only remove the file on this branch from now on, but it remains in history and git will remember it.
The right way to do it is with git filter-branch
, as others have mentioned here. It will rewrite every commit in the history of the branch to delete that file.
But, even after doing that, git can remember it because there can be references to it in reflog, remotes, tags and such.
If you want to completely obliterate it in one step, I recommend you to use git forget-blob
It is easy, just do git forget-blob file1.txt
.
This will remove every reference, do git filter-branch
, and finally run the git garbage collector git gc
to completely get rid of this file in your repo.
I just converted from Win 7 Home to Win 10 Pro and wanted to replace the batch I call from other batches to echo info in color. Reviewing what is discussed above I use the following which will directly replace my previous batch. NOTE the addition of "~" to the message so that messages with spaces may be used. Instead of remembering codes I use letters for the colors I needed.
If %2 contains spaces requires "..." %1 Strong Colors on black: R=Red G=GREEN Y=YELLOW W=WHITE
ECHO OFF
IF "%1"=="R" ECHO ^[91m%~2[0m
IF "%1"=="G" ECHO ^[92m%~2[0m
IF "%1"=="Y" ECHO ^[93m%~2[0m
IF "%1"=="W" ECHO ^[97m%~2[0m
You can also just add an ON CONFLICT REPLACE clause to your user_name unique constraint and then just INSERT away, leaving it to SQLite to figure out what to do in case of a conflict. See:https://sqlite.org/lang_conflict.html.
Also note the sentence regarding delete triggers: When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.
Try initializing your variables and use them in your connection object:
$username ="root";
$password = "password";
$host = "localhost";
$table = "shop";
$conn = new mysqli("$host", "$username", "$password", "$table");
If you are certain your tnsnames.ora file is correct (eg by testing the connection with the Oracle Net Config Assistant, or logging in successfully with SQLplus), and you are able to open the PLSQL Developer application, but you still can't connect to the database in PLSQL Developer, then follow these steps:
In PLSQL Developer (version 11.0) go to Help/Support Info
Click the TNS Names tab. If the path in PLSQL Developer is wrong it will be blank (no tns file found) or incorrect (wrong tns file in use)
On the Info tab scroll down to the TNS File entry and to see the path for the tns file PLSQL Developer is using. Very likely this is wrong.
To correct the path:
plsqldev.exe TNS_ADMIN=c:\your\tns\directory\path\here
*path is to the directory containing your tnsnames.ora file - for me this is: c:\Oracle\product\11.2.0\client_1\network\admin
A new PLSQL Developer UI will open and you should be able to connect.
Make sure you have a Windows environment variable TNS_ADMIN set to the same path
Model1.belongsTo(Model2, { as: 'alias' })
Model1.findAll({include: [{model: Model2 , as: 'alias' }]},{raw: true}).success(onSuccess).error(onError);
var date = new Date().toLocaleDateString()
"12/30/2009"
Using ASP.NET Core 2.0 will automatically add the IConfiguration
instance of your application in the dependency injection container. This also works in conjunction with ConfigureAppConfiguration
on the WebHostBuilder
.
For example:
public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.AddIniFile("foo.ini");
})
.UseStartup<Startup>()
.Build();
host.Run();
}
It's just as easy as adding the IConfiguration
instance to the service collection as a singleton object in ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
// ...
}
Where Configuration
is the instance in your Startup
class.
This allows you to inject IConfiguration
in any controller or service:
public class HomeController
{
public HomeController(IConfiguration configuration)
{
// Use IConfiguration instance
}
}
If you run the browser in the server and test your url of the project with the local ip you have received all errors of that project without a generally error page(for example 500 error page).
Try;
var str = "foo/bar/test.html"; var tmp = str.split("/"); alert(tmp.pop());
Along the lines of @halfcube's suggestion, this works really well:
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb
Use the gca
("get current axes") helper function:
ax = plt.gca()
Example:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()
Add the following code in .htaccess file.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
URLs redirect tutorial can be found from here - Redirect non-www to www & HTTP to HTTPS using .htaccess file
To expand on Peri's post & why we may not want to use viewstate the following code:
style="<%= _myCSS %>"
Protected _myCSS As String = "display: none"
Is the approach to look at if you're using AJAX, it allows for manipulating the display via asp.net back end code rather than jquery/jscript.
Declare @tablename varchar(50)
set @tablename = 'Your table Name'
EXEC('select * from ' + @tablename)
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h
Ref-link: https://docs.python.org/3.3/library/argparse.html
You can use the following format to generate a tooltip for an image.
<div class="tooltip"><img src="joe.jpg" />
<span class="tooltiptext">Tooltip text</span>
</div>
Just try with:
var check = moment(n.entry.date_entered, 'YYYY/MM/DD');
var month = check.format('M');
var day = check.format('D');
var year = check.format('YYYY');
Here is how I would do it in Java:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
try boost::asio lib (http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) it have lot examples.
This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext
data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:
Argument data type ntext is invalid for argument 1 of replace function.
The simplest fix, if your column data fits within nvarchar
, is to cast the column during replace. Borrowing the code from the accepted answer:
UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'
This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!
I believe this is what you're looking for. It automatically scaled the video to fit the container.
DEMO: http://jsfiddle.net/t8qhgxuy/
Video need to have height and width always set to 100% of the parent.
HTML:
<div class="one"> CONTENT OVER VIDEO
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>
<div class="two">
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>
CSS:
body {
overflow: scroll;
padding: 60px 20px;
}
.one {
width: 90%;
height: 30vw;
overflow: hidden;
border: 15px solid red;
margin-bottom: 40px;
position: relative;
}
.two{
width: 30%;
height: 300px;
overflow: hidden;
border: 15px solid blue;
position: relative;
}
.video-background { /* class name used in javascript too */
width: 100%; /* width needs to be set to 100% */
height: 100%; /* height needs to be set to 100% */
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
JS:
function scaleToFill() {
$('video.video-background').each(function(index, videoTag) {
var $video = $(videoTag),
videoRatio = videoTag.videoWidth / videoTag.videoHeight,
tagRatio = $video.width() / $video.height(),
val;
if (videoRatio < tagRatio) {
val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
} else if (tagRatio < videoRatio) {
val = videoRatio / tagRatio * 1.02;
}
$video.css('transform','scale(' + val + ',' + val + ')');
});
}
$(function () {
scaleToFill();
$('.video-background').on('loadeddata', scaleToFill);
$(window).resize(function() {
scaleToFill();
});
});
Here you can check for couple of things.
DateTime.TryParseExact
. Check the complete list of formats, available here. CultureInfo.InvariantCulture
which is more likely add problem. So instead of passing a NULL
value or setting it to CultureInfo provider = new CultureInfo("en-US")
, you may write it like.
.
if (!DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate))
{
//your condition fail code goes here
return false;
}
else
{
//success code
}
Easiest way to get it done is by adding required
into your select
Select the best option
<br/>
<select name="dd1" id="dd1" required>
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select>
<br/><br/>?
SELECT 'ColName1', 'ColName2', 'ColName3' UNION ALL SELECT ColName1, ColName2, ColName3 FROM YourTable INTO OUTFILE 'c:\\datasheet.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'
There is an underlying buffer/stream that getchar()
and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar()
can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.
If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput
where myInput
is a text file with some data, it will get the EOF
when it reaches the end of the input. EOF
isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.
As an extra warning, I believe getchar()
will also return EOF
if it encounters an error, so you'll want to check ferror()
. Example below (not tested, but you get the idea).
main() {
int c;
do {
c = getchar();
if (c == EOF && ferror()) {
perror("getchar");
}
else {
putchar(c);
}
}
while(c != EOF);
}
Change padding-bottom , i.e may be the simplest possible way .
Not exactly sure why, or what I missed, but after running trough most of the answers and failing. I realized that with this .env file:
MY_VAR="hello there!"
MY_OTHER_VAR=123
I could simply do this:
source .env
echo $MY_VAR
Outputs: Hello there!
Seems to work just fine in Ubuntu linux.
Try to remove the trailing backslash or slash at the end of you publish path and install url
/p:PublishDir="\\BSIIS3\c$\DATA\WEBSITES\benesys.net\benesys.net\TotalEducationTest"
/p:InstallUrl="https://www.benesys.net/benesys.net/TotalEducationTest"
You must have hit a special sequence of characters with the \" and (or) /", but I don't know enough in cmd.exe to figure out.
I personnaly always use Powershell : it's way more friendly and powerful!
Hope it helps!
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm
Also, you can just set the ViewName:
return View("ViewName");
Full controller example:
public ActionResult SomeAction() {
if (condition)
{
return View("CustomView");
}else{
return View();
}
}
This works on MVC 5.
Simple solution to drop all the table at once from terminal.
This involved few steps inside your mysql shell (not a one step solution though), this worked me and saved my day.
Worked for Server version: 5.6.38 MySQL Community Server (GPL)
Steps I followed:
1. generate drop query using concat and group_concat.
2. use database
3. turn off / disable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 0;),
4. copy the query generated from step 1
5. re enable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 1;)
6. run show table
MySQL shell
$ mysql -u root -p
Enter password: ****** (your mysql root password)
mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0; Query OK, 0 rows affected (0.00 sec)
// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)
mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW tables;
Empty set (0.01 sec)
mysql>
I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException
can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.
Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.
The best solution to your problem is probably to first export your dataframe to HTML and then convert it using an HTML-to-image tool. The final appearance could be tweaked via CSS.
Popular options for HTML-to-image rendering include:
Let us assume we have a dataframe named df
.
We can generate one with the following code:
import string
import numpy as np
import pandas as pd
np.random.seed(0) # just to get reproducible results from `np.random`
rows, cols = 5, 10
labels = list(string.ascii_uppercase[:cols])
df = pd.DataFrame(np.random.randint(0, 100, size=(5, 10)), columns=labels)
print(df)
# A B C D E F G H I J
# 0 44 47 64 67 67 9 83 21 36 87
# 1 70 88 88 12 58 65 39 87 46 88
# 2 81 37 25 77 72 9 20 80 69 79
# 3 47 64 82 99 88 49 29 19 19 14
# 4 39 32 65 9 57 32 31 74 23 35
This approach uses a pip
-installable package, which will allow you to do everything using the Python ecosystem.
One shortcoming of weasyprint
is that it does not seem to provide a way of adapting the image size to its content.
Anyway, removing some background from an image is relatively easy in Python / PIL, and it is implemented in the trim()
function below (adapted from here).
One also would need to make sure that the image will be large enough, and this can be done with CSS's @page size
property.
The code follows:
import weasyprint as wsp
import PIL as pil
def trim(source_filepath, target_filepath=None, background=None):
if not target_filepath:
target_filepath = source_filepath
img = pil.Image.open(source_filepath)
if background is None:
background = img.getpixel((0, 0))
border = pil.Image.new(img.mode, img.size, background)
diff = pil.ImageChops.difference(img, border)
bbox = diff.getbbox()
img = img.crop(bbox) if bbox else img
img.save(target_filepath)
img_filepath = 'table1.png'
css = wsp.CSS(string='''
@page { size: 2048px 2048px; padding: 0px; margin: 0px; }
table, td, tr, th { border: 1px solid black; }
td, th { padding: 4px 8px; }
''')
html = wsp.HTML(string=df.to_html())
html.write_png(img_filepath, stylesheets=[css])
trim(img_filepath)
wkhtmltopdf
/wkhtmltoimage
This approach uses an external open source tool and this needs to be installed prior to the generation of the image.
There is also a Python package, pdfkit
, that serves as a front-end to it (it does not waive you from installing the core software yourself), but I will not use it.
wkhtmltoimage
can be simply called using subprocess
(or any other similar means of running an external program in Python).
One would also need to output to disk the HTML file.
The code follows:
import subprocess
df.to_html('table2.html')
subprocess.call(
'wkhtmltoimage -f png --width 0 table2.html table2.png', shell=True)
and its aspect could be further tweaked with CSS similarly to the other approach.
I have a same problem in Visual Studio 2015. Because I use SSL binding in web.config
<rewrite>
<rules>
<rule name="HTTP to HTTPS Redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Found" />
</rule>
</rules>
</rewrite>
And I can fix the problem with the answer of Mr.djroedger. By replacing
<add input="{HTTPS}" pattern="off" />
with
<add input="{HTTP_HOST}" pattern="localhost" negate="true" />
into my web.config, so my code is
<rewrite>
<rules>
<rule name="HTTP to HTTPS Redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="localhost" negate="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Found" />
</rule>
</rules>
</rewrite>
Include the custom error page after changing the header.
The installation of these tools may vary on different OS.
Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.
So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass
I've created a simple example tutorial. You can read this and use in your application.
http://ribinsandroidhelper.blogspot.in/2013/03/qr-code-reading-on-your-application.html
Through this link you can download the qrcode library project and import into your workspace and add library to your project
and copy this code to your activity
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(this, contents,Toast.LENGTH_LONG).show();
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
//Handle cancel
}
}
}
SET UP THE REPOSITORY
For Ubuntu 14.04/16.04/16.10/17.04:
sudo add-apt-repository "deb [arch=amd64] \
https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
For Ubuntu 17.10:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"
Add Docker’s official GPG key:
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
Then install
$ sudo apt-get update && sudo apt-get -y install docker-ce
Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.
An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto
and can afterwards be manually edited.
subcomponent subcomponent_instance_name(/*AUTOINST*/);
Expanded
subcomponent subcomponent_instance_name (/*AUTOINST*/
//Inputs
.clk, (clk)
.rst_n, (rst_n)
.data_rx (data_rx_1[9:0]),
//Outputs
.data_tx (data_tx[9:0])
);
Implicit wires can be automated with /*AUTOWIRE*/
. Check the link for further information.
Better code with adding a subclass AuthorizeRole.cs
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params Rolenames[] roles)
{
this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
}
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Unauthorized" },
{ "controller", "Home" },
{ "area", "" }
}
);
//base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Login" },
{ "controller", "Account" },
{ "area", "" },
{ "returnUrl", HttpContext.Current.Request.Url }
}
);
}
}
}
How to use this
[AuthorizeRole(Rolenames.Admin,Rolenames.Member)]
public ActionResult Index()
{
return View();
}
If you run npm config edit
, you'll get an editor showing the current configuration, and also a list of options and their default values.
But I don't think there's a 'reset' command.
You can use pathlib.
For Python 3.5 and above:
from pathlib import Path
contents = Path(file_path).read_text()
For older versions of Python use pathlib2:
$ pip install pathlib2
Then:
from pathlib2 import Path
contents = Path(file_path).read_text()
This is the actual read_text
implementation:
def read_text(self, encoding=None, errors=None):
"""
Open the file in text mode, read it, and close the file.
"""
with self.open(mode='r', encoding=encoding, errors=errors) as f:
return f.read()
If none of the above solutions work for you (they did not for me) here is what worked on my server:
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
Just a side note for anyone that stumbles onto this same inquiry... My Operating System is 64 bit - so of course I downloaded the 64 bit MySQL driver... however, my Office applications are 32 bit... Once I downloaded the 32 bit version, the error went away and I could move forward.
You have mixed indentation formatting (spaces and tabs)
Go to Settings -> Preferences -> Tab Settings -> Replace by spaces
Select everything CTRL+A
Click TAB once, to add an indentation everywhere
Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.
Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH%
is used to represent value of existing path variable in Windows while ${PATH}
is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:
export CLASSPATH=${CLASSPATH}:/new/path
but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:
-cp
options overrides CLASSPATH
environment variable.-cp
and CLASSPATH
envorinment variable.Reference: How Classpath works in Java.
This is another option:
switch (true) {
case (value > 100):
//do stuff
break;
case (value <= 100)&&(value > 75):
//do stuff
break;
case (value < 50):
//do stuff
break;
}
You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there
export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR
To accomodate both data scenarios you have, you will want to use this:
datevalue(text(a2,"mm/dd/yyyy"))
That will give you the date number representation for a cell that Excel has in date, or in text datatype.
To create a new line, symbol is '\n'
var i;
for(i=10; i>=0; i= i-1){
var s;
for(s=0; s<i; s = s+1){
document.write("*");
}
//i want this to print a new line
document.write('\n');
}
If you are outputting to the page, you'll want to use "<br/>"
instead of '/n'
;
Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...
id = cursor.lastrowid
...should work too, and it's per-connection based obviously.
Something like this?
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
alert(res);
convert to date again:
date = new Date(res);
alert(date)
or alternatively:
date = new Date(res);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = date + '-' + hours + ':' + minutes + ':' + seconds;
alert(formattedTime)
Set tag for imageview and label in cell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("imagedataCell", forIndexPath: indexPath) as! UITableViewCell
let rowData = self.tableData[indexPath.row] as! NSDictionary
let urlString = rowData["artworkUrl60"] as? String
// Create an NSURL instance from the String URL we get from the API
let imgURL = NSURL(string: urlString!)
// Get the formatted price string for display in the subtitle
let formattedPrice = rowData["formattedPrice"] as? String
// Download an NSData representation of the image at the URL
let imgData = NSData(contentsOfURL: imgURL!)
(cell.contentView.viewWithTag(1) as! UIImageView).image = UIImage(data: imgData!)
(cell.contentView.viewWithTag(2) as! UILabel).text = rowData["trackName"] as? String
return cell
}
OR
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "imagedataCell")
if let rowData: NSDictionary = self.tableData[indexPath.row] as? NSDictionary,
urlString = rowData["artworkUrl60"] as? String,
imgURL = NSURL(string: urlString),
formattedPrice = rowData["formattedPrice"] as? String,
imgData = NSData(contentsOfURL: imgURL),
trackName = rowData["trackName"] as? String {
cell.detailTextLabel?.text = formattedPrice
cell.imageView?.image = UIImage(data: imgData)
cell.textLabel?.text = trackName
}
return cell
}
see also TableImage loader from github
For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail
why not use substring/replace space to echo;
?
set "_line=hello world"
echo\%_line: =&echo;%
hello
world
echo;
set "_line=hello\nworld"
echo\%_line:\n=&echo;%
Here is a complete version of code for doing this. I have tested it. The BufferedImage
and Base64
class do the trick mainly. Also some parameter needs to be set correctly.
public class SimpleConvertImage {
public static void main(String[] args) throws IOException{
String dirName="C:\\";
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
ImageIO.write(img, "jpg", baos);
baos.flush();
String base64String=Base64.encode(baos.toByteArray());
baos.close();
byte[] bytearray = Base64.decode(base64String);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
}
}
You can do this with html5 very easily:
var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove()
The following works well in a .php file.
<php? /*your block you want commented out*/ ?>
Use something like this:
page1.php
<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start()
BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
Another option in SQL Server is to do all of your dynamic querying into table variable in a stored proc, then use a cursor to query and process that. As to the dreaded cursor debate :), I have seen studies that show that in some situations, a cursor can actually be faster if properly set up. I use them myself when the required query is too complex, or just not humanly (for me ;) ) possible.
nickf's solution modified:
function addhttp($url) {
if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
$url = "http://" . $url;
}
return $url;
}
When in doubt, be explicit about the data type conversion using CAST/CONVERT:
UPDATE TABLE
SET EndDate = CAST('2009-05-25' AS DATETIME)
WHERE Id = 1
Use an image editor to cut out a portion of the background, then apply CSS's background-repeat property to make the small image fill the area where it is used.
In some cases, background-repeat creates seams where the image repeats. A solution is to use an image editor as follows: starting with the background image, copy the image, flip (mirror, not rotate) the copy left-to-right, and paste it to the right edge of the original, overlapping 1 pixel. Crop to remove 1 pixel from the right edge of the combined image. Now repeat for the vertical: copy the combined image, flip the copy top-to-bottom, paste it to the bottom of the combined, overlapping one pixel. Crop to remove 1 pixel from the bottom. The resulting image should be seam-free.
You can do:Math.round(<double precision value> * 100.0) / 100.0
But Math.round is fastest but it breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)).
Use Bigdecimal it is bit inefficient as it converts the values to string but more relieval:
BigDecimal(<value>).setScale(<places>, RoundingMode.HALF_UP).doubleValue()
use your preference of Rounding mode.
If you are curious and want to know more detail why this happens you can read this:
window.clipboardData.getData('Text')
will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.
You import the function from outside the main instance, and don't add it to the methods block. so the context of this
is not the vm.
Either do this:
ready() {
checkAuth.call(this)
}
or add the method to your methods first (which will make Vue bind this
correctly for you) and call this method:
methods: {
checkAuth: checkAuth
},
ready() {
this.checkAuth()
}
Don't check File.Exists()
like that. In fact, the whole thing is over-complicated. This should do what you need:
Dim strFile As String = $@"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in Occured at-- {DateTime.Now}{Environment.NewLine}")
Got it all down to two lines of code :)
You can force cut to display all fields and subsequent ones adding -
to field number.
NAME=`basename "$FILE"`
EXTENSION=`echo "$NAME" | cut -d'.' -f2-`
So if FILE is eth0.pcap.gz
, the EXTENSION will be pcap.gz
Using the same logic, you can also fetch the file name using '-' with cut as follows :
NAME=`basename "$FILE" | cut -d'.' -f-1`
This works even for filenames that do not have any extension.
Check this out: http://www.tamirgal.com/home/dev.aspx?Item=sharpSsh
SharpSSH is a pure .NET implementation of the SSH2 client protocol suite. It provides an API for communication with SSH servers and can be integrated into any .NET application.
The library is a C# port of the JSch project from JCraft Inc. and is released under BSD style license.
SharpSSH allows you to read/write data and transfer files over SSH channels using an API similar to JSch's API. In addition, it provides some additional wrapper classes which offer even simpler abstraction for SSH communication.
SharpSSH project page at source forge: http://sourceforge.net/projects/sharpssh
The following MySQL query will itself produce a single query that will truncate all tables in a given database. It bypasses FOREIGN keys:
SELECT CONCAT(
'SET FOREIGN_KEY_CHECKS=0; ',
GROUP_CONCAT(dropTableSql SEPARATOR '; '), '; ',
'SET FOREIGN_KEY_CHECKS=1;'
) as dropAllTablesSql
FROM ( SELECT Concat('TRUNCATE TABLE ', table_schema, '.', TABLE_NAME) AS dropTableSql
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = 'DATABASE_NAME' ) as queries
nodevars.bat
"%HOMEDRIVE%%HOMEPATH% /file1/file2/file3
nodevars.bat
This work even with Swedish words
The mechanism I tend to use is a combination of readelf -V
to dump the .gnu.version
information from libstdc++, and then a lookup table that matches the largest GLIBCXX_
value extracted.
readelf -sV /usr/lib/libstdc++.so.6 | sed -n 's/.*@@GLIBCXX_//p' | sort -u -V | tail -1
if your version of sort
is too old to have the -V
option (which sorts by version number) then you can use:
tr '.' ' ' | sort -nu -t ' ' -k 1 -k 2 -k 3 -k 4 | tr ' ' '.'
instead of the sort -u -V
, to sort by up to 4 version digits.
In general, matching the ABI version should be good enough.
If you're trying to track down the libstdc++.so.<VERSION>
, though, you can use a little bash like:
file=/usr/lib/libstdc++.so.6
while [ -h $file ]; do file=$(ls -l $file | sed -n 's/.*-> //p'); done
echo ${file#*.so.}
so for my system this yielded 6.0.10
.
If, however, you're trying to get a binary that was compiled on systemX to work on systemY, then these sorts of things will only get you so far. In those cases, carrying along a copy of the libstdc++.so that was used for the application, and then having a run script that does an:
export LD_LIBRARY_PATH=<directory of stashed libstdc++.so>
exec application.bin "$@"
generally works around the issue of the .so that is on the box being incompatible with the version from the application. For more extreme differences in environment, I tend to just add all the dependent libraries until the application works properly. This is the linux equivalent of working around what, for windows, would be considered dll hell.
Right click on the page and choose 'inspect element'. In the screen that opens now (the developer tools), clicking the second icon from the left @ the bottom of it opens a console, where you can type javascript. The console is linked to the current page.
I think you can use JSON.stringify:
// after your each loop
JSON.stringify(values);
The best solution I could find for this problem is to specify private key file in ansible.cfg (I usually keep it in the same folder as a playbook):
[defaults]
inventory=ec2.py
vault_password_file = ~/.vault_pass.txt
host_key_checking = False
private_key_file = /Users/eric/.ssh/secret_key_rsa
Though, it still sets private key globally for all hosts in playbook.
Note: You have to specify full path to the key file - ~user/.ssh/some_key_rsa silently ignored.
You can simply create a controller funciton and pass your parameters with the $scope object.
$scope.Edit = function (modalParam) {
var modalInstance = $modal.open({
templateUrl: '/app/views/admin/addeditphone.html',
controller: function($scope) {
$scope.modalParam = modalParam;
}
});
}
ListView.FocusedItem.Index
or you can use foreach loop like this
int index= -1;
foreach (ListViewItem itm in listView1.SelectedItems)
{
if (itm.Selected)
{
index= itm.Index;
}
}
In addition to running it with mvn exec:java
, you can also run it with mvn exec:exec
mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"
or you can simply use
def question_params
params.require(:question).permit(team_ids: [])
end
Using the title attribute:
<div id="sub1 sub2 sub3" title="some text on mouse over">some text</div>
Not tested but you can try something like this :
Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))
while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile ,
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists
when 1 then 'Yes'
else 'No'
end as isExists
set @count=@count+1
END