For me my issue was that I had two of the same NuGet Packages installed with different Versions.
It is not enough to manually add keys to the Windows certificate store. The certificate only contains the signed public key. You must also import the private key that is associated with the public key in the certificate. A .pfx file contains both public and private keys in a single file. That is what you need to import.
import static java.util.Comparator.naturalOrder;
...
list.stream()
.map(User::getDate)
.max(naturalOrder())
.orElse(null) // replace with .orElseThrow() is the list cannot be empty
It's clumsy, but you can get this from the usage messages for s_client
or s_server
, which are #if
ed at compile time to match the supported protocol versions. Use something like
openssl s_client -help 2>&1 | awk '/-ssl[0-9]|-tls[0-9]/{print $1}'
# in older releases any unknown -option will work; in 1.1.0 must be exactly -help
You can use
<div class="col-sm-12" *ngIf="event.attendees?.length">
Without event.attendees?.length > 0
or even event.attendees?length != 0
Because ?.length
already return boolean value.
If in array will be something it will display it else not.
buildscript {
project.ext {
supportLibVersion = '27.1.1'
compileVersion = 28
minSupportedVersion = 22
}
}
and set dependencies:
implementation "com.android.support:appcompat-v7:$project.supportLibVersion"
A subquery is a select statement that is embedded in a clause of another select statement.
EX:
select ename, sal
from emp where sal > (select sal
from emp where ename ='FORD');
A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.
Ex:
select empno,sal,deptid
from emp e
where sal=(select avg(sal)
from emp where deptid=e.deptid);
DIFFERENCE
The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)
Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)
For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html
Maybe you are looking for Vector
. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList
instead.
You have two options:
Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator
Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator
Right-click on the project and select Validate to make the errors disappear.
Probably best to change the className:
document.getElementById("button").className = 'button_color';
Then you add a buton style to the CSS where you can set the background color and anything else.
As several answer explained the you should run:
npm i
BUT if it does not solve...
Check the version of your npm
executable. (For me it was 3.x.x which doesn't uses the package-lock.json
(at all))
npm -v
It should be at least 5.x.x (which introduced the package-lock.json file.)
To update npm
on Linux, follow these instructions.
For more details about package files, please read this medium story.
And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:
plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))
the plus works just fine, i personally prefer using the concat function.
var s = string.Concat(string 1, string 2, string, 3, etc)
Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:
import readline
for i in range(readline.get_current_history_length()):
print (readline.get_history_item(i + 1))
note the extra ()
(using shell scripts to parse .python_history or using python to modify the above code is a matter of personal taste and situation imho)
This is not an exact duplicate of sprintf
; however, it is similar and more powerful: https://github.com/anywhichway/stringformatter
Format expressions using this library take the form of embedded Javascript objects, e.g.
format("I have {number: {currency: "$", precision:2}}.",50.2);
will return "I have $50.20."
.
I didn't like bhavya's answer because of using AppDelegate
inside View Controllers and setting rootViewController
has no animation. And Trevor's answer has issue with flashing view controller on iOS8.
UPD 07/18/2015
AppDelegate inside View Controllers:
Changing AppDelegate state (properties) inside view controller breaks encapsulation.
Very simple hierarchy of objects in every iOS project:
AppDelegate (owns window
and rootViewController
)
ViewController (owns view
)
It's ok that objects from the top change objects at the bottom, because they are creating them. But it's not ok if objects on the bottom change objects on top of them (I described some basic programming/OOP principle : DIP (Dependency Inversion Principle : high level module must not depend on the low level module, but they should depend on abstractions)).
If any object will change any object in this hierarchy, sooner or later there will be a mess in the code. It might be ok on the small projects but it's no fun to dig through this mess on the bit projects =]
UPD 07/18/2015
I replicate modal controller animations using UINavigationController
(tl;dr: check the project).
I'm using UINavigationController
to present all controllers in my app. Initially I displayed login view controller in navigation stack with plain push/pop animation. Than I decided to change it to modal with minimal changes.
How it works:
Initial view controller (or self.window.rootViewController
) is UINavigationController with ProgressViewController as a rootViewController
. I'm showing ProgressViewController because DataModel can take some time to initialize because it inits core data stack like in this article (I really like this approach).
AppDelegate is responsible for getting login status updates.
DataModel handles user login/logout and AppDelegate is observing it's userLoggedIn
property via KVO. Arguably not the best method to do this but it works for me. (Why KVO is bad, you can check in this or this article (Why Not Use Notifications? part).
ModalDismissAnimator and ModalPresentAnimator are used to customize default push animation.
How animators logic works:
AppDelegate sets itself as a delegate of self.window.rootViewController
(which is UINavigationController).
AppDelegate returns one of animators in -[AppDelegate navigationController:animationControllerForOperation:fromViewController:toViewController:]
if necessary.
Animators implement -transitionDuration:
and -animateTransition:
methods. -[ModalPresentAnimator animateTransition:]
:
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
[[transitionContext containerView] addSubview:toViewController.view];
CGRect frame = toViewController.view.frame;
CGRect toFrame = frame;
frame.origin.y = CGRectGetHeight(frame);
toViewController.view.frame = frame;
[UIView animateWithDuration:[self transitionDuration:transitionContext]
animations:^
{
toViewController.view.frame = toFrame;
} completion:^(BOOL finished)
{
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
}
Test project is here.
It's for validation purposes.
Validation It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a Controller method parameter with the @Valid annotation: After binding incoming POST parameters, the AppointmentForm will be validated; in this case, to verify the date field value is not null and occurs in the future.
Look here for more info:
http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/
Another way is to simply remove collapse navbar-collapse
from the markup. Example with Bootstrap 3.3.7
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<nav class="navbar navbar-atp">_x000D_
<div class="container-fluid">_x000D_
<div class="">_x000D_
<ul class="nav navbar-nav nav-custom">_x000D_
<li>_x000D_
<a href="#" id="sidebar-btn"><span class="fa fa-bars">Toggle btn</span></a>_x000D_
</li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li>Nav item</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>
_x000D_
As stated by Harry Joy, you can do it on the onclick
attr like so:
<input type="button" onclick="func1();func2();" value="Call2Functions" />
Or, in your JS like so:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1();
func2();
};
Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):
var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
func1 = Call2FunctionsEle.onclick;
Call2FunctionsEle.onclick = function()
{
if( typeof func1 === 'function' )
{
func1();
}
func2();
};
If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1.apply( this, arguments );
func2.apply( this, arguments );
};
I have just had all the script variations tested by Pui Cdm, included answers above and many others using php, htaccess, server configuration, and Javascript, the results are that the script
<script type="text/javascript">
function showProtocall() {
if (window.location.protocol != "https") {
window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
window.location.reload();
}
}
showProtocall();
</script>
provided by vivek-srivastava works best and you can add further security in java script.
Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.
Digest Access Authentication uses the hashing methodologies to generate the cryptographic result
Pass the items of the dictionary to the DataFrame constructor, and give the column names. After that parse the Date
column to get Timestamp
values.
Note the difference between python 2.x and 3.x:
In python 2.x:
df = pd.DataFrame(data.items(), columns=['Date', 'DateValue'])
df['Date'] = pd.to_datetime(df['Date'])
In Python 3.x: (requiring an additional 'list')
df = pd.DataFrame(list(data.items()), columns=['Date', 'DateValue'])
df['Date'] = pd.to_datetime(df['Date'])
You can use $(":disabled")
to select all disabled items in the current context.
To determine whether a single item is disabled you can use $("#textbox1").is(":disabled")
.
PowerShell 3 supports this out of the box now.
If you're stuck on PowerShell 2, you basically have to use the legacy net use
command (as suggested earlier).
You can also make an extention method out of Matt Howells. Example.
namespace System
{
public static class MSSystemExtenstions
{
private static Random rng = new Random();
public static void Shuffle<T>(this T[] array)
{
rng = new Random();
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n);
n--;
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
}
Then you can just use it like:
string[] names = new string[] {
"Aaron Moline1",
"Aaron Moline2",
"Aaron Moline3",
"Aaron Moline4",
"Aaron Moline5",
"Aaron Moline6",
"Aaron Moline7",
"Aaron Moline8",
"Aaron Moline9",
};
names.Shuffle<string>();
Your problem is that you have 64-bit eclipse
running but you have 32 bit JRE
.So please download JRE
for 64 bit windows
and let it install on the default location.
Finally add that path till bin in your PATH variable.
Try it should work.
//Off the cuff, Prototype style.
//Note, this is not optimal; there should be some basic partitioning and caching going on.
(function () {
var elements = [];
Element.register = function (element) {
for (var i=0; i<elements.length; i++) {
if (elements[i]==element) break;
}
elements.push(element);
if (arguments.length>1)
for (var i=0; i<arguments.length; i++)
Element.register(arguments[i]);
};
Element.collide = function () {
for (var outer=0; outer < elements.length; outer++) {
var e1 = Object.extend(
$(elements[outer]).positionedOffset(),
$(elements[outer]).getDimensions()
);
for (var inner=outer; inner<elements.length; innter++) {
var e2 = Object.extend(
$(elements[inner]).positionedOffset(),
$(elements[inner]).getDimensions()
);
if (
(e1.left+e1.width)>=e2.left && e1.left<=(e2.left+e2.width) &&
(e1.top+e1.height)>=e2.top && e1.top<=(e2.top+e2.height)
) {
$(elements[inner]).fire(':collision', {element: $(elements[outer])});
$(elements[outer]).fire(':collision', {element: $(elements[inner])});
}
}
}
};
})();
//Usage:
Element.register(myElementA);
Element.register(myElementB);
$(myElementA).observe(':collision', function (ev) {
console.log('Damn, '+ev.memo.element+', that hurt!');
});
//detect collisions every 100ms
setInterval(Element.collide, 100);
Be careful when setting default values on property definition! Do it in constructor instead, to keep it problem-free. If you define it on property definition, then persist the object to the database, then make a partial load, then not loaded properties will again have the default value. That is dangerous if you want to persist the object again.
<Button x:Name="btnBack" Grid.Row="2" Width="300"
Click="btnBack_Click">
<Button.Template>
<ControlTemplate>
<Border CornerRadius="10" Background="#463190">
<TextBlock Text="Retry" Foreground="White"
HorizontalAlignment="Center"
Margin="0,5,0,0"
Height="40"
FontSize="20"></TextBlock>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
This is working fine for me.
Because I always struggle to remember, a quick summary of what each of these do:
>>> pd.Timestamp.now() # naive local time
Timestamp('2019-10-07 10:30:19.428748')
>>> pd.Timestamp.utcnow() # tz aware UTC
Timestamp('2019-10-07 08:30:19.428748+0000', tz='UTC')
>>> pd.Timestamp.now(tz='Europe/Brussels') # tz aware local time
Timestamp('2019-10-07 10:30:19.428748+0200', tz='Europe/Brussels')
>>> pd.Timestamp.now(tz='Europe/Brussels').tz_localize(None) # naive local time
Timestamp('2019-10-07 10:30:19.428748')
>>> pd.Timestamp.now(tz='Europe/Brussels').tz_convert(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
>>> pd.Timestamp.utcnow().tz_localize(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
>>> pd.Timestamp.utcnow().tz_convert(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
In kotlin
print()
The print statement prints everything inside it onto the screen.
The print statements internally call System.out.print
.
println()
The println statement appends a newline at the end of the output.
As the message said, you should set permission as owner to your user. So you can use following:
ALTER AUTHORIZATION
ON DATABASE::[YourDBName]
TO [UserLogin];
Hope helpful! Leave comment if it's ok for you.
string decodedUrl = Uri.UnescapeDataString(url)
or
string decodedUrl = HttpUtility.UrlDecode(url)
Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:
private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}
When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).
Never used the feature but the docs say you can.
public static List<ApplicationInfo> getApplications(Context context) {
return context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
}
Text2Conv="Aa"
for letter in $(echo "$Text2Conv" | sed "s/\(.\)/'\1 /g");do printf '%x' "$letter";done
4161
The trick is using sed to parse the Text2Conv to format we can then seperate anf loop using for.
in my experience. I was using jsp for web. at that time I use mysql 5 and mysql connecter jar 8. So due to the version problem I face this kind of problem. I solve by replace the mysql connector jar file the exact version mysql.
Ideally, every custom watch should be removed when you leave the scope.
It helps in better memory management and better app performance.
// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));
$scope.$on('$destroy', function() {
listener(); // call the de-register function on scope destroy
});
HTML :
<div class="span4">
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
</div>
</div>
CSS :
.panel-height {
height: 100px; / change according to your requirement/
}
Here is my solution which works fine with ajax loaded content too.
/*
* popover handler assigned document (or 'body')
* triggered on hover, show content from data-content or
* ajax loaded from url by using data-remotecontent attribute
*/
$(document).popover({
selector: 'a.preview',
placement: get_popover_placement,
content: get_popover_content,
html: true,
trigger: 'hover'
});
function get_popover_content() {
if ($(this).attr('data-remotecontent')) {
// using remote content, url in $(this).attr('data-remotecontent')
$(this).addClass("loading");
var content = $.ajax({
url: $(this).attr('data-remotecontent'),
type: "GET",
data: $(this).serialize(),
dataType: "html",
async: false,
success: function() {
// just get the response
},
error: function() {
// nothing
}
}).responseText;
var container = $(this).attr('data-rel');
$(this).removeClass("loading");
if (typeof container !== 'undefined') {
// show a specific element such as "#mydetails"
return $(content).find(container);
}
// show the whole page
return content;
}
// show standard popover content
return $(this).attr('data-content');
}
function get_popover_placement(pop, el) {
if ($(el).attr('data-placement')) {
return $(el).attr('data-placement');
}
// find out the best placement
// ... cut ...
return 'left';
}
If you want to merge changes in SubBranch to MainBranch
git checkout MainBranch
git merge SubBranch
With the React Devtools installed you can run this from the browser console:
__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.forEach(r => console.log(`${r.rendererPackageName}: ${r.version}`))
Which outputs something like:
react-dom: 16.12.0
I had problems closing the bootstrap modal dialog, if it was opened with:
$('#myModal').modal('show');
I solved this problem opening the dialog by the following link:
<a href="#myModal" data-toggle="modal">Open my dialog</a>
Do not forget the initialization:
$('#myModal').modal({show: false});
I also used the following attributes for the closing button:
data-dismiss="modal" data-target="#myModal"
I noticed that the answers here are using: device-width
, device-height
, min-device-width
, min-device-height
, max-device-width
, max-device-height
.
Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width
, max-width
and so on. For extra assurance, you can set the min and max to the same px amount.
For example:
iPhone X
@media only screen
and (width : 375px)
and (height : 635px)
and (orientation : portrait)
and (-webkit-device-pixel-ratio : 3) { }
You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight
. Here are a few useful links on this subject:
Use tuple unpacking:
>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
... print a, b
...
a 1
b 2
c 3
See also: Tuple unpacking in for loops.
To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:
$ rm -rf .git
Or to delete .gitignore and .gitmodules if any (via @aragaer):
$ rm -rf .git*
Then from the same ex-repository folder, to see if hidden folder .git is still there:
$ ls -lah
If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).
To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
Source: http://lifehacker.com/188892/show-hidden-files-in-finder.
No need to use str.replace
or string.replace
here, just convert that string to a raw string:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
Below is the repr
version of the above string, that's why you're seeing \\
here.
But, in fact the actual string contains just '\'
not \\
.
>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'
>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3
But when you're going to print this string you'll not get '\\'
in the output.
>>> print strs
C:\Users\Josh\Desktop\20130216
If you want the string to show '\\'
during print
then use str.replace
:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
repr
version will now show \\\\
:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
You may use trick in unix/linux environment:
in gnuplot program: plot "/dev/stdin" ...
In command line: gnuplot program.plot < data.dat
the style is:
<style type="text/css">
.topcorner{
position:absolute;
top:0;
right:0;
}
</style>
hope it will work. Thanks
Reposting this here for others from the requests issue page:
Requests' does not support doing this before version 1. Subsequent to version 1, you are expected to subclass the HTTPAdapter, like so:
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
import ssl
class MyAdapter(HTTPAdapter):
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=ssl.PROTOCOL_TLSv1)
When you've done that, you can do this:
import requests
s = requests.Session()
s.mount('https://', MyAdapter())
Any request through that session object will then use TLSv1.
Giphy Gotcha
After following the 2 requirements listed above (must end in .gif
and using the image syntax), if you are having trouble with a gif from giphy:
Be sure you have the correct giphy url! You can't just add .gif
to the end of this one and have it work.
If you just copy the url from a browser, you will get something like:
https://giphy.com/gifs/gol-automaton-game-of-life-QfsvYoBSSpfbtFJIVo
You need to instead click on "Copy Link" and then grab the "GIF Link" specifically. Notice the correct one points to media.giphy.com
instead of just giphy.com
:
[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);
int main(int argc, char *argv[]){
DIR *dip;
struct dirent *dit;
struct stat statbuf;
char currentPath[FILENAME_MAX];
int depth = 0; /*Used to correctly space output*/
/*Open Current Directory*/
if((dip = opendir(".")) == NULL)
return errno;
/*Store Current Working Directory in currentPath*/
if((getcwd(currentPath, FILENAME_MAX)) == NULL)
return errno;
/*Read all items in directory*/
while((dit = readdir(dip)) != NULL){
/*Skips . and ..*/
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
/*Correctly forms the path for stat and then resets it for rest of algorithm*/
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
if(stat(currentPath, &statbuf) == -1){
perror("stat");
return errno;
}
getcwd(currentPath, FILENAME_MAX);
/*Checks if current item is of the type file (type 8) and no command line arguments*/
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*If a command line argument is given, checks for filename match*/
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
if(strcmp(dit->d_name, argv[1]) == 0)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*Checks if current item is of the type directory (type 4)*/
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
closedir(dip);
return 0;
}
/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
if((dip = opendir(currentPath)) == NULL)
printf("Error: Failed to open Directory ==> %s\n", currentPath);
while((dit = readdir(dip)) != NULL){
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
stat(currentPath, &statbuf);
getcwd(currentPath, FILENAME_MAX);
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
if(strcmp(dit->d_name, argv[1]) == 0){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
}
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
/*Changing back here is necessary because of how stat is done*/
chdir("..");
closedir(dip);
}
void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
/*If two directories exist at the same level the path
is built wrong and needs to be corrected*/
if((chdir(currentPath)) == -1){
chdir("..");
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
for(i = 0; i < depth; i++)
printf (" ");
printf("%s (subdirectory)\n", dit->d_name);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
else{
for(i =0; i < depth; i++)
printf(" ");
printf("%s (subdirectory)\n", dit->d_name);
chdir(currentPath);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
}
Yes. The windows-kill
project does exactly what you want:
windows-kill -SIGINT 1234
Best way to do this is
int i = 3;
Double d = i * 1.0;
d is 3.0 now.
I'm having the same issue here and I was a bit afraid of checking the last box, since I have no idea what the 3rd party SDK will do with the data collected and if they will respect the Limit Ad Settings.
But I found a post by a Google Admob programmer, Eric Leichtenschlag, on their forums:
The Google Mobile Ads SDK and the Google Conversion Tracking SDK utilize Apple's advertising identifier introduced in iOS 6 (IDFA). While each developer is responsible for how they access device data, the SDKs use IDFA under the guidelines laid out in the iOS developer program license agreement, including Limit Ad Tracking.
Including Limit Ad Tracking. This is what the last box is all about. So you must check the that box if you use AdMob. If you use other SDK I strongly recommend checking if they respect the guidelines as well.
Since I run only ads (Google AdMob), I checked the first (Serve ads...) and last box (I, ___, confirm...). App was approved and released, no issues.
Source: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk
change_column_default :employees, :foreign, false
datagridview1.Rows[0].HeaderCell.Value = "Your text";
It works.
Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
Based on this HTML5 Doctor diagram, I'm thinking this may be the best markup:
<aside class="sidebar">
<article id="widget_1" class="widget">...</article>
<article id="widget_2" class="widget">...</article>
<article id="widget_3" class="widget">...</article>
</aside> <!-- end .sidebar -->
I think it's clear that <aside>
is the appropriate element as long as it's outside the main <article>
element.
Now, I'm thinking that <article>
is also appropriate for each widget in the aside. In the words of the W3C:
The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
I assume from db
that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);
Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).
For a trivial example of the type of thing you can do:
select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };
You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...
To remove a remote:
git remote remove origin
To add a remote:
git remote add origin yourRemoteUrl
and finally
git push -u origin master
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
?
Try
SELECT * FROM Profiles WHERE date(DateReg)=$date
where $date is in yyyy-mm-dd
Alternatively
SELECT * FROM Profiles WHERE left(DateReg,10)=$date
Cheers
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break
is up there with the while
), you could create a variable result = None
and loop while it is None
. You should also adjust the variables and you can replace continue
with the semantically perhaps correct pass
(you don't care if an error occurs, you just want to ignore it) and drop the break
- this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except:
clauses are evil for reasons given in the documentation.
Example incorporating all of the above:
result = None
while result is None:
try:
# connect
result = get_data(...)
except:
pass
# other code that uses result but is not involved in getting it
#mydiv:before {
content: url("data:image/svg+xml; utf8, <svg.. code here</svg>");
display:block;
width:22px;
height:10px;
margin:10px 5px 0 10px;
}
make sure your svg doesn't contain double quotes, and uriencode any # symbols.
If you are sending alphanumeric data try changing
'Content-Type': 'multipart/form-data'
to
'Content-Type': 'application/x-www-form-urlencoded'
If you are sending non-alphanumeric data try to remove 'Content-Type' at all.
If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)
For ListView or GridView there is an another difference, when visibility initially set to
INVISIBLE:
Adapter's getView() function called
GONE:
Adapter's getView() function didn't call, thus preventing views to load, when it is unnecessary
Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element
or null
. Properties without can return any other kind of node.
console.log(document.body.parentNode, "is body's parent node"); // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>
var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null
To create a model that references another, use the Ruby on Rails model generator:
$ rails g model wheel car:references
That produces app/models/wheel.rb:
class Wheel < ActiveRecord::Base
belongs_to :car
end
And adds the following migration:
class CreateWheels < ActiveRecord::Migration
def self.up
create_table :wheels do |t|
t.references :car
t.timestamps
end
end
def self.down
drop_table :wheels
end
end
When you run the migration, the following will end up in your db/schema.rb:
$ rake db:migrate
create_table "wheels", :force => true do |t|
t.integer "car_id"
t.datetime "created_at"
t.datetime "updated_at"
end
As for documentation, a starting point for rails generators is Ruby on Rails: A Guide to The Rails Command Line which points you to API Documentation for more about available field types.
At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):
// You can keep this in your filters.php file
App::before(function($request) {
App::singleton('site_settings', function(){
return Setting::all();
});
// If you use this line of code then it'll be available in any view
// as $site_settings but you may also use app('site_settings') as well
View::share('site_settings', app('site_settings'));
});
To get the same data in any controller you may use:
$site_settings = app('site_settings');
There are many ways, just use one or another, which one you prefer but I'm using the Container
.
There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines()
, eg) for use.
If your website was running fine and now unexpected ERROR: (HY000/2002): No such file or directory
Then you should NOT CHANGE any configuration file!
First check server error.log file, for Nginx it's located:
/var/log/nginx/error.log
Or for Apache try:
/var/log/apache2/error_log
In my case I could see PHP Fatal error: OUT OF MEMORY in error.log for nginx.
The solution: Add more RAM to server.
I tried to reboot the web server first before upgrading/adding RAM.
Then I got rid of ERROR (HY000/2002) but got some ERROR 50X: Connection Error...
At this point I added 2GB RAM, rebooted the web server and all was working fine!
When the web server was up I noticed 200+ cron-jobs was stuck due to a loop bug in 1 PHP script.
So check which script is consuming memory.
Here is an example which gets big numbers very quickly.
import java.math.BigInteger;
/*
250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
Time to compute: 3.5 seconds.
1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
Time to compute: 58.1 seconds.
*/
public class Main {
public static void main(String... args) {
int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
long start = System.nanoTime();
BigInteger fibNumber = fib(place);
long time = System.nanoTime() - start;
System.out.println(place + "th fib # is: " + fibNumber);
System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
}
private static BigInteger fib(int place) {
BigInteger a = new BigInteger("0");
BigInteger b = new BigInteger("1");
while (place-- > 1) {
BigInteger t = b;
b = a.add(b);
a = t;
}
return b;
}
}
If You have Legacy Cordova framework having issues with NPM and Cordova command. I would suggest the below option.
Create file android/res/xml/network_security_config.xml -
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
</domain-config>
</network-security-config>
AndroidManifest.xml -
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...>
...
</application>
</manifest>
It sounds like that if you request faq.html
the webserver signals your browser that the file is in UTF-8 encoding.
Check that with your browser which encoding is announced and used, please see the documentation of your browser how to do that. Every browser has this, most often accessible via the menu (to specify your preference which website's encoding should be used) and to see what the server returned, you often find this in page properties.
Then it sounds like that if you request faq.php
the webserver singals your browser that the file is in some other encoding. Probably no charset/encoding is given as per default PHP configuration setting. As it's a PHP file you can most often solve this by changing the PHP configuration default_charset
Docs directive:
default_charset = "UTF-8"
Locate your php.ini on the host and edit it accordingly.
If you don't have the php.ini available, you can change this by code as well by using the ini_set
Docs function:
ini_set('default_charset', 'UTF-8');
Take care that you change this very early in your script because PHP needs to be able to send out headers to have this working, and headers can't be set any longer if they have already been send.
Manually sending the Content-Type
header-line does work, too:
header('Content-Type: text/html; charset=UTF-8');
Additionally it's good practice that all the HTML pages you output have this header as well in their HTML <head>
section:
<html>
<head>
...
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
...
Hope this is helpful.
You're looking for Select
which can be used to transform\project the input sequence:
IEnumerable<string> strings = integers.Select(i => i.ToString());
This is the simplest way to plot an ROC curve, given a set of ground truth labels and predicted probabilities. Best part is, it plots the ROC curve for ALL classes, so you get multiple neat-looking curves as well
import scikitplot as skplt
import matplotlib.pyplot as plt
y_true = # ground truth labels
y_probas = # predicted probabilities generated by sklearn classifier
skplt.metrics.plot_roc_curve(y_true, y_probas)
plt.show()
Here's a sample curve generated by plot_roc_curve. I used the sample digits dataset from scikit-learn so there are 10 classes. Notice that one ROC curve is plotted for each class.
Disclaimer: Note that this uses the scikit-plot library, which I built.
JSch is a nice library to work with. It has quite an easy answer for your question.
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
session.connect();
boolean ptimestamp = true;
// exec 'scp -t rfile' remotely
String command="scp " + (ptimestamp ? "-p" :"") +" -t "+rfile;
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out=channel.getOutputStream();
InputStream in=channel.getInputStream();
channel.connect();
if(checkAck(in)!=0){
System.exit(0);
}
File _lfile = new File(lfile);
if(ptimestamp){
command="T "+(_lfile.lastModified()/1000)+" 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command+=(" "+(_lfile.lastModified()/1000)+" 0\n");
out.write(command.getBytes()); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
}
You can find complete code at
http://faisalbhagat.blogspot.com/2013/09/java-uploading-file-remotely-via-scp.html
This is the conditional operator expression.
(condition) ? [true path] : [false path];
For example
string value = someBooleanExpression ? "Alpha" : "Beta";
So if the boolean expression is true, value will hold "Alpha", otherwise, it holds "Beta".
For a common pitfall that people fall into, see this question in the C# tag wiki.
DELETE t1
FROM Table1 t1
JOIN Table2 t2 ON t1.ID = t2.ID;
I always use the alias in the delete statement as it prevents the accidental
DELETE Table1
caused when failing to highlight the whole query before running it.
The original code you suggest is the best way.
Matlab is extremely good at vectorized operations such as this, at least for large vectors.
The built-in norm function is very fast. Here are some timing results:
V = rand(10000000,1);
% Run once
tic; V1=V/norm(V); toc % result: 0.228273s
tic; V2=V/sqrt(sum(V.*V)); toc % result: 0.325161s
tic; V1=V/norm(V); toc % result: 0.218892s
V1 is calculated a second time here just to make sure there are no important cache penalties on the first call.
Timing information here was produced with R2008a x64 on Windows.
EDIT:
Revised answer based on gnovice's suggestions (see comments). Matrix math (barely) wins:
clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V); end; toc % 6.3 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 9.3 s
tic; for i=1:N, V3 = V/sqrt(V'*V); end; toc % 6.2 s ***
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 9.2 s
tic; for i=1:N, V1=V/norm(V); end; toc % 6.4 s
IMHO, the difference between "norm(V)" and "sqrt(V'*V)" is small enough that for most programs, it's best to go with the one that's more clear. To me, "norm(V)" is clearer and easier to read, but "sqrt(V'*V)" is still idiomatic in Matlab.
The #!
line tells the kernel (specifically, the implementation of the execve
system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46
(^?ELF) that identifies them as such.
You can put an absolute path to any program you want after the #!
, as long as that program is not itself a #!
script. The kernel rewrites an invocation of
./script arg1 arg2 arg3 ...
where ./script
starts with, say, #! /usr/bin/perl
, as if the command line had actually been
/usr/bin/perl ./script arg1 arg2 arg3
Or, as you have seen, you can use #! /bin/sh
to write a script intended to be interpreted by sh
.
The #!
line is only processed if you directly invoke the script (./script
on the command line); the file must also be executable (chmod +x script
). If you do sh ./script
the #!
line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/*
-- you will discover that a great many stock programs are in fact using this feature.)
Here are some rules for using this feature:
#!
must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #!
script.#!
must be an absolute path (starts with /
). It cannot contain space, tab, or newline characters.#!
and the /
. Do not put more than one space there.#!
line, they will not be expanded.#! /usr/bin/awk -f
), sometimes it's just useful (#! /usr/bin/perl -Tw
). Unfortunately, you cannot put two or more arguments after the absolute path.#! /usr/bin/env interpreter
instead of #! /absolute/path/to/interpreter
. This is almost always a mistake. It makes your program's behavior depend on the $PATH
variable of the user who invokes the script. And not all systems have env
in the first place.setuid
or setgid
privileges can't use #!
; they have to be compiled to machine code. (If you don't know what setuid
is, don't worry about this.)Regarding csh
, it relates to sh
roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh
have caught up) a number of advantages over sh
for interactive usage, but using it (or its descendant tcsh
) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh
. If you are using a csh
relative as your login shell, switch to bash
or zsh
, so that the interactive command language will be the same as the scripting language you're learning.
An easier way to do this in the current stable version (1.0.6) requires a lot less code.
After setting up your module add a factory:
var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
// route setups
});
app.factory('MyCache', function ($cacheFactory) {
return $cacheFactory('myCache');
});
Now you can pass this into your controller:
app.controller('MyController', function ($scope, $http, MyCache) {
$http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
// stuff with results
});
});
One downside is that the key names are also setup automatically, which could make clearing them tricky. Hopefully they'll add in some way to get key names.
Setting remote repository URL worked for me:
git remote set-url origin https://github.com/path-to-repo/MyRepo.git
It works for me:
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Edit:
If above hard-coded sdcard directory is not working in your case, you can fetch the sdcard path:
String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new File(sdcardPath);
On param change reload page won't happen. This is really good feature. There is no need to reload the page but we should change the value of the component. paramChange method will call on url change. So we can update the component data
/product/: id / details
import { ActivatedRoute, Params, Router } from ‘@angular/router’;
export class ProductDetailsComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) {
this.route.params.subscribe(params => {
this.paramsChange(params.id);
});
}
// Call this method on page change
ngOnInit() {
}
// Call this method on change of the param
paramsChange(id) {
}
If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.
I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.
Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber>
@pcs.rogers.com
will be immediately delivered to your Rogers/Chatr phone as a text message.
* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.
There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.
.VBS
extension, such as TextMyself.vbs
. That's all!
Just double-click the file to send a test message, or else run it from a batch file using START
.
Sub SendMessage()
Const EmailToSMSAddy = "[email protected]"
Dim objOutlookRecip
With CreateObject("Outlook.Application").CreateItem(0)
Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
objOutlookRecip.Type = 1
.Subject = "The computer needs your attention!"
.Body = "Go see why Windows Command Line is texting you!"
.Save
.Send
End With
End Sub
START x:\mypath\TextMyself.vbs
Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.
I got this error when loading '|' separated CSV file although there were no '"' characters in my input file. It turned out that I forgot to specify FORMAT:
COPY ... FROM ... WITH (FORMAT CSV, DELIMITER '|').
Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST
function nextImage (){
url = url + 1;
location.href='http://mywebsite.com/' + url+'.html';
}
Full answer to give you jquery and bootstrap since jquery is a requirement for bootstrap.js:
Install jquery and bootstrap into node_modules:
npm install bootstrap
npm install jquery
Import in your components using this exact filepath:
import 'jquery/src/jquery'; //for bootstrap.min.js
//bootstrap-theme file for bootstrap 3 only
import 'bootstrap/dist/css/bootstrap-theme.min.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
I prefer going the long route. These are the checks I follow to avoid using a try-except clause -
Here, DATA
is the suspect variable -
DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty
You have to use GetThumbnailImage
method in the Image
class:
https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx
Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.
Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));
It is in the System.Drawing namespace (in System.Drawing.dll).
Behavior:
If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.
Important: the remarks section of the Microsoft link above warns of certain potential problems:
The
GetThumbnailImage
method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the
DrawImage
method.
It allows you to read from the standard input (mainly, the console). This SO question may helps you.
It is important to define an id in the model
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Model(model => model.Id(p => p.id))
)
The first is not working of course. The controls on a form are private, visible only for that form by design.
To make it all public is also not the best way.
If I would like to expose something to the outer world (which also can mean an another form), I make a public property for it.
public Boolean nameOfControlVisible
{
get { return this.nameOfControl.Visible; }
set { this.nameOfControl.Visible = value; }
}
You can use this public property to hide or show the control or to ask the control current visibility property:
otherForm.nameOfControlVisible = true;
You can also expose full controls, but I think it is too much, you should make visible only the properties you really want to use from outside the current form.
public ControlType nameOfControlP
{
get { return this.nameOfControl; }
set { this.nameOfControl = value; }
}
you can use toggleClass()
to toggle class it is really handy.
case:1
<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>
case:2
<div id='mydiv' class="class2"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class1"></div>
case:3
<div id='mydiv' class="class1 class2 class3"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class3"></div>
You are close :o) Spring 3.0 adds Spring Expression Language. You can use
<util:properties id="dbProperties"
location="classpath:config_#{systemProperties['env']}/db.properties" />
Combined with java ... -Denv=QA
should solve your problem.
Note also a comment by @yiling:
In order to access system environment variable, that is OS level variables as amoe commented, we can simply use "systemEnvironment" instead of "systemProperties" in that EL. Like
#{systemEnvironment['ENV_VARIABLE_NAME']}
EDIT: As of ~March 2016, Microsoft offers a C/C++ extension for Visual Studio Code and therefor the answer I originally gave is no longer valid.
Visual Studio Code doesn't support C/C++ very well. As such it doesn't >naturally support gcc or gdb within the Visual Studio Code application. The most it will do is syntax highlighting, the advanced features like >intellisense aren't supported with C. You can still compile and debug code >that you wrote in VSC, but you'll need to do that outside the program itself.
The following method worked for me. This approach allowed me to test some code that should work both in the browser and in Node.js, as it allowed me to set window
to undefined
.
This was with Jest 24.8 (I believe):
let windowSpy;
beforeEach(() => {
windowSpy = jest.spyOn(window, "window", "get");
});
afterEach(() => {
windowSpy.mockRestore();
});
it('should return https://example.com', () => {
windowSpy.mockImplementation(() => ({
location: {
origin: "https://example.com"
}
}));
expect(window.location.origin).toEqual("https://example.com");
});
it('should be undefined.', () => {
windowSpy.mockImplementation(() => undefined);
expect(window).toBeUndefined();
});
Just in case someone is interest only in what kind of process created the shared moeries, call
ls -l /dev/shm
It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.
SELECT t1.credit,
t2.debit
FROM (SELECT Sum(c.total_amount) AS credit
FROM credit c
WHERE c.status = "a") AS t1,
(SELECT Sum(d.total_amount) AS debit
FROM debit d
WHERE d.status = "a") AS t2
For Intellij IDEA version 11.0.2
File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Next goto Build | Build artifacts --> choose your artifact.
source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/
Take a look at https://www.json.org
[edited] Imagine that you have a simple Java class like this:
public class Person {
private String name;
private Integer age;
public String getName() { return this.name; }
public void setName( String name ) { this.name = name; }
public Integer getAge() { return this.age; }
public void setAge( Integer age ) { this.age = age; }
}
So, to transform it to a JSon object, it's very simple. Like this:
import org.json.JSONObject;
public class JsonTest {
public static void main( String[] args ) {
Person person = new Person();
person.setName( "Person Name" );
person.setAge( 333 );
JSONObject jsonObj = new JSONObject( person );
System.out.println( jsonObj );
}
}
Hope it helps.
[edited] Here there is other example, in this case using Jackson: https://brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/
Maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.1</version>
</dependency>
And a link (below) to find the latest/greatest version:
I think it's pretty well covered by the answers above that String args[]
is simply an array of string arguments you can pass to your application when you run it. For completion, I might add that it's also valid to define the method parameter passed to the main
method as a variable argument (varargs) of type String:
public static void main (String... args)
In other words, the main
method must accept either a String array (String args[]
) or varargs (String... args
) as a method argument. And there is no magic with the name args
either. You might as well write arguments
or even freddiefujiwara
as shown in below e.gs.:
public static void main (String[] arguments)
public static void main (String[] freddiefujiwara)
My requirements were a bit different than the ones asked on the original question, but hopefully I might help someone who is going through the same problem that I was..
I had to define if a field was required or not based on a scope variable.. So I basically had to set ng-required="myScopeVariable"
(which is a boolean variable).
<div class="align-left" ng-repeat="schema in schemas">
<input type="text" ng-required="schema.Required" />
</div>
How about using <input type="number"...>
?
http://www.w3schools.com/tags/tag_input.asp
Also, here is a question that has some examples of using Javascript for validation.
Update: linked to better question (thanks alexblum).
There are two events on client side as given below.
1. window.onbeforeunload (calls on Browser/tab Close & Page Load)
2. window.onload (calls on Page Load)
On server Side
public JsonResult TestAjax( string IsRefresh)
{
JsonResult result = new JsonResult();
return result = Json("Called", JsonRequestBehavior.AllowGet);
}
On Client Side
<script type="text/javascript">_x000D_
window.onbeforeunload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: { IsRefresh: 'Close' }_x000D_
});_x000D_
};_x000D_
_x000D_
window.onload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: {IsRefresh:'Load'}_x000D_
});_x000D_
};_x000D_
</script>
_x000D_
On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".
On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.
ReactJS component based on the selected answer:
import React from 'react';
const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => {
const angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
};
const describeSlice = (x, y, radius, startAngle, endAngle) => {
const start = polarToCartesian(x, y, radius, endAngle);
const end = polarToCartesian(x, y, radius, startAngle);
const largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";
const d = [
"M", 0, 0, start.x, start.y,
"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
].join(" ");
return d;
};
const path = (degrees = 90, radius = 10) => {
return describeSlice(0, 0, radius, 0, degrees) + 'Z';
};
export const Arc = (props) => <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
<g transform="translate(150,150)" stroke="#000" strokeWidth="2">
<path d={path(props.degrees, props.radius)} fill="#333"/>
</g>
</svg>;
export default Arc;
Regarding Chrome, checkout the monitorEvents() via the command line API.
Open the console via Menu > Tools > JavaScript Console.
Enter monitorEvents(window);
View the console flooded with events
...
mousemove MouseEvent {dataTransfer: ...}
mouseout MouseEvent {dataTransfer: ...}
mouseover MouseEvent {dataTransfer: ...}
change Event {clipboardData: ...}
...
There are other examples in the documentation. I'm guessing this feature was added after the previous answer.
If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.
javascript:
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 30000);
</script>
Go to view
, then appearence
. Then select move panel bottom.
Try the below:
pod deintegrate
pod install
Or, One-Liner:
pod deintegrate; pod install
The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)
For your query, this would be:
SELECT *
FROM courses
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time
Or,
SELECT *
FROM courses
WHERE ADDTIME(now(), '02:00:00') > start_time
Easier solution for wamp is: go to phpMyAdmin, click localhost, select latin1_bin for Server connection collation, then start to create database and table
you can mix between glob() function & pathinfo() function like below.
the below code will show files information for specific extension "pdf"
foreach ( glob("*.pdf") as $file ) {
$file_info = pathinfo( getcwd().'/'.$file );
echo $file_info['dirname'], "<br>";
echo $file_info['basename'], "<br>";
echo $file_info['extension'], "<br>";
echo $file_info['filename'], "<br>";
echo '<hr>';
}
IntelliJ IDEA seems to have reorganized the configurations panel. Now one should go to Editor -> Color Scheme and click on the gears icon to import the theme they want from external .jar
files.
Editing the config.ini
file with
osgi.instance.area.default=\D:\\Projects\\Eclipse Workspace\\
worked for me.
The console is no extra window anymore but it is under the texteditor area. You can set the preferences to always show this area. Go to "General" "Run Start" and activate "Show Debugger". Under "Run completes" the Debugger is set to hide again. You should deactivate that option. Now the console will remain visible.
EDIT
In the latest GM Release you can show and hide the console via a button in the toolbar. Very easy.
You can simply do this
$data += array($category => $question);
If your're running on php 5.4+
$data += [$category => $question];
Isn't this the path you are looking for?
C:\Program Files\nodejs\node_modules\npm\npmrc
I know that npm outputs that , but the global folder is the folder where node.js is installed and all the modules are.
You could use:
echo date('F Y', strtotime('20130814'));
which should do the trick.
Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.
The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:
if (typeof(value) !== "undefined" && value)
or
if (typeof value !== "undefined" && value)
^(?=.{1,253}\.?$)(?:(?!-|[^.]+_)[A-Za-z0-9-_]{1,63}(?<!-)(?:\.|$)){2,}$
It is basically mkyong's answer and additionally:
Lookahead, limit max length between ^$ to 253 characters with optional trailing literal '.'
(?=.{1,253}\.?$)
Lookahead, next character is not a '-' and no '_' follows any characters before the next '.'. That is to say, enforce that the first character of a label isn't a '-' and only the first character may be a '_'.
(?!-|[^.]+_)
Between 1 and 63 of the allowed characters per label.
[A-Za-z0-9-_]{1,63}
Lookbehind, previous character not '-'. That is to say, enforce that the last character of a label isn't a '-'.
(?<!-)
Force a '.' at the end of every label except the last, where it is optional.
(?:\.|$)
Mostly combined from above, this requires at least two domain levels, which is not quite correct, but usually a reasonable assumption. Change from {2,} to + if you want to allow TLDs or unqualified relative subdomains through (eg, localhost, myrouter, to.)
(?:(?!-|[^.]+_)[A-Za-z0-9-_]{1,63}(?<!-)(?:\.|$)){2,}
Unit tests for this expression.
Using pathlib and preserving full path:
from pathlib import Path
p = Path('/User/my/path')
new_p = Path(p.parent.as_posix() + '/' + p.stem + '.aln')
var elementCheckBox = document.getElementById("IdOfCheckBox");_x000D_
_x000D_
_x000D_
elementCheckBox[0].checked //return true if checked and false if not checked
_x000D_
thanks
test -z
returns true if the parameter is empty (see man sh
or man test
).
WARNING: operating on strings alone will only work with ASCII and will count wrong when input is a non-ASCII UTF-8 encoded character, and will probably even corrupt characters since it cuts multibyte chars mid-sequence.
Here's a UTF-8-aware version:
// NOTE: this isn't multi-Unicode-codepoint aware, like specifying skintone or
// gender of an emoji: https://unicode.org/emoji/charts/full-emoji-modifiers.html
func substr(input string, start int, length int) string {
asRunes := []rune(input)
if start >= len(asRunes) {
return ""
}
if start+length > len(asRunes) {
length = len(asRunes) - start
}
return string(asRunes[start : start+length])
}
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.
When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.
By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790
So the solution is:
class UserVerification extends Model
{
protected $primaryKey = 'your_key_name'; // or null
public $incrementing = false;
// In Laravel 6.0+ make sure to also set $keyType
protected $keyType = 'string';
}
Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.
All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.
There are many clients you can use to install a Let's Encrypt certificate:
Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/
input[type='text'], input[type='password']
{
// my css
}
That is the correct way to do it. Sadly CSS is not a programming language.
Using the rowid()
function in data.table
:
> set.seed(100)
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]
> df$num <- data.table::rowid(df$cat)
> df
cat val num
4 aaa 0.05638315 1
2 aaa 0.25767250 2
1 aaa 0.30776611 3
5 aaa 0.46854928 4
3 aaa 0.55232243 5
10 bbb 0.17026205 1
8 bbb 0.37032054 2
6 bbb 0.48377074 3
9 bbb 0.54655860 4
7 bbb 0.81240262 5
13 ccc 0.28035384 1
14 ccc 0.39848790 2
11 ccc 0.62499648 3
15 ccc 0.76255108 4
12 ccc 0.88216552 5
The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).
Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.
OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.
Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.
Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...
Converting to double can be done by casting an int to a double:
You can convert an int to a double by using this mechnism like so:
int i = 3; // i is 3
double d = (double) i; // d = 3.0
Alternative (using Java's automatic type recognition):
double d = 1.0 * i; // d = 3.0
Implementing this in your code would be something like:
double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));
Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:
double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));
Good luck.
Add multiple classes:
$("p").addClass("class1 class2 class3");
or in cascade:
$("p").addClass("class1").addClass("class2").addClass("class3");
Very similar also to remove more classes:
$("p").removeClass("class1 class2 class3");
or in cascade:
$("p").removeClass("class1").removeClass("class2").removeClass("class3");
As of Matplotlib 2.0, there is a reversed()
method for ListedColormap
and LinearSegmentedColorMap
objects, so you can just do
cmap_reversed = cmap.reversed()
Here is the documentation.
Try this:
df.loc[len(df)]=['8/19/2014','Jun','Fly','98765']
Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.
In versions pre-G++ 4.7, you'll have to use -std=c++0x
, for more recent versions you can use -std=c++11
.
I had a problem because my canvas was inside of a container without ID so I used this jquery code below
$('.cropArea canvas').width()
If you have several specific properties that you want to transition in the same way (because you also have some properties you specifically don't want to transition, say opacity
), another option is to do something like this (prefixes omitted for brevity):
.myclass {
transition: all 200ms ease;
transition-property: box-shadow, height, width, background, font-size;
}
The second declaration overrides the all
in the shorthand declaration above it and makes for (occasionally) more concise code.
/* prefixes omitted for brevity */_x000D_
.box {_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
background: red;_x000D_
box-shadow: red 0 0 5px 1px;_x000D_
transition: all 500ms ease;_x000D_
/*note: not transitioning width */_x000D_
transition-property: height, background, box-shadow;_x000D_
}_x000D_
_x000D_
.box:hover {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
box-shadow: blue 0 0 10px 3px;_x000D_
background: blue;_x000D_
}
_x000D_
<p>Hover box for demo</p>_x000D_
<div class="box"></div>
_x000D_
I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:
#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file
This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/
and placing a wildcard in place of the_original_line
.
Go to http://nodejs.org and download and run the installer. It works now - for me at least.
For example, if you want an array of int
pointers it will be int* a[10]
. It means that variable a
is a collection of 10 int*
s.
EDIT
I guess this is what you want to do:
class Bar
{
};
class Foo
{
public:
//Takes number of bar elements in the pointer array
Foo(int size_in);
~Foo();
void add(Bar& bar);
private:
//Pointer to bar array
Bar** m_pBarArr;
//Current fee bar index
int m_index;
};
Foo::Foo(int size_in) : m_index(0)
{
//Allocate memory for the array of bar pointers
m_pBarArr = new Bar*[size_in];
}
Foo::~Foo()
{
//Notice delete[] and not delete
delete[] m_pBarArr;
m_pBarArr = NULL;
}
void Foo::add(Bar &bar)
{
//Store the pointer into the array.
//This is dangerous, you are assuming that bar object
//is valid even when you try to use it
m_pBarArr[m_index++] = &bar;
}
In simpler words:
key=
parameter of sort
requires a key function (to be applied to be objects to be sorted) rather than a single key value and operator.itemgetter(1)
will give you: A function that grabs the first item from a list-like object. (More precisely those are callables, not functions, but that is a difference that can often be ignored.)
Our team use Visual Paradigm to generate ER diagram from database in many of our projects. While we mainly work on MS SQL and Oracle, as I know they also support some other DBMS like PostgreSQL, MySQL, Sybase, DB2 and SQLite.
Steps:
BTW they also support generating and updating database schema from ERD.
Hope this helps. :-)
More information about generating ERD from PostgreSQL database
Edit: the api call has been removed by google. so it is no longer functioning.
Agree with Pareshkumar's answer. Now there is a python wrapper googlefinance for the url call.
Install googlefinance
$pip install googlefinance
It is easy to get current stock price:
>>> from googlefinance import getQuotes
>>> import json
>>> print json.dumps(getQuotes('AAPL'), indent=2)
[
{
"Index": "NASDAQ",
"LastTradeWithCurrency": "129.09",
"LastTradeDateTime": "2015-03-02T16:04:29Z",
"LastTradePrice": "129.09",
"Yield": "1.46",
"LastTradeTime": "4:04PM EST",
"LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
"Dividend": "0.47",
"StockSymbol": "AAPL",
"ID": "22144"
}
]
Google finance is a source that provides real-time stock data. There are also other APIs from yahoo, such as yahoo-finance, but they are delayed by 15min for NYSE and NASDAQ stocks.
There is no need to pass anything to ffmpeg
you can just grab the desired format, in this example, it was the "95" format.
So once you know that it is the 95, you just type:
youtube-dl -f 95 https://www.youtube.com/watch\?v\=6aXR-SL5L2o
that is to say:
youtube-dl -f <format number> <url>
It will begin generating on the working directory a <somename>.<probably mp4>.part
which is the partially downloaded file, let it go and just press <Ctrl-C>
to stop the capture.
The file will still be named <something>.part
, rename it to <whatever>.mp4
and there it is...
The ffmpeg
code:
ffmpeg -i $(youtube-dl -f <format number> -g <url>) -copy <file_name>.ts
also worked for me, but sound and video got out of sync, using just youtube-dl
seemed to yield a better result although it too uses ffmpeg
.
The downside of this approach is that you cannot watch the video while downloading, well you can open yet another FF or Chrome, but it seems that mplayer
cannot process the video output till youtube-dl
/ffmpeg
are running.
To disable a warning locally in a block, add
# pylint: disable=C0321
to that block.
VSCode can now support debugging PHP projects through the marketplace extension vscode-php-debug.
This extension uses XDebug in the background, and allows you to use breakpoints, watches, stack traces and the like:
Installation is straightforward from within VSCode: Summon the command line with F1 and then type ext install php-debug
Take a look at these. I didn't use more parenthesis to keep it readable, so remember that multiplication is done before addition or subtraction.
Both below return:
hr mins sec timediff
73 12 30 73:12:30
This is written to not use a sub-query and be the most readable and understandable:
declare @StartDate datetime,
@EndDate datetime
set @StartDate = '10/01/2012 08:40:18.000'
set @EndDate = '10/04/2012 09:52:48.000'
select datediff(hour, @StartDate, @EndDate) hr,
datediff(minute, @StartDate, @EndDate)
- datediff(hour, @StartDate, @EndDate) * 60 mins,
datediff(second, @StartDate, @EndDate)
- (datediff(minute, @StartDate, @EndDate) * 60) sec,
cast(datediff(hour, @StartDate, @EndDate) as varchar)+':'+
cast(datediff(minute, @StartDate, @EndDate)
- datediff(hour, @StartDate, @EndDate) * 60 as varchar)+':'+
cast(datediff(second, @StartDate, @EndDate)
- (datediff(minute, @StartDate, @EndDate) * 60) as varchar) timediff
This is a version that would perform better if you have a lot of data. It requires a sub-query.
declare @StartDate datetime,
@EndDate datetime
set @StartDate = '10/01/2012 08:40:18.000'
set @EndDate = '10/04/2012 09:52:48.000'
select s.seconds / 3600 hrs,
s.seconds / 60 - (seconds / 3600 ) * 60 mins,
s.seconds - (s.seconds / 60) * 60 seconds,
cast(s.seconds / 3600 as varchar) + ':' +
cast((s.seconds / 60 - (seconds / 3600 ) * 60) as varchar) + ':' +
cast((s.seconds - (s.seconds / 60) * 60) as varchar) timediff
from (select datediff(second, @StartDate, @EndDate) as seconds) s
Console applications will exit when the main function has finished running. A "return" will achieve this.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:
System.Environment.Exit(-1);
WHERE created_date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY)
AND created_date <= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)), INTERVAL 0 DAY)
This worked for me (Selects all records created from last month, regardless of the day you run the query this month)
First you have to exhaustively identify the special characters that you want to check.
Then you can write a regular expression and use
public boolean matches(String regex)
This solution might also help :
$(document).ready(function () {
$(window).resize(function() {
if ($(window).width() < 600) {
$('body').css('font-size', '2.8vw' );
} else if ($(window).width() >= 600 && $(window).width() < 750) {
$('body').css('font-size', '2.4vw');
}
// and so on... (according to our needs)
} else if ($(window).width() >= 1200) {
$('body').css('font-size', '1.2vw');
}
});
});
It worked for me well !
In you app config file change the url
to localhost/example/public
Then when you want to link to something
<a href="{{ url('page') }}">Some Text</a>
without blade
<a href="<?php echo url('page') ?>">Some Text</a>
While Richard's is what you want if you do want to go with a typedef, I'd suggest that it's probably not a particularly good idea in this instance, as you lose sight of it being a pointer, while not gaining anything.
If you were treating it a a counted string, or something with additional functionality, that might be different, but I'd really recommend that in this instance, you just get familiar with the 'standard' C string implementation being a 'char *'...
I do not know whether this is the general opinion, but I've always differentiated the two by what they are used for. An emulator is used if you actually want to use the emulated machine for its output. A simulator, on the other hand, is for when you want to study the simulated machine or test its behaviour.
For example, if you want to write some state machine logic in your application (which is running on a general purpose CPU), you write a small state machine emulator. If you want to study the efficiency or viability of a state machine for a particular problem, you write a simulator.
It is impossible to safely escape a string without a DB connection. mysql_real_escape_string()
and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.
If you are only testing, then you may as well use mysql_escape_string()
, it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.
As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).
Use Spring's Numberformatter instead, which is thread safe.
In the navigator under SCHEMAS, right click your schema/database and select "Table Data Import Wizard"
Works for mac too.
The problem here seems to be that you're reassigning $today
by assigning a string to it:
$today = $dd+'/'+$mm+'/'+$yyyy;
Strings don't have getDate
.
Also, $today.getDate()-1
just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:
$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.
Then just apply the formatting code you wrote:
var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!
var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;
Because of the last statement, $yesterday
is now a String
(not a Date
) containing the formatted date.
Try this query
select
*,
Days = datediff(dd,0,DateDif),
Hours = datepart(hour,DateDif),
Minutes = datepart(minute,DateDif),
Seconds = datepart(second,DateDif),
MS = datepart(ms,DateDif)
from
(select
DateDif = EndDate-StartDate,
aa.*
from
( -- Test Data
Select
StartDate = convert(datetime,'20090213 02:44:37.923'),
EndDate = convert(datetime,'20090715 13:24:45.837')) aa
) a
Output
DateDif StartDate EndDate Days Hours Minutes Seconds MS
----------------------- ----------------------- ----------------------- ---- ----- ------- ------- ---
1900-06-02 10:40:07.913 2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 152 10 40 7 913
(1 row(s) affected)
To tell from the style of your code snippet, I suppose you were using IPython rather than Jupyter Notebook.
In this issue on GitHub, it was made clear by a member of IPython in 2016 that the display of charts would only work when "only work when it's a Jupyter kernel". Thus, the %matplotlib inline
would not work.
I was just having the same issue and suggest you use Jupyter Notebook for the visualization.
I ran into something similar, I think that the cause of the warning is Eclipse trying to discourage you from using the internal com.sun
packages that are installed as part of your workspace JRE but which are not part of the public Java API.
As Justin says in his answer, changing your compiler settings can hide the warning. A more fine-grained approach is to modify your build path to explicitly allow access to the package in question:
"com/sun/xml/internal/**"
.After adding this access rule, your project should build without these warning.
You don't need jQuery for this, as simple javascript will suffice:
alert(document.domain);
See it in action:
console.log("Output;");
console.log(location.hostname);
console.log(document.domain);
alert(window.location.hostname)
console.log("document.URL : "+document.URL);
console.log("document.location.href : "+document.location.href);
console.log("document.location.origin : "+document.location.origin);
console.log("document.location.hostname : "+document.location.hostname);
console.log("document.location.host : "+document.location.host);
console.log("document.location.pathname : "+document.location.pathname);
for more details click here window.location
just append "http://" before domain name to get appropriate result.
The error is a result of the missing semicolon on the third line:
window.Glog = function(msg) {
console.log(msg);
}; // <--- Add this semicolon
(function(win) {
// ...
})(window);
The ECMAScript specification has specific rules for automatic semicolon insertion, however in this case a semicolon isn't automatically inserted because the parenthesised expression that begins on the next line can be interpreted as an argument list for a function call.
This means that without that semicolon, the anonymous window.Glog
function was being invoked with a function as the msg
parameter, followed by (window)
which was subsequently attempting to invoke whatever was returned.
This is how the code was being interpreted:
window.Glog = function(msg) {
console.log(msg);
}(function(win) {
// ...
})(window);
Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";
$result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
$lastid= $connection->insert_id;
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK ){
$name = $lastid.$_FILES['file']['name'][$key];
$target_dir = "photo/";
$sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
$result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
}
}
And how to fetch
$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());
if($result->num_rows > 0) {
while($r = mysqli_fetch_assoc($result)){
$eventid= $r['id'];
$sqli="select id,image from photos where eventid='".$eventid."'";
$resulti=mysqli_query($connection,$sqli);
$image_json_array = array();
while($row = mysqli_fetch_assoc($resulti)){
$image_id = $row['id'];
$image_name = $row['image'];
$image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
}
$msg1[] = array ("imagelist" => $image_json_array);
}
in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})
There isn't one.
I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.
I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).
Update 2012
I've changed how I program over time. I now use camel case (thisIsASelector
) instead of hyphens now; I find the latter rather ugly. Use whatever you prefer, which may easily change over time.
Update 2013
It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn't a standard.
Update 2015
An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case
. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.
Update 2016 (you asked for it)
I've adopted the BEM standard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actually a standard (so my no
becomes a yes
perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.
Update 2019 (you asked for it)
After writing no CSS for quite a while, I started working at a place that uses OOCSS in one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.
I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.
OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromises because CSS just isn't that good.
Update 2020
A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.
In WPF RelativeSource
binding exposes three properties
to set:
1. Mode: This is an enum
that could have four values:
a. PreviousData(
value=0
): It assigns the previous value of theproperty
to the bound oneb. TemplatedParent(
value=1
): This is used when defining thetemplates
of any control and want to bind to a value/Property of thecontrol
.For example, define
ControlTemplate
:
<ControlTemplate>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</ControlTemplate>
c. Self(
value=2
): When we want to bind from aself
or aproperty
of self.For example: Send checked state of
checkbox
asCommandParameter
while setting theCommand
onCheckBox
<CheckBox ...... CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=IsChecked}" />
d. FindAncestor(
value=3
): When want to bind from a parentcontrol
inVisual Tree
.For example: Bind a
checkbox
inrecords
if agrid
,ifheader
checkbox
is checked
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}, Path=DataContext.IsHeaderChecked, Mode=TwoWay}" />
2. AncestorType: when mode is FindAncestor
then define what type of ancestor
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}
3. AncestorLevel: when mode is FindAncestor
then what level of ancestor (if there are two same type of parent in visual tree
)
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid, AncestorLevel=1}}
Above are all use-cases for
RelativeSource binding
.
I have created a snippet - inspired by the actual View source - that reliably detects long clicks/presses with a custom delay. But it's in Kotlin:
val LONG_PRESS_DELAY = 500
val handler = Handler()
var boundaries: Rect? = null
var onTap = Runnable {
handler.postDelayed(onLongPress, LONG_PRESS_DELAY - ViewConfiguration.getTapTimeout().toLong())
}
var onLongPress = Runnable {
// Long Press
}
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
boundaries = Rect(view.left, view.top, view.right, view.bottom)
handler.postDelayed(onTap, ViewConfiguration.getTapTimeout().toLong())
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(onLongPress)
handler.removeCallbacks(onTap)
}
MotionEvent.ACTION_MOVE -> {
if (!boundaries!!.contains(view.left + event.x.toInt(), view.top + event.y.toInt())) {
handler.removeCallbacks(onLongPress)
handler.removeCallbacks(onTap)
}
}
}
return true
}
Use the Apache XMLSerializer
here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
In my case i moved the validate part outside of the document ready function and it works fine for me. I hope it would work for u...
$(document).ready(function () {
// paste validate function outside of the document ready function...
});
$('#form1').validate({
rules: {
English_Name: { required: true, minlength: 3 },
Arabic_Name: { required: true, minlength: 3 },
latitude: { required: true, min: 16, max: 32, number: true },
longitude: { required: true, min: 32, max: 52, number: true },
EmployeeID: { required: true },
PaymentTypeID: { required: true },
BusinessTypeID: { required: true },
SalesTypeID: { required: true },
OutletLength: { required: true },
OutletWidth: { required: true },
CONTACT_PERSON: { required: true },
MOBILE_NO: { required: true, minlength: 9, maxlength: 13, digits: true },
TRADE_LIC_DATE: { dateValidation: true },
CreditLimit: { min: 0, max: 2000000 },
CreditPeriod: { min: 0, max: 365 },
EMAIL_ADDRESS: { email: true },
BusinessClassID: { required: true },
CustomerClassificationID: { required: true },
LicenseTypeID: { required: true }
},
message: {
English_Name: {
required: ''
},
ToDate: {
required: ''
}
},
submitHandler: function (form) { // for demo
$.ajax({
type: 'POST',
url: '/sfa/Verification/SaveDataInDatabase',
data: $('form').serialize(),
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function (msg) {
$("#form1").trigger('reset');
$('.modal').modal('hide');
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
});
To change password using Linux command line, use:
sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
I would wrap the text in a so you can target it separately. Now if you float both and left, you can use line-height to control the vertical spacing of the . Setting it to the same height as the (30px) will middle align it. See here.
New Markup:
<div>
<i class='icon icon-2x icon-camera'></i>
<span id="text">hello world</span>
</div>
New CSS:
div {
border: 1px solid #ccc;
height: 30px;
margin: 60px;
padding: 4px;
vertical-align: middle;
}
i{
float: left;
}
#text{
line-height: 30px;
float: left;
}
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
Thanks @crea1
A small variant:
As it is written on https://git-scm.com/docs/git-config#_includes:
If the pattern ends with
/
,**
will be automatically added. For example, the patternfoo/
becomesfoo/**
. In other words, it matchesfoo
and everything inside, recursively.
So I use in my case,
~/.gitconfig :
[user] # as default, personal needs
email = [email protected]
name = bcag2
[includeIf "gitdir:~/workspace/"] # job needs, like workspace/* so all included projects
path = .gitconfig-job
# all others section: core, alias, log…
So If the project directory is in my ~/wokspace/
, default user settings is replace with
~/.gitconfig-job :
[user]
name = John Smith
email = [email protected]
Use preventDefault()
to stop the event of submit button and in ajax call success submit the form using submit()
:
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Why not just target the ones you want (demo)?
$('form').find('input[type=text],textarea,select').filter(':visible:first');
Edit
Or use jQuery :input selector to filter form descendants.
$('form').find('*').filter(':input:visible:first');
Sounds like you need to add the formatting to the WHERE
:
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE DATE_FORMAT(users.signup_date, '%Y-%m-%d') = CURDATE()
Following up on the comment ron posted, here is the detailed solution. Let's say you have registered a repeating alarm with a pending intent like this:
Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 1);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60, pendingIntent);
The way you would check to see if it is active is to:
boolean alarmUp = (PendingIntent.getBroadcast(context, 0,
new Intent("com.my.package.MY_UNIQUE_ACTION"),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp)
{
Log.d("myTag", "Alarm is already active");
}
The key here is the FLAG_NO_CREATE
which as described in the javadoc: if the described PendingIntent **does not** already exists, then simply return null
(instead of creating a new one)
if you want to check csv file is empty or not .......try this
with open('file.csv','a',newline='') as f:
csv_writer=DictWriter(f,fieldnames=['user_name','user_age','user_email','user_gender','user_type','user_check'])
if os.stat('file.csv').st_size > 0:
pass
else:
csv_writer.writeheader()
Since Spring 2.5 there's a very easy (and elegant) way to achieve that.
You can just change the params proxyMode
and value
of the @Scope
annotation.
With this trick you can avoid to write extra code or to inject the ApplicationContext every time that you need a prototype inside a singleton bean.
Example:
@Service
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class LoginAction {}
With the config above LoginAction
(inside HomeController
) is always a prototype even though the controller is a singleton.
On each loop of the result set, you're appending a new root element to the document, creating an XML document like this:
<?xml version="1.0"?>
<mycatch>...</mycatch>
<mycatch>...</mycatch>
...
An XML document can only have one root element, which is why the error is stating there is "extra content". Create a single root element and add all the mycatch elements to that:
$root = $dom->createElement("root");
$dom->appendChild($root);
// ...
while ($row = @mysql_fetch_assoc($result)){
$node = $dom->createElement("mycatch");
$root->appendChild($node);
The explanation from Scott Meyers in Effective C++ might help understand when to use them:
Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.
I published an update to my app yesterday noon(I have selected Manual release instead of Automatic) and Today early morning App store review was completed and after I release the build manually, the App shows Ready for sale in iTunesConect immediately. After 45mins I got the update on the App store.
I've get closer to VisualStudio-like behaviour by setting the "Autocomplete Trigger for Java" to
.(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
and setting delay to 0.
Now I'd like to realize how to make it autocomplete method name when I press ( as VS's Intellisense does.
I made a different route for every file in a particular directory. Therefore, going to that path meant opening that file.
function getroutes(list){
list.forEach(function(element) {
app.get("/"+ element, function(req, res) {
res.sendFile(__dirname + "/public/extracted/" + element);
});
});
I called this function passing the list of filename in the directory __dirname/public/extracted
and it created a different route for each filename which I was able to render on server side.
When you write a "string" in your source code, it gets written directly into the executable because that value needs to be known at compile time (there are tools available to pull software apart and find all the plain text strings in them). When you write char *a = "This is a string"
, the location of "This is a string" is in the executable, and the location a
points to, is in the executable. The data in the executable image is read-only.
What you need to do (as the other answers have pointed out) is create that memory in a location that is not read only--on the heap, or in the stack frame. If you declare a local array, then space is made on the stack for each element of that array, and the string literal (which is stored in the executable) is copied to that space in the stack.
char a[] = "This is a string";
you can also copy that data manually by allocating some memory on the heap, and then using strcpy()
to copy a string literal into that space.
char *a = malloc(256);
strcpy(a, "This is a string");
Whenever you allocate space using malloc()
remember to call free()
when you are finished with it (read: memory leak).
Basically, you have to keep track of where your data is. Whenever you write a string in your source, that string is read only (otherwise you would be potentially changing the behavior of the executable--imagine if you wrote char *a = "hello";
and then changed a[0]
to 'c'
. Then somewhere else wrote printf("hello");
. If you were allowed to change the first character of "hello"
, and your compiler only stored it once (it should), then printf("hello");
would output cello
!)
I'll go into differences at the hardware level, on x86. This is mostly irrelevant unless you're writing a compiler or using assembly language. But it's nice to know.
Firstly, x86 has native support for the two's complement representation of signed numbers. You can use other representations but this would require more instructions and generally be a waste of processor time.
What do I mean by "native support"? Basically I mean that there are a set of instructions you use for unsigned numbers and another set that you use for signed numbers. Unsigned numbers can sit in the same registers as signed numbers, and indeed you can mix signed and unsigned instructions without worrying the processor. It's up to the compiler (or assembly programmer) to keep track of whether a number is signed or not, and use the appropriate instructions.
Firstly, two's complement numbers have the property that addition and subtraction is just the same as for unsigned numbers. It makes no difference whether the numbers are positive or negative. (So you just go ahead and ADD
and SUB
your numbers without a worry.)
The differences start to show when it comes to comparisons. x86 has a simple way of differentiating them: above/below indicates an unsigned comparison and greater/less than indicates a signed comparison. (E.g. JAE
means "Jump if above or equal" and is unsigned.)
There are also two sets of multiplication and division instructions to deal with signed and unsigned integers.
Lastly: if you want to check for, say, overflow, you would do it differently for signed and for unsigned numbers.
You can use Jinja's default
:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
You can try this to ignore "https":
pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org [your package..]
Heapsort implementation. An O(n log(n)) (both average and worst case), in place, unstable sorting algorithm.
Use with: Call HeapSort(A)
, where A
is a one dimensional array of variants, with Option Base 1
.
Sub SiftUp(A() As Variant, I As Long)
Dim K As Long, P As Long, S As Variant
K = I
While K > 1
P = K \ 2
If A(K) > A(P) Then
S = A(P): A(P) = A(K): A(K) = S
K = P
Else
Exit Sub
End If
Wend
End Sub
Sub SiftDown(A() As Variant, I As Long)
Dim K As Long, L As Long, S As Variant
K = 1
Do
L = K + K
If L > I Then Exit Sub
If L + 1 <= I Then
If A(L + 1) > A(L) Then L = L + 1
End If
If A(K) < A(L) Then
S = A(K): A(K) = A(L): A(L) = S
K = L
Else
Exit Sub
End If
Loop
End Sub
Sub HeapSort(A() As Variant)
Dim N As Long, I As Long, S As Variant
N = UBound(A)
For I = 2 To N
Call SiftUp(A, I)
Next I
For I = N To 2 Step -1
S = A(I): A(I) = A(1): A(1) = S
Call SiftDown(A, I - 1)
Next
End Sub
I found a solution for ajax issue noted by Lion_cl.
global.asax:
protected void Application_Error()
{
if (HttpContext.Current.Request.IsAjaxRequest())
{
HttpContext ctx = HttpContext.Current;
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
rc.RouteData.Values["action"] = "AjaxGlobalError";
// TODO: distinguish between 404 and other errors if needed
rc.RouteData.Values["newActionName"] = "WrongRequest";
rc.RouteData.Values["controller"] = "ErrorPages";
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, "ErrorPages");
controller.Execute(rc);
ctx.Server.ClearError();
}
}
ErrorPagesController
public ActionResult AjaxGlobalError(string newActionName)
{
return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
}
AjaxRedirectResult
public class AjaxRedirectResult : RedirectResult
{
public AjaxRedirectResult(string url, ControllerContext controllerContext)
: base(url)
{
ExecuteResult(controllerContext);
}
public override void ExecuteResult(ControllerContext context)
{
if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
{
JavaScriptResult result = new JavaScriptResult()
{
Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
};
result.ExecuteResult(context);
}
else
{
base.ExecuteResult(context);
}
}
}
AjaxRequestExtension
public static class AjaxRequestExtension
{
public static bool IsAjaxRequest(this HttpRequest request)
{
return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
It is posible. My android device version is 4.0.4 and android.os.Build.VERSION.SDK_INT is 15
I have 3 spinners
Spinner c_fruit=(Spinner) findViewById(R.id.fruits);
Spinner c_vegetable=(Spinner) findViewById(R.id.vegetables);
Spinner c_beverage=(Spinner) findViewById(R.id.beverages);
And also I have a Async-Tack class.
Here is my spinner loading code
RequestSend reqs_fruit = new RequestSend(this);
reqs_fruit.where="Get_fruit_List";
reqs_fruit.title="Loading fruit";
reqs_fruit.execute();
RequestSend reqs_vegetable = new RequestSend(this);
reqs_vegetable.where="Get_vegetable_List";
reqs_vegetable.title="Loading vegetable";
reqs_vegetable.execute();
RequestSend reqs_beverage = new RequestSend(this);
reqs_beverage.where="Get_beverage_List";
reqs_beverage.title="Loading beverage";
reqs_beverage.execute();
This is working perfectly. One by one my spinners loaded. I didn't user executeOnExecutor.
Here is my Async-task class
public class RequestSend extends AsyncTask<String, String, String > {
private ProgressDialog dialog = null;
public Spinner spin;
public String where;
public String title;
Context con;
Activity activity;
String[] items;
public RequestSend(Context activityContext) {
con = activityContext;
dialog = new ProgressDialog(activityContext);
this.activity = activityContext;
}
@Override
protected void onPostExecute(String result) {
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
} catch (NullPointerException e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(activity, "Can not load list. Check your connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle(title);
dialog.setMessage("Wait...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected String doInBackground(String... Strings) {
try {
Send_Request();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void Send_Request() throws JSONException {
try {
String DataSendingTo = "http://www.example.com/AppRequest/" + where;
//HttpClient
HttpClient httpClient = new DefaultHttpClient();
//Post header
HttpPost httpPost = new HttpPost(DataSendingTo);
//Adding data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("authorized","001"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line) ;
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
items = new String[finalResult.length()];
// looping through All details and store in public String array
for(int i = 0; i < finalResult.length(); i++) {
JSONObject c = finalResult.getJSONObject(i);
items[i]=c.getString("data_name");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
@Path("/resource")
class MyResource {
// one way to get HttpServletResponse
@Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(@Context HttpServletResponse servletResponse) {
// ... code
}
}
You can find the solution to this problem at: https://help.github.com/en/github/using-git/configuring-git-to-handle-line-endings
Simplified description of how you can solve this problem on windows:
Global settings for line endings The git config core.autocrlf command is used to change how Git handles line endings. It takes a single argument.
On Windows, you simply pass true to the configuration. For example: C:>git config --global core.autocrlf true
Good luck, I hope I helped.
So wait, this is just a list-within-a-list?
The easiest way is probably just to use nested for loops:
>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
... for number in list:
... print number
...
1
3
4
2
4
4
3
4
5
Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.
Also, for performance reasons, you might want to look at using list comprehensions to do this:
http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions