You can't.
As a workaround you can use a // @ts-nocheck
comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/
So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)
We can handle this by using offset value
public static long convertDateTimeZone(long lngDate, String fromTimeZone,
String toTimeZone){
TimeZone toTZ = TimeZone.getTimeZone(toTimeZone);
Calendar toCal = Calendar.getInstance(toTZ);
TimeZone fromTZ = TimeZone.getTimeZone(fromTimeZone);
Calendar fromCal = Calendar.getInstance(fromTZ);
fromCal.setTimeInMillis(lngDate);
toCal.setTimeInMillis(fromCal.getTimeInMillis()
+ toTZ.getOffset(fromCal.getTimeInMillis())
- TimeZone.getDefault().getOffset(fromCal.getTimeInMillis()));
return toCal.getTimeInMillis();
}
Test Code snippet:
System.out.println(new Date().getTime())
System.out.println(convertDateTimeZone(new Date().getTime(), TimeZone
.getDefault().getID(), "EST"));
Output: 1387353270742 1387335270742
Your Ubuntu definitely has a sufficiently recent version of g++
. The flag to use is -std=c++0x
.
For me it was the "Start In" - I copied the values from an older server, and updated the path to the new .exe location, but I forgot to update the "start in" location - if it doesn't exist, you get this error too
Quoting @hans-passant 's comment from above, because it is valuable to debugging this issue:
Convert the error code to hex to get 0x8007010B. The 7 makes it a Windows error. Which makes 010B error code 267. "The directory name is invalid". Sure, that happens.
Most probably unit mongodb.service is masked. Use following command to unmask it.
sudo systemctl unmask mongod
and re-run
sudo service mongod start
The long must be at least the same size as an int, and possibly, but not necessarily, longer.
On common 32-bit systems, both int and long are 4-bytes/32-bits, and this is valid according to the C++ spec.
On other systems, both int and long long may be a different size. I used to work on a platform where int was 2-bytes, and long was 4-bytes.
I had some trouble determining the Java package that was installed when I ran into this problem, since the previous answers didn't exactly work for me. To sort it out, I typed:
Sys.setenv(JAVA_HOME="C:/Program Files/Java/
and then hit tab and the two suggested directories were "jre1.8.0_31/" and "jre7/"
Jre7 didn't solve my problem, but jre1.8.0_31/ did. Final answer was running (before library(rJava)):
Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_31/")
I'm using 64-bit Windows 8.1 Hope this helps someone else.
Update:
Check your version to determine what X should be (mine has changed several times since this post):
Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_x/")
newlist = oldlist[::10]
This picks out every 10th element of the list.
You may try;
$this->Output(/path/to/file);
So for you, it will be like;
$this->Output(/kuitit/); //or try ("/kuitit/")
The following works for me:
DEPS := $(OBJS:.o=.d)
-include $(DEPS)
%.o: %.cpp
$(CXX) $(CFLAGS) -MMD -c -o $@ $<
Recently I am also faced the same problem, while submitting my own WordPress plugin to the directory, Finally, i figured out and worked me,
Just add a comment/ Commit message. It will work,
I used TortiseSVN.
I'm not sure if I understood the question properly.
Anyway, are you looking for this:
std::string ip ="192.168.1.54";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << " " << b << " " << c << " "<< d;
192 168 1 54
I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:
@{
var htmlAttr = new Dictionary<string, object>();
htmlAttr.Add("id", strElementId);
if (!CSSClass.IsEmpty())
{
htmlAttr.Add("class", strCSSClass);
}
}
@* ... *@
@Html.TextBox("somename", "", htmlAttr)
If this way will be useful for you i recommend to define dictionary htmlAttr
in your model so your view doesn't need any @{ }
logic blocks (be more clear).
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
You could read the entire input line from scanner, then split the line by ,
then you have a String[]
, parse each number into int[]
with index one to one matching...(assuming valid input and no NumberFormatExceptions
) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[]
will be represented by a 0
, these need to be removed in order to differentiate between a valid input value of 0
.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
nil?
is a standard Ruby method that can be called on all objects and returns true
if the object is nil
:
b = nil
b.nil? # => true
empty?
is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returns true
if these objects contain no element:
a = []
a.empty? # => true
b = ["2","4"]
b.empty? # => false
empty?
cannot be called on nil
objects.
blank?
is a Rails method that can be called on nil
objects as well as empty objects.
Also if you want selected field from table and aggregated then as array .
SELECT json_agg(json_build_object('data_a',a,
'data_b',b,
)) from t;
The result will come .
[{'data_a':1,'data_b':'value1'}
{'data_a':2,'data_b':'value2'}]
For me worked just with
# yum install ffmpeg-2.6.4-1.fc22.x86_64.rpm
And automatically asked authorization to dowload the depedencies. Below the example, i am using fedora 22
[root@localhost lukas]# yum install ffmpeg-2.6.4-1.fc22.x86_64.rpm
Yum command has been deprecated, redirecting to '/usr/bin/dnf install ffmpeg-2.6.4-1.fc22.x86_64.rpm'.
See 'man dnf' and 'man yum2dnf' for more information.
To transfer transaction metadata from yum to DNF, run:
'dnf install python-dnf-plugins-extras-migrate && dnf-2 migrate'
Last metadata expiration check performed 0:28:24 ago on Fri Sep 25 12:43:44 2015.
Dependencies resolved.
====================================================================================================================
Package Arch Version Repository Size
====================================================================================================================
Installing:
SDL x86_64 1.2.15-17.fc22 fedora 214 k
ffmpeg x86_64 2.6.4-1.fc22 @commandline 1.5 M
ffmpeg-libs x86_64 2.6.4-1.fc22 rpmfusion-free-updates 5.0 M
fribidi x86_64 0.19.6-3.fc22 fedora 69 k
lame-libs x86_64 3.99.5-5.fc22 rpmfusion-free 345 k
libass x86_64 0.12.1-1.fc22 updates 85 k
libavdevice x86_64 2.6.4-1.fc22 rpmfusion-free-updates 75 k
libdc1394 x86_64 2.2.2-3.fc22 fedora 124 k
libva x86_64 1.5.1-1.fc22 fedora 79 k
openal-soft x86_64 1.16.0-5.fc22 fedora 292 k
opencv-core x86_64 2.4.11-5.fc22 updates 1.9 M
openjpeg-libs x86_64 1.5.1-14.fc22 fedora 89 k
schroedinger x86_64 1.0.11-7.fc22 fedora 315 k
soxr x86_64 0.1.2-1.fc22 updates 83 k
x264-libs x86_64 0.142-12.20141221git6a301b6.fc22 rpmfusion-free 587 k
x265-libs x86_64 1.6-1.fc22 rpmfusion-free 486 k
xvidcore x86_64 1.3.2-6.fc22 rpmfusion-free 264 k
Transaction Summary
====================================================================================================================
Install 17 Packages
Total size: 11 M
Total download size: 9.9 M
Installed size: 35 M
Is this ok [y/N]: y
Use get_the_category()
like this:
<?php
foreach((get_the_category()) as $category) {
echo $category->cat_name . ' ';
}
?>
It returns a list because a post can have more than one category.
The documentation also explains how to do this from outside the loop.
FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.
If supporting legacy browsers is not needed, you could use a combination of required
, valid
, and invalid
.
The good thing about using this is the valid
and invalid
pseudo-elements work well with the type attributes of input fields. For example:
input:invalid, textarea:invalid { _x000D_
box-shadow: 0 0 5px #d45252;_x000D_
border-color: #b03535_x000D_
}_x000D_
_x000D_
input:valid, textarea:valid {_x000D_
box-shadow: 0 0 5px #5cd053;_x000D_
border-color: #28921f;_x000D_
}
_x000D_
<input type="email" name="email" placeholder="[email protected]" required />_x000D_
<input type="url" name="website" placeholder="http://johndoe.com"/>_x000D_
<input type="text" name="name" placeholder="John Doe" required/>
_x000D_
For reference, JSFiddle here: http://jsfiddle.net/0sf6m46j/
Use hamcrest Matcher containsString()
// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));
// Error Message
java.lang.AssertionError:
Expected: a string containing "myName"
got: "some other name"
You can optional add an even more detail error message.
// Hamcrest assertion with custom error message
assertThat("my error message", person.getName(), containsString("myName"));
// Error Message
java.lang.AssertionError: my error message
Expected: a string containing "myName"
got: "some other name"
Posted my answer to a duplicate question here
In case also setting the height of the html and the body to 100% makes everything messier for you as it did for me, the following worked for me:
height: calc(100vh - 33rem)
The - 33rem is the height of the elements coming after the one we want to take full height, i.e., 100vh. By subtracting the height, we will make sure there is no overflow and it will always be responsive (assuming we are working with rem instead of px).
The Swift version of maxkonovalov's answer is this:
player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil)
and
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "rate" {
if let rate = change?[NSKeyValueChangeNewKey] as? Float {
if rate == 0.0 {
print("playback stopped")
}
if rate == 1.0 {
print("normal playback")
}
if rate == -1.0 {
print("reverse playback")
}
}
}
}
Thank you maxkonovalov!
Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Subject varchar(50) NULL
)
CREATE TABLE dbo.Owner
(
ID int NOT NULL,
User_ID int NULL,
Group_ID int NULL,
{{AdditionalEntity_ID}} int NOT NULL
)
With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).
If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
Subject varchar(50) NULL
)
With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.
Sorry if I got some SQL wrong, I just threw this together.
I managed to remove the errors by disabling the validations:
{
"javascript.validate.enable": false,
"html.validate.styles": false,
"html.validate.scripts": false,
"css.validate": false,
"scss.validate": false
}
Obs: My project is a PWA using StyledComponents, React, Flow, Eslint and Prettier.
In short, there is no simpler way. You need to make another server request to show PDF file. Al though, there are few alternatives but they are not perfect and won't work on all browsers:
Url.Action("Evil", model)
will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51
Just Add "JsonRequestBehavior.AllowGet" on your Json object.
In python 3s print function:
lst = [1, 2, 3]
print('My list:', *lst, sep='\n- ')
Output:
My list:
- 1
- 2
- 3
Con: The sep
must be a string, so you can't modify it based on which element you're printing. And you need a kind of header to do this (above it was 'My list:'
).
Pro: You don't have to join()
a list into a string object, which might be advantageous for larger lists. And the whole thing is quite concise and readable.
Actually, you can always test it by yourself.
CREATE TABLE CUSTOMERS
(
CUSTOMER_ID NUMBER NOT NULL,
JOIN_DATE DATE NOT NULL,
CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
CUSTOMER_NAME VARCHAR2(20) NOT NULL,
CREDITRATING VARCHAR2(10)
)
;
select column_name, data_type, nullable, data_length, data_precision, data_scale from user_tab_columns where table_name ='CUSTOMERS';
Wrote a small class for doing this cleanly.
import tempfile
class FileModifierError(Exception):
pass
class FileModifier(object):
def __init__(self, fname):
self.__write_dict = {}
self.__filename = fname
self.__tempfile = tempfile.TemporaryFile()
with open(fname, 'rb') as fp:
for line in fp:
self.__tempfile.write(line)
self.__tempfile.seek(0)
def write(self, s, line_number = 'END'):
if line_number != 'END' and not isinstance(line_number, (int, float)):
raise FileModifierError("Line number %s is not a valid number" % line_number)
try:
self.__write_dict[line_number].append(s)
except KeyError:
self.__write_dict[line_number] = [s]
def writeline(self, s, line_number = 'END'):
self.write('%s\n' % s, line_number)
def writelines(self, s, line_number = 'END'):
for ln in s:
self.writeline(s, line_number)
def __popline(self, index, fp):
try:
ilines = self.__write_dict.pop(index)
for line in ilines:
fp.write(line)
except KeyError:
pass
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
with open(self.__filename,'w') as fp:
for index, line in enumerate(self.__tempfile.readlines()):
self.__popline(index, fp)
fp.write(line)
for index in sorted(self.__write_dict):
for line in self.__write_dict[index]:
fp.write(line)
self.__tempfile.close()
Then you can use it this way:
with FileModifier(filename) as fp:
fp.writeline("String 1", 0)
fp.writeline("String 2", 20)
fp.writeline("String 3") # To write at the end of the file
A canvas element with some JavaScript would work great.
In fact, Signature Pad (a jQuery plugin) already has this implemented.
Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.
Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.
//
// ViewController.m
// AutoLayoutDynamicVerticalContainerHeight
//
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end
@implementation ViewController
- (void)viewDidLoad
{
// INVOKE SUPER
[super viewDidLoad];
// INIT ALL REQUIRED UI ELEMENTS
self.contentView = [[UIView alloc] init];
self.myLabel = [[UILabel alloc] init];
self.myOtherLabel = [[UILabel alloc] init];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);
// TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;
// ESTABLISH VIEW HIERARCHY
[self.view addSubview:self.contentView]; // View adds content view
[self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
[self.contentView addSubview:self.myOtherLabel];
// LAYOUT
// Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
// Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet
/* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
// ^To me this is what's weird... but okay once you understand...
// Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
// Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
// Note, this is the view that we are choosing to use to drive the height (and width) of our container...
// The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// COLOR VIEWS
self.view.backgroundColor = [UIColor purpleColor];
self.contentView.backgroundColor = [UIColor redColor];
self.myLabel.backgroundColor = [UIColor orangeColor];
self.myOtherLabel.backgroundColor = [UIColor greenColor];
// CONFIGURE VIEWS
// Configure MY LABEL
self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
self.myLabel.numberOfLines = 0; // Let it flow
// Configure MY OTHER LABEL
self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
self.myOtherLabel.numberOfLines = 0;
self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}
@end
JPG doesn't support transparency
If you run
cmake .
it will regenerate the CMake files. Which is necessary if you add a new file to a source folder that is selected by *.cc, for example.
While this isn't a "clean" per se, it does "clean" up the CMake files by regenerating the caches.
This rings a bell. I came across a similar problem in the past,
You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.
Cheers, Tarun
Update 2016-07-08:
For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:
After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.
i prefer to use ng-value with ng-if, [ng-value] will handle trigger changes
<input type="radio" name="isStudent" ng-model="isStudent" ng-value="true" />
//to show and hide input by removing it from the DOM, that's make me secure from malicious data
<input type="text" ng-if="isStudent" name="textForStudent" ng-model="job">
%r
shows with quotes:
It will be like:
I said: 'There are 10 types of people.'.
If you had used %s
it would have been:
I said: There are 10 types of people..
Just add style="text-align: left"
to your label.
You might also need to provide your user with an alert showing that those functions are disabled for the text input fields. This will work
function showError(){_x000D_
alert('you are not allowed to cut,copy or paste here');_x000D_
}_x000D_
_x000D_
$('.form-control').bind("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<textarea class="form-control" oncopy="showError()" onpaste="showError()"></textarea>
_x000D_
To accept 0 as a value in variable use isset
Check if variable is empty
$var = 0;
if ($var == '') {
echo "empty";
} else {
echo "not empty";
}
//output is empty
Check if variable is set
$var = 0;
if (isset($var)) {
echo "not empty";
} else {
echo "empty";
}
//output is not empty
<?php $data = array('a'=>'apple','b'=>'banana','c'=>'orange');?>
<pre><?php print_r($data); ?></pre>
Result:
Array
(
[a] => apple
[b] => banana
[c] => orange
)
You can use stat
with a file glob and a decorate-sort-undecorate with the file time added on the front:
$ stat -f "%m%t%N" b2* | sort -rn | head -1 | cut -f2-
You have to increase client_max_body_size in nginx.conf
file. This is the basic step. But if your backend laravel
then you have to do some changes in the php.ini
file as well. It depends on your backend. Below I mentioned file location and condition name.
sudo vim /etc/nginx/nginx.conf.
After open the file adds this into HTTP section.
client_max_body_size 100M;
You need to use the __getitem__
method.
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
And if you're going to be setting values you'll need to implement the __setitem__
method too, otherwise this will happen:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
I recommend to use bellow formula suggested on Apache:
MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)
Find my script here which is running on Rhel 6.7. you can made change according to your OS.
#!/bin/bash
echo "HostName=`hostname`"
#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit
This was the ONLY thing that worked for me (on Chrome Version 54.0.2840.27):
$('select').each(function() {_x000D_
$(this).data('lastSelectedIndex', this.selectedIndex);_x000D_
});_x000D_
$('select').click(function() {_x000D_
$(this).data('lastSelectedIndex', this.selectedIndex);_x000D_
});_x000D_
_x000D_
$('select[class*="select-with-confirm"]').change(function() { _x000D_
if (!confirm("Do you really want to change?")) {_x000D_
this.selectedIndex = $(this).data('lastSelectedIndex');_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select id='fruits' class="select-with-confirm">_x000D_
<option selected value="apples">Apples</option>_x000D_
<option value="bananas">Bananas</option>_x000D_
<option value="melons">Melons</option>_x000D_
</select>_x000D_
_x000D_
<select id='people'>_x000D_
<option selected value="john">John</option>_x000D_
<option value="jack">Jack</option>_x000D_
<option value="jane">Jane</option>_x000D_
</select>
_x000D_
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
Your code was compiled with Java 8.
Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.
Hope this helps...
You could run it without the -jar
command line argument if you happen to know the name of the main class you wish to run:
java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
If perchance you are using linux, you should use ":" instead of ";" in the classpath.
Please check that your key exists in the array or not, instead of simply trying to access it.
Replace:
$myVar = $someArray['someKey']
With something like:
if (isset($someArray['someKey'])) {
$myVar = $someArray['someKey']
}
or something like:
if(is_array($someArray['someKey'])) {
$theme_img = 'recent_works_iso_thumbnail';
}else {
$theme_img = 'recent_works_iso_thumbnail';
}
You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:
If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.
Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.
You can use generic code inspection via instanceof
:
var e = document.getElementById('#my-element');
if (e instanceof HTMLInputElement) {} // <input>
elseif (e instanceof HTMLSelectElement) {} // <select>
elseif (e instanceof HTMLTextAreaElement) {} // <textarea>
elseif ( ... ) {} // any interface
Look here for a complete list of interfaces.
React elements are simple JS, so you can follow the rule of javascript. So you can use a for
loop in javascript like this:-
<tbody>
for (var i=0; i < numrows; i++) {
<ObjectRow/>
}
</tbody>
But the valid and best way is to use the .map
function. Shown below:-
<tbody>
{listObject.map(function(listObject, i){
return <ObjectRow key={i} />;
})}
</tbody>
Here, one thing is necessary: to define the key. Otherwise it will throw a warning like this:-
warning.js:36 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of
ComponentName
. See "link" for more information.
run below command firstly
adb root
adb remount
Then execute what you input previously
C:\anand>adb push anand.jpg /data/local
C:\anand>adb push anand.jpg /data/opt
C:\anand>adb push anand.jpg /data/tmp
My usual approach is
FK_ColumnNameOfForeignKey_TableNameOfReference_ColumnNameOfReference
Or in other terms
FK_ChildColumnName_ParentTableName_ParentColumnName
This way I can name two foreign keys that reference the same table like a history_info table
with column actionBy and actionTo
from users_info
table
It will be like
FK_actionBy_usersInfo_name - For actionBy
FK_actionTo_usersInfo_name - For actionTo
Note that:
I didn't include the child table name because it seems common sense to me, I am in the table of the child so I can easily assume the child's table name. The total character of it is 26 and fits well to the 30 character limit of oracle which was stated by Charles Burns on a comment here
Note for readers: Many of the best practices listed below do not work in Oracle because of its 30 character name limit. A table name or column name may already be close to 30 characters, so a convention combining the two into a single name requires a truncation standard or other tricks. – Charles Burns
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 !
I was having the same issue and was searching for a possible idea to solve this.
I had some CSS already in place for my tabs and this is what worked for me:
(Note specifically the padding-bottom: 2px;
inside #tabs #selected a {
. That hides the bottom box-shadow
neatly and worked great for me with the following CSS.)
#tabs {
margin-top: 1em;
margin-left: 0.5em;
}
#tabs li a {
padding: 1 1em;
position: relative;
top: 1px;
background: #FFFFFF;
}
#tabs #selected {
/* For the "selected" tab */
box-shadow: 0 0 3px #666666;
background: #FFFFFF;
}
#tabs #selected a {
position: relative;
top: 1px;
background: #FFFFFF;
padding-bottom: 2px;
}
#tabs ul {
list-style: none;
padding: 0;
margin: 0;
}
#tabs li {
float: left;
border: 1px solid;
border-bottom-width: 0;
margin: 0 0.5em 0 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
Thought I'd put this out there as another possible solution for anyone perusing SO for this.
Are you using Hibernate's Query
object, or JPA? For JPA, it should work fine:
String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
For Hibernate's, you'll need to use the setParameterList:
String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);
Well, instead of passing Application.Current.MainWindow
, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handle
and so on.
I am both a web developer and a former employee of one of the companies you mentioned. I completely understand where you're coming from. Verifying addresses seems like a simple problem to tackle, but it's very much an iceberg. I suppose one workaround to the legal constraints of the Google or Yahoo! Maps APIs is to request your users verify their addresses on a map. If I were in your shoes, though, I wouldn't go that route.
The reason address verification services are so expensive is that they require licenses and ongoing relationships with grumpy, bureaucratic postal authorities (including the Royal Mail). Unfortunately, postal authorities are the best (and often the only) sources of data against which to verify addresses, so there really isn't any other way to go about it. The bottom line is you need to weigh the cost of bad addresses (usually a question of mail volume) against the cost of the software to verify them. Irish postal data is even more rubbish than Irish postal formats (which frequently omit building numbers), so there's little you can do about those addresses.
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
I always return multiple values by using a combination of list()
and array()
s:
function DecideStuffToReturn() {
$IsValid = true;
$AnswerToLife = 42;
// Build the return array.
return array($IsValid, $AnswerToLife);
}
// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();
You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.
See list()
for more information.
Actually, pywin32
and ctypes
seem to be an overkill for this simple task. Tkinter
is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.
If all you need is to put some text to system clipboard, this will do it:
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
And that's all, no need to mess around with platform-specific third-party libraries.
If you are using Python 3, replace TKinter
with tkinter
.
To compile C or C++ programs, there is a common command:
make filename
./filename
make will build your source file into an executable file with the same name. But if you want to use the standard way, You could use the gcc compiler to build C programs & g++ for c++
For C:
gcc filename.c
./a.out
For C++:
g++ filename.cpp
./a.out
I had similar problem when using Tomcat6.x and none of the advices I found was helping.
At the end I deleted work
folder (of Tomcat) and the problem gone.
I know it is illogical but for documentation purpose...
There are two obvious issues with the set literal syntax:
my_set = {'foo', 'bar', 'baz'}
It's not available before Python 2.7
There's no way to express an empty set using that syntax (using {}
creates an empty dict)
Those may or may not be important to you.
The section of the docs outlining this syntax is here.
As with most things, "it depends". But to me, your practice is not bad and is not going against the HTTP spec per se. However, let's clear some things up.
First, URI's should be opaque. Even if they're not opaque to people, they are opaque to machines. In other words, the difference between http://mywebsite/api/user/13
, http://mywebsite/restapi/user/13
is the same as the difference between http://mywebsite/api/user/13
and http://mywebsite/api/user/14
i.e. not the same is not the same period. So a 404 would be completely appropriate for http://mywebsite/api/user/14
(if there is no such user) but not necessarily the only appropriate response.
You could also return an empty 200 response or more explicitly a 204 (No Content) response. This would convey something else to the client. It would imply that the resource identified by http://mywebsite/api/user/14
has no content or is essentially nothing. It does mean that there is such a resource. However, it does not necessarily mean that you are claiming there is some user persisted in a data store with id 14. That's your private concern, not the concern of the client making the request. So, if it makes sense to model your resources that way, go ahead.
There are some security implications to giving your clients information that would make it easier for them to guess legitimate URI's. Returning a 200 on misses instead of a 404 may give the client a clue that at least the http://mywebsite/api/user
part is correct. A malicious client could just keep trying different integers. But to me, a malicious client would be able to guess the http://mywebsite/api/user
part anyway. A better remedy would be to use UUID's. i.e. http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66
is better than http://mywebsite/api/user/14
. Doing that, you could use your technique of returning 200's without giving much away.
JavaScript arrays can be "empty", in a sense, even if the length of the array is non-zero. For example:
var empty = new Array(10);
var howMany = empty.reduce(function(count, e) { return count + 1; }, 0);
The variable "howMany" will be set to 0
, even though the array was initialized to have a length of 10
.
Thus because many of the Array iteration functions only pay attention to elements of the array that have actually been assigned values, you can use something like this call to .some()
to see if an array has anything actually in it:
var hasSome = empty.some(function(e) { return true; });
The callback passed to .some()
will return true
whenever it's called, so if the iteration mechanism finds an element of the array that's worthy of inspection, the result will be true
.
According to the sqlite docs about table creation, using the create table as select produces a new table without constraints and without primary key.
However, the documentation also says that primary keys and unique indexes are logically equivalent (see constraints section):
In most cases, UNIQUE and PRIMARY KEY constraints are implemented by creating a unique index in the database. (The exceptions are INTEGER PRIMARY KEY and PRIMARY KEYs on WITHOUT ROWID tables.) Hence, the following schemas are logically equivalent:
CREATE TABLE t1(a, b UNIQUE); CREATE TABLE t1(a, b PRIMARY KEY); CREATE TABLE t1(a, b); CREATE UNIQUE INDEX t1b ON t1(b);
So, even if you cannot alter your table definition through SQL alter syntax, you can get the same primary key effect through the use an unique index.
Also, any table (except those created without the rowid syntax) have an inner integer column known as "rowid". According to the docs, you can use this inner column to retrieve/modify record tables.
Here a new answer for an old post.
To pad a binary value with leading zeros to a specific length, try this:
Integer.toBinaryString( (1 << len) | val ).substring( 1 )
If len = 4
and val = 1
,
Integer.toBinaryString( (1 << len) | val )
returns the string "10001"
, then
"10001".substring( 1 )
discards the very first character. So we obtain what we want:
"0001"
If val
is likely to be negative, rather try:
Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )
If you really have to iterate a Pandas dataframe, you will probably want to avoid using iterrows(). There are different methods and the usual iterrows()
is far from being the best. itertuples() can be 100 times faster.
In short:
df.itertuples(name=None)
. In particular, when you have a fixed number columns and less than 255 columns. See point (3)df.itertuples()
except if your columns have special characters such as spaces or '-'. See point (2)itertuples()
even if your dataframe has strange columns by using the last example. See point (4)iterrows()
if you cannot the previous solutions. See point (1)Generate a random dataframe with a million rows and 4 columns:
df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 4)), columns=list('ABCD'))
print(df)
1) The usual iterrows()
is convenient, but damn slow:
start_time = time.clock()
result = 0
for _, row in df.iterrows():
result += max(row['B'], row['C'])
total_elapsed_time = round(time.clock() - start_time, 2)
print("1. Iterrows done in {} seconds, result = {}".format(total_elapsed_time, result))
2) The default itertuples()
is already much faster, but it doesn't work with column names such as My Col-Name is very Strange
(you should avoid this method if your columns are repeated or if a column name cannot be simply converted to a Python variable name).:
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
result += max(row.B, row.C)
total_elapsed_time = round(time.clock() - start_time, 2)
print("2. Named Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))
3) The default itertuples()
using name=None is even faster but not really convenient as you have to define a variable per column.
start_time = time.clock()
result = 0
for(_, col1, col2, col3, col4) in df.itertuples(name=None):
result += max(col2, col3)
total_elapsed_time = round(time.clock() - start_time, 2)
print("3. Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))
4) Finally, the named itertuples()
is slower than the previous point, but you do not have to define a variable per column and it works with column names such as My Col-Name is very Strange
.
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])
total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))
Output:
A B C D
0 41 63 42 23
1 54 9 24 65
2 15 34 10 9
3 39 94 82 97
4 4 88 79 54
... .. .. .. ..
999995 48 27 4 25
999996 16 51 34 28
999997 1 39 61 14
999998 66 51 27 70
999999 51 53 47 99
[1000000 rows x 4 columns]
1. Iterrows done in 104.96 seconds, result = 66151519
2. Named Itertuples done in 1.26 seconds, result = 66151519
3. Itertuples done in 0.94 seconds, result = 66151519
4. Polyvalent Itertuples working even with special characters in the column name done in 2.94 seconds, result = 66151519
This article is a very interesting comparison between iterrows and itertuples
You forget a '}' before the last line (to close the "methods {...").
This code works :
Vue.config.keyCodes.atsign = 50;_x000D_
_x000D_
new Vue({_x000D_
el: '#myApp',_x000D_
data: {_x000D_
emailAddress: '',_x000D_
log: ''_x000D_
},_x000D_
methods: {_x000D_
_x000D_
onEnterClick: function() {_x000D_
alert('Enter was pressed');_x000D_
},_x000D_
_x000D_
onAtSignClick: function() {_x000D_
alert('@ was pressed');_x000D_
},_x000D_
_x000D_
postEmailAddress: function() {_x000D_
this.log += '\n\nPosting';_x000D_
}_x000D_
}_x000D_
})
_x000D_
html, body, #editor {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://vuejs.org/js/vue.min.js"></script>_x000D_
_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
_x000D_
<input type="text" v-model="emailAddress" v-on:keyup.enter="onEnterClick" v-on:keyup.atsign="onAtSignClick" />_x000D_
_x000D_
<button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
<br /><br />_x000D_
_x000D_
<textarea v-model="log" rows="4"></textarea>_x000D_
</div>
_x000D_
To answer the questions directly:
Will
collect()
behave the same way if called on a dataframe?
Yes, spark.DataFrame.collect
is functionally the same as spark.RDD.collect
. They serve the same purpose on these different objects.
What about the
select()
method?
There is no such thing as spark.RDD.select
, so it cannot be the same as spark.DataFrame.select
.
Does it also work the same way as
collect()
if called on a dataframe?
The only thing that is similar between select
and collect
is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.
Here's my own description: collect
is the opposite of sc.parallelize
. select
is the same as the SELECT
in any SQL statement.
If you are still having trouble understanding what collect
actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:
I recommend you to use an unordered list for your image gallery.
You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.
#photos li {
opacity: .5;
transition: opacity .5s ease-out;
-moz-transition: opacity .5s ease-out;
-webkit-transition: opacity .5s ease-out;
-o-transition: opacity .5s ease-out;
}
#photos li:hover {
opacity: 1;
}
To better understand the volume
instruction in dockerfile, let us learn the typical volume usage in mysql official docker file implementation.
VOLUME /var/lib/mysql
Reference: https://github.com/docker-library/mysql/blob/3362baccb4352bcf0022014f67c1ec7e6808b8c5/8.0/Dockerfile
The /var/lib/mysql
is the default location of MySQL that store data files.
When you run test container for test purpose only, you may not specify its mounting point,e.g.
docker run mysql:8
then the mysql container instance will use the default mount path which is specified by the volume
instruction in dockerfile. the volumes is created with a very long ID-like name inside the Docker root, this is called "unnamed" or "anonymous" volume. In the folder of underlying host system /var/lib/docker/volumes.
/var/lib/docker/volumes/320752e0e70d1590e905b02d484c22689e69adcbd764a69e39b17bc330b984e4
This is very convenient for quick test purposes without the need to specify the mounting point, but still can get best performance by using Volume for data store, not the container layer.
For a formal use, you will need to specify the mount path by using named volume or bind mount, e.g.
docker run -v /my/own/datadir:/var/lib/mysql mysql:8
The command mounts the /my/own/datadir directory from the underlying host system as /var/lib/mysql inside the container.The data directory /my/own/datadir won't be automatically deleted, even the container is deleted.
Usage of the mysql official image (Please check the "Where to Store Data" section):
Reference: https://hub.docker.com/_/mysql/
If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:
INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;
If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.
Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.
The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.
Try this one, should work:
cast((convert(bigint,b.tax_id)) as varchar(20))
remove
user.setId(1);
because it is auto generate on the DB, and continue with persist command.
HTML 5 Code Sample
<button href="#" ng-click="shoutOut()" confirmation-needed="Do you really want to
shout?">Click!</button>
AngularJs Custom Directive code-sample
var app = angular.module('mobileApp', ['ngGrid']);
app.directive('confirmationNeeded', function () {
return {
link: function (scope, element, attr) {
var msg = attr.confirmationNeeded || "Are you sure?";
var clickAction = attr.ngClick;
element.bind('click',function (e) {
scope.$eval(clickAction) if window.confirm(msg)
e.stopImmediatePropagation();
e.preventDefault();
});
}
};
});
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
In case if you're trying to deploy a project using VSTS, then issue might be connected with checking "Hosted Windows Container" option instead of "Hosted VS2017"(or 18, etc.):
@Min
and @Max
are used for validating numeric fields which could be String
(representing number), int
, short
, byte
etc and their respective primitive wrappers.
@Size
is used to check the length constraints on the fields.
As per documentation @Size
supports String
, Collection
, Map
and arrays
while @Min
and @Max
supports primitives and their wrappers. See the documentation.
You're missing a GROUP BY clause:
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.
For Apache 2.4.9
in addition, look at the httpd-vhosts.conf file in C:\wamp\bin\apache\apache2.4.9\conf\extra
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require local
</Directory>
</VirtualHost>
Change to:
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
</VirtualHost>
changing from "Require local" to "Require all granted" solved the error 403 in my local network
MySQL use HAVING statement for this tasks.
Your query would look like this:
SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4
example when references have different names
SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4
Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.
Starting with vim
v7.4 you can use
:set nofixendofline
There is some information about that change here: http://ftp.vim.org/vim/patches/7.4/7.4.785 .
If you need to diff on a single file in a stash for example you can do
git diff stash@{0} -- path/to/file
For Spooling in Oracle SQL Developer, here is the solution.
set heading on
set linesize 1500
set colsep '|'
set numformat 99999999999999999999
set pagesize 25000
spool E:\abc.txt
@E:\abc.sql;
spool off
The hint is :
when we spool from sql plus , then the whole query is required.
when we spool from Oracle Sql Developer , then the reference path of the query required as given in the specified example.
Inspired by the answers of @Mark and @Myrddin I created this function for a universal prompt
uniprompt(){
while true; do
echo -e "$1\c"
read opt
array=($2)
case "${array[@]}" in *"$opt"*) eval "$3=$opt";return 0;; esac
echo -e "$opt is not a correct value\n"
done
}
use it like this:
unipromtp "Select an option: (a)-Do one (x)->Do two (f)->Do three : " "a x f" selection
echo "$selection"
I developed a noSQL database for storing DOM trees in Web Browsers where references to all DOM elements on page are stored in a short index. Thus function "getElementById()" is not needed to get/modify an element. When elements in DOM tree are instantiated on page the database assigns surrogate primary keys to each element. It is a free tool http://js2dx.com
My text marquee for more text, and position absolute enabled
http://jsfiddle.net/zrW5q/2075/
(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: 'auto',
'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, {
count: -1,
speed: 1e1,
leftToRight: false
}, args),
i = 0,
stop = textWidth * -1,
dfd = $.Deferred();
function go() {
if (that.css('overflow') != "hidden") {
that.css('text-indent', width + 'px');
return false;
}
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i == args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {
$(this).removeAttr("style");
}).mouseout(function () {
$(this).marquee();
});
})(jQuery);
Something that works for me. Enjoy.
Excel.Application excelApplication = new Excel.Application() // start excel and turn off msg boxes
{
DisplayAlerts = false,
Visible = false
};
Excel.Workbook workBook = excelApplication.Workbooks.Open(targetFile);
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Worksheets[1];
var rDT = workSheet.Range(workSheet.Cells[monthYearNameRow, monthYearNameCol], workSheet.Cells[monthYearNameRow, maxTableColumnIndex]);
rDT.Merge();
rDT.Value = monthName + " " + year;
var reportDateRowStyle = workBook.Styles.Add("ReportDateRowStyle");
reportDateRowStyle.HorizontalAlignment = XlHAlign.xlHAlignCenter;
reportDateRowStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
reportDateRowStyle.Font.Bold = true;
reportDateRowStyle.Font.Size = 14;
rDT.Style = reportDateRowStyle;
In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.
In a few words, an authentication scheme based on tokens follow these steps:
Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).
This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.
It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml
descriptor. It's a custom authentication.
Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:
@Path("/authentication")
public class AuthenticationEndpoint {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam("username") String username,
@FormParam("password") String password) {
try {
// Authenticate the user using the credentials provided
authenticate(username, password);
// Issue a token for the user
String token = issueToken(username);
// Return the token on the response
return Response.ok(token).build();
} catch (Exception e) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
private void authenticate(String username, String password) throws Exception {
// Authenticate against a database, LDAP, file or whatever
// Throw an Exception if the credentials are invalid
}
private String issueToken(String username) {
// Issue a token (can be a random String persisted to a database or a JWT token)
// The issued token must be associated to a user
// Return the issued token
}
}
If any exceptions are thrown when validating the credentials, a response with the status 403
(Forbidden) will be returned.
If the credentials are successfully validated, a response with the status 200
(OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.
When consuming application/x-www-form-urlencoded
, the client must to send the credentials in the following format in the request payload:
username=admin&password=123456
Instead of form params, it's possible to wrap the username and the password into a class:
public class Credentials implements Serializable {
private String username;
private String password;
// Getters and setters omitted
}
And then consume it as JSON:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {
String username = credentials.getUsername();
String password = credentials.getPassword();
// Authenticate the user, issue a token and return a response
}
Using this approach, the client must to send the credentials in the following format in the payload of the request:
{
"username": "admin",
"password": "123456"
}
The client should send the token in the standard HTTP Authorization
header of the request. For example:
Authorization: Bearer <token-goes-here>
The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.
JAX-RS provides @NameBinding
, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured
annotation as following:
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }
The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter
, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext
can be used to access the HTTP request headers and then extract the token:
@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
private static final String REALM = "example";
private static final String AUTHENTICATION_SCHEME = "Bearer";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Validate the Authorization header
if (!isTokenBasedAuthentication(authorizationHeader)) {
abortWithUnauthorized(requestContext);
return;
}
// Extract the token from the Authorization header
String token = authorizationHeader
.substring(AUTHENTICATION_SCHEME.length()).trim();
try {
// Validate the token
validateToken(token);
} catch (Exception e) {
abortWithUnauthorized(requestContext);
}
}
private boolean isTokenBasedAuthentication(String authorizationHeader) {
// Check if the Authorization header is valid
// It must not be null and must be prefixed with "Bearer" plus a whitespace
// The authentication scheme comparison must be case-insensitive
return authorizationHeader != null && authorizationHeader.toLowerCase()
.startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
}
private void abortWithUnauthorized(ContainerRequestContext requestContext) {
// Abort the filter chain with a 401 status code response
// The WWW-Authenticate header is sent along with the response
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE,
AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
.build());
}
private void validateToken(String token) throws Exception {
// Check if the token was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
}
}
If any problems happen during the token validation, a response with the status 401
(Unauthorized) will be returned. Otherwise the request will proceed to a resource method.
To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured
annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.
If some methods or classes do not need authentication, simply do not annotate them:
@Path("/example")
public class ExampleResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myUnsecuredMethod(@PathParam("id") Long id) {
// This method is not annotated with @Secured
// The authentication filter won't be executed before invoking this method
...
}
@DELETE
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response mySecuredMethod(@PathParam("id") Long id) {
// This method is annotated with @Secured
// The authentication filter will be executed before invoking this method
// The HTTP request must be performed with a valid token
...
}
}
In the example shown above, the filter will be executed only for the mySecuredMethod(Long)
method because it's annotated with @Secured
.
It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:
Within your ContainerRequestFilter.filter(ContainerRequestContext)
method, a new SecurityContext
instance can be set for the current request. Then override the SecurityContext.getUserPrincipal()
, returning a Principal
instance:
final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return () -> username;
}
@Override
public boolean isUserInRole(String role) {
return true;
}
@Override
public boolean isSecure() {
return currentSecurityContext.isSecure();
}
@Override
public String getAuthenticationScheme() {
return AUTHENTICATION_SCHEME;
}
});
Use the token to look up the user identifier (username), which will be the Principal
's name.
Inject the SecurityContext
in any JAX-RS resource class:
@Context
SecurityContext securityContext;
The same can be done in a JAX-RS resource method:
@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id,
@Context SecurityContext securityContext) {
...
}
And then get the Principal
:
Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();
If, for some reason, you don't want to override the SecurityContext
, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.
Create a CDI qualifier:
@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }
In your AuthenticationFilter
created above, inject an Event
annotated with @AuthenticatedUser
:
@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;
If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):
userAuthenticatedEvent.fire(username);
It's very likely that there's a class that represents a user in your application. Let's call this class User
.
Create a CDI bean to handle the authentication event, find a User
instance with the correspondent username and assign it to the authenticatedUser
producer field:
@RequestScoped
public class AuthenticatedUserProducer {
@Produces
@RequestScoped
@AuthenticatedUser
private User authenticatedUser;
public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
this.authenticatedUser = findUser(username);
}
private User findUser(String username) {
// Hit the the database or a service to find a user by its username and return it
// Return the User instance
}
}
The authenticatedUser
field produces a User
instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User
instance (in fact, it's a CDI proxy):
@Inject
@AuthenticatedUser
User authenticatedUser;
Note that the CDI @Produces
annotation is different from the JAX-RS @Produces
annotation:
javax.enterprise.inject.Produces
javax.ws.rs.Produces
Be sure you use the CDI @Produces
annotation in your AuthenticatedUserProducer
bean.
The key here is the bean annotated with @RequestScoped
, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.
Compared to the approach that overrides the SecurityContext
, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.
Please refer to my other answer for details on how to support role-based authorization.
A token can be:
See details below:
A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:
Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.
It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):
iss
: Principal that issued the token.sub
: Principal that is the subject of the JWT.exp
: Expiration date for the token.nbf
: Time on which the token will start to be accepted for processing.iat
: Time on which the token was issued. jti
: Unique identifier for the token.Be aware that you must not store sensitive data, such as passwords, in the token.
The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.
You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti
claim) along with some other details such as the user you issued the token for, the expiration date, etc.
When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.
There are a few Java libraries to issue and validate JWT tokens such as:
To find some other great resources to work with JWT, have a look at http://jwt.io.
If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.
The jti
claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti
claim against the token identifiers you have on server side.
For security purposes, revoke all the tokens for a user when they change their password.
Take a look at String.format. Note, however, that it takes format specifiers similar to those of C's printf family of functions -- for example:
String.format("Hello %s, %d", "world", 42);
Would return "Hello world, 42". You may find this helpful when learning about the format specifiers. Andy Thomas-Cramer was kind enough to leave this link in a comment below, which appears to point to the official spec. The most commonly used ones are:
This is radically different from C#, which uses positional references with an optional format specifier. That means that you can't do things like:
String.format("The {0} is repeated again: {0}", "word");
... without actually repeating the parameter passed to printf/format. (see The Scrum Meister's comment below)
If you just want to print the result directly, you may find System.out.printf (PrintStream.printf) to your liking.
It allocates that much space according to the value of n and pointer will point to the array i.e the 1st element of array
int *array = new int[n];
Even though the proposed solution works, it might not be the best solution for every case because based on the documentation for ViewTreeObserver.OnGlobalLayoutListener
Interface definition for a callback to be invoked when the global layout state or the visibility of views within the view tree changes.
which means it gets called many times and not always the view is measured (it has its height and width determined)
An alternative is to use ViewTreeObserver.OnPreDrawListener
which gets called only when the view is ready to be drawn and has all of its measurements.
final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnPreDrawListener(new OnPreDrawListener() {
@Override
public void onPreDraw() {
tv.getViewTreeObserver().removeOnPreDrawListener(this);
// Your view will have valid height and width at this point
tv.getHeight();
tv.getWidth();
}
});
your code
SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01'
how SQL reading it
SELECT * FROM Cases WHERE '2013-05-01 22:25:19' BETWEEN '2013-05-01 00:00:00' AND '2013-05-01 00:00:00'
if you don't mention time while comparing DateTime and Date by default hours:minutes:seconds will be zero in your case dates are the same but if you compare time created_at
is 22 hours
ahead from your end date range
if the above is clear you fix this in many ways like putting ending hours in your end date eg BETWEEN '2013-05-01' AND ''2013-05-01 23:59:59''
OR
simply cast create_at as date like cast(created_at as date)
after casting as date '2013-05-01 22:25:19'
will be equal to '2013-05-01 00:00:00'
def query(id):
for line in file:
table = line.split(";")
if id == int(table[0]):
yield table
id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
print("ID: " + id_)
print("Name: " + name)
print("City: " + city)
file.close()
Using yield..
Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.
0 == false // true
0 === false // false, because they are of a different type
1 == "1" // true, automatic type conversion for value only
1 === "1" // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
If the DataGridView
has been populated by DataSource = x
(i.e. is databound) then you need to change the bound data, not the DataGridView cells themselves.
One way of getting to that data from a known row or column is thus:
(YourRow.DataBoundItem as DataRowView).Row['YourColumn'] = NewValue;
The other answers here rely on the user making an initial click (on the image). This is fine for the specifics of the OP detail but not necessarily the question title.
There is an answer here explaining how to do it by firing a click event on the button ( or any element ).
Here is how to get the value of a hidden column in a GridView
that is set to Visible=False
: add the data field in this case SpecialInstructions
to the DataKeyNames property of the bound GridView , and access it this way.
txtSpcInst.Text = GridView2.DataKeys(GridView2.SelectedIndex).Values("SpecialInstructions")
That's it, it works every time very simple.
The tidyverse
version is this:
> library(dplyr)
> library(scales)
> set.seed(1)
> m <- runif(5)
> dt <- as.data.frame(m)
> dt %>% mutate(perc=percent(m,accuracy=0.001))
m perc
1 0.2655087 26.551%
2 0.3721239 37.212%
3 0.5728534 57.285%
4 0.9082078 90.821%
5 0.2016819 20.168%
Looks tidy as usual.
On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize
printed : uintx MaxHeapSize := 266338304
, which is approx 266MB and is 1/4th of my total RAM.
In Jan2018 the only solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
Try with paramter
.....................
.....................
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
{
command.Paramter.Add("@IDNumber",IDNumber)
command.ExecuteNonQuery();
}
.....................
.....................
No need to close connection in using statement
Code snippets from my CAE project with unicode development environment:
/// @brief Gets current module file path.
std::string getModuleFilePath() {
TCHAR buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH );
CT2CA pszPath(buffer);
std::string path(pszPath);
std::string::size_type pos = path.find_last_of("\\/");
return path.substr( 0, pos);
}
Just use the templete CA2CAEX or CA2AEX which calls the internal API ::MultiByteToWideChar or ::WideCharToMultiByte?
Why not store the function itself? myvar = mypackage.mymodule.myfunction
is much cleaner.
What you really want to do is to remove any string that starts with either http://
or https://
plus any combination of non white space characters. Here is how I would solve it. My solution is very similar to that of @tolgayilmaz
#Define the text from which you want to replace the url with "".
text ='''The link to this post is https://stackoverflow.com/questions/11331982/how-to-remove-any-url-within-a-string-in-python'''
import re
#Either use:
re.sub('http://\S+|https://\S+', '', text)
#OR
re.sub('http[s]?://\S+', '', text)
And the result of running either code above is
>>> 'The link to this post is '
I prefer the second one because it is more readable.
you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...
View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);
You can do like this
SELECT something
FROM
(a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'
Nope, doing a simple comparison looks good to me:
return dateToCheck >= startDate && dateToCheck < endDate;
Things to think about though:
DateTime
is a somewhat odd type in terms of time zones. It could be UTC, it could be "local", it could be ambiguous. Make sure you're comparing apples with apples, as it were.I know you can look up IP address to get approximate location, but it's not always accurate. Perhaps they're using that?
update:
Typically, your browser uses information about the Wi-Fi access points around you to estimate your location. If no Wi-Fi access points are in range, or your computer doesn't have Wi-Fi, it may resort to using your computer's IP address to get an approximate location.
Else is executed if while loop did not break.
I kinda like to think of it with a 'runner' metaphor.
The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).
For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:
for i in [1,2,3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 b
# Finished
In app.module.ts:
Add imports:
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
And in NgModule provider, add:
{provide: LocationStrategy, useClass: HashLocationStrategy}
Example (app.module.ts):
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
bootstrap: [AppComponent],
})
export class AppModule {}
Use RouterModule.forRoot with the {useHash: true} argument.
Example:(from angular docs)
import { NgModule } from '@angular/core';
...
const routes: Routes = [//routes in here];
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes, { useHash: true })
],
bootstrap: [AppComponent]
})
export class AppModule { }
This is how I solved it. I forgot that sublist was a direct reference to the elements in the original list, so it makes sense why it wouldn't work.
ArrayList<Integer> inputA = new ArrayList<Integer>(input.subList(0, input.size()/2));
Best I can give you is a "works for me" on SVN 1.5. You may try adding --no-auth-cache
to your svn update
to see if that lets you override more easily.
If you want to permanently switch from user2 to user1, head into ~/.subversion/auth/ on *nix and delete the auth cache file for domain.com (most likely in ~/.subversion/auth/svn.simple/ -- just read through them and you'll find the one you want to drop). While it is possible to update the current auth cache, you have to make sure to update the length tokens as well. Simpler just to get prompted again next time you update.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
If you just want to resize the div itself you need to specify that in css style. You need to add overflow and resize property.
Below is my code snippet
#div1 {
width: 90%;
height: 350px;
padding: 10px;
border: 1px solid #aaaaaa;
overflow: auto;
resize: both;
}
<div id="div1">
</div>
try using dedicated functions from high level programming languages. JavaScript .getSeconds();
suits here:
var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds();
var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds();
alert(specifiedTimeSeconds-currentTimeSeconds);
/* This example uses an XML variable with a schema */
IF EXISTS (SELECT * FROM sys.xml_schema_collections
WHERE name = 'OrderingAfternoonTea')
BEGIN
DROP XML SCHEMA COLLECTION dbo.OrderingAfternoonTea
END
GO
CREATE XML SCHEMA COLLECTION dbo.OrderingAfternoonTea AS
N'<?xml version="1.0" encoding="UTF-16" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://Tfor2.com/schemas/actions/orderAfternoonTea"
xmlns="http://Tfor2.com/schemas/actions/orderAfternoonTea"
xmlns:TFor2="http://Tfor2.com/schemas/actions/orderAfternoonTea"
elementFormDefault="qualified"
version="0.10"
>
<xsd:complexType name="AfternoonTeaOrderType">
<xsd:sequence>
<xsd:element name="potsOfTea" type="xsd:int"/>
<xsd:element name="cakes" type="xsd:int"/>
<xsd:element name="fruitedSconesWithCream" type="xsd:int"/>
<xsd:element name="jams" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="schemaVersion" type="xsd:long" use="required"/>
</xsd:complexType>
<xsd:element name="afternoonTeaOrder"
type="TFor2:AfternoonTeaOrderType"/>
</xsd:schema>' ;
GO
DECLARE @potsOfTea int;
DECLARE @cakes int;
DECLARE @fruitedSconesWithCream int;
DECLARE @jams nvarchar(128);
DECLARE @RequestMsg NVARCHAR(2048);
DECLARE @RequestXml XML(dbo.OrderingAfternoonTea);
set @potsOfTea = 5;
set @cakes = 7;
set @fruitedSconesWithCream = 25;
set @jams = N'medlar jelly, quince and mulberry';
SELECT @RequestMsg = N'<?xml version="1.0" encoding="utf-16" ?>
<TFor2:afternoonTeaOrder schemaVersion="10"
xmlns:TFor2="http://Tfor2.com/schemas/actions/orderAfternoonTea">
<TFor2:potsOfTea>' + CAST(@potsOfTea as NVARCHAR(20))
+ '</TFor2:potsOfTea>
<TFor2:cakes>' + CAST(@cakes as NVARCHAR(20)) + '</TFor2:cakes>
<TFor2:fruitedSconesWithCream>'
+ CAST(@fruitedSconesWithCream as NVARCHAR(20))
+ '</TFor2:fruitedSconesWithCream>
<TFor2:jams>' + @jams + '</TFor2:jams>
</TFor2:afternoonTeaOrder>';
SELECT @RequestXml = CAST(CAST(@RequestMsg AS VARBINARY(MAX)) AS XML) ;
with xmlnamespaces('http://Tfor2.com/schemas/actions/orderAfternoonTea'
as tea)
select
cast( x.Rec.value('.[1]/@schemaVersion','nvarchar(20)') as bigint )
as schemaVersion,
cast( x.Rec.query('./tea:potsOfTea')
.value('.','nvarchar(20)') as bigint ) as potsOfTea,
cast( x.Rec.query('./tea:cakes')
.value('.','nvarchar(20)') as bigint ) as cakes,
cast( x.Rec.query('./tea:fruitedSconesWithCream')
.value('.','nvarchar(20)') as bigint )
as fruitedSconesWithCream,
x.Rec.query('./tea:jams').value('.','nvarchar(50)') as jams
from @RequestXml.nodes('/tea:afternoonTeaOrder') as x(Rec);
select @RequestXml.query('/*')
For me, I was trying to match up a regular indexed field in a child table, to a primary key in the parent table, and by default some MySQL frontend GUIs like Sequel Pro set the primary key as unsigned, so you have to make sure that the child table field is unsigned too (unless these fields might contain negative ints, then make sure they're both signed).
You can create a util method that converts any collection to a java list
public static List<?> convertObjectToList(Object obj) {
List<?> list = new ArrayList<>();
if (obj.getClass().isArray()) {
list = Arrays.asList((Object[])obj);
} else if (obj instanceof Collection) {
list = new ArrayList<>((Collection<?>)obj);
}
return list;
}
you can also mix with this validation below:
public static boolean isCollection(Object obj) {
return obj.getClass().isArray() || obj instanceof Collection;
}
This will enable appending to file using StreamWriter
using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}
This is default mode, not append to file and create a new file.
using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}
Anyhow if you want to check if the file exists and then do other things,you can use
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{...}
you have to call set and add functions on chart object before calling redraw.
chart.xAxis[0].setCategories([2,4,5,6,7], false);
chart.addSeries({
name: "acx",
data: [4,5,6,7,8]
}, false);
chart.redraw();
The output of head -10 file
can be piped to grep
in order to accomplish this:
head -10 file | grep …
Using Perl:
perl -ne 'last if $. > 10; print if /pattern/' file
The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.
WITH PivotCTE AS
(
select * from mytransactions
pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
numericmonth,
chardate,
SUM(totalamount) AS totalamount,
SUM(ISNULL(Australia, 0)) AS Australia,
SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate
The ISNULL
is to stop a NULL
value from nullifying the sum (because NULL
+ any value = NULL
)
Also note that despite errors being hidden, any custom error handler (set with set_error_handler
) will still be executed!
I would use:
if (Stream.of("a","b","c").anyMatch("a"::equals)) {
//Code to execute
};
or:
Stream.of("a","b","c")
.filter("a"::equals)
.findAny()
.ifPresent(ignore -> /*Code to execute*/);
Checking the Options Over Write Database worked for me :)
I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.
after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.
I've found Waldo!
How I've done it
First, I'm filtering out all colours that aren't red
waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];
Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.
corr = ImageCorrelate[red,
Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]],
NormalizedSquaredEuclideanDistance];
I use Binarize
to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation
pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];
I had to play around a little with the level. If the level is too high, too many false positives are picked out.
Finally I'm combining this result with the original image to get the result above
found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]
For me it was the difference between
var response = Request.CreateResponse(HttpStatusCode.OK, new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
and
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
The first one was returning the JSON representation of StringContent: {"Headers":[{"Key":"Content-Type","Value":["application/octet-stream; charset=utf-8"]}]}
While the second one was returning the file proper.
It seems that Request.CreateResponse has an overload that takes a string as the second parameter and this seems to have been what was causing the StringContent object itself to be rendered as a string, instead of the actual content.
I found that this works if wanting in a (123) - 456-7890 format.
UPDATE table
SET Phone_number = '(' +
SUBSTRING(Phone_number, 1, 3)
+ ') '
+ '- ' +
SUBSTRING(Phone_number, 4, 3)
+ '-' +
SUBSTRING(Phone_number, 7, 4)
For general updating table1 specific colom based on Table2 specific colom, below query works perfectly...
UPDATE table 1
SET Col 2 = t2.Col2,
Col 3 = t2.Col3
FROM table1 t1
INNER JOIN table 2 t2 ON t1.Col1 = t2.col1
This answer, but with storyboard support.
class SwipeNavigationController: UINavigationController {
// MARK: - Lifecycle
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup() {
delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// This needs to be in here, not in init
interactivePopGestureRecognizer?.delegate = self
}
deinit {
delegate = nil
interactivePopGestureRecognizer?.delegate = nil
}
// MARK: - Overrides
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
duringPushAnimation = true
super.pushViewController(viewController, animated: animated)
}
// MARK: - Private Properties
fileprivate var duringPushAnimation = false
}
iisexpress
program is responsible for that.
http://www.iis.net/learn/extensions/using-iis-express/running-iis-express-from-the-command-line
Add 'justified' class to 'ul'.
<ul class="nav navbar-nav justified">
CSS:
.justified {
position:absolute;
left:50%;
}
Now, calculate its 'margin-left' in order to align it to center
.
// calculating margin-left to align it to center;
var width = $('.justified').width();
$('.justified').css('margin-left', '-' + (width / 2)+'px');
Java 8 Lambda shortens the sort.
Collections.sort(stdList, (o1, o2) -> o1.getName().compareTo(o2.getName()));
Try this:
Create a model called Profile
and reference the user with a OneToOneField
and provide an option of related_name
.
models.py
from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
try:
if created:
Profile.objects.create(user=instance).save()
except Exception as err:
print('Error creating user profile!')
Now to directly access the profile using a User
object you can use the related_name
.
views.py
from django.http import HttpResponse
def home(request):
profile = f'profile of {request.user.user_profile}'
return HttpResponse(profile)
If you want to get value from a mapped select input then you can refer to this example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fruit: "banana",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log("Fruit Selected!!");
this.setState({ fruit: e.target.value });
}
render() {
return (
<div id="App">
<div className="select-container">
<select value={this.state.fruit} onChange={this.handleChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</div>
</div>
);
}
}
export default App;
Anything that is not mutable (mutable means, likely to change) can be hashed. Besides the hash function to look for, if a class has it, by eg. dir(tuple)
and looking for the __hash__
method, here are some examples
#x = hash(set([1,2])) #set unhashable
x = hash(frozenset([1,2])) #hashable
#x = hash(([1,2], [2,3])) #tuple of mutable objects, unhashable
x = hash((1,2,3)) #tuple of immutable objects, hashable
#x = hash()
#x = hash({1,2}) #list of mutable objects, unhashable
#x = hash([1,2,3]) #list of immutable objects, unhashable
List of immutable types:
int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes
List of mutable types:
list, dict, set, bytearray, user-defined classes
You can always make it a function
function writeObject(color){
$('body').append('<div style="color:'+color+';">Hello!</div>')
}
writeObject('blue')
?
There is an "onunload" parameter for the body tag you can call javascript functions from there. If it returns false it prevents navigating away.
While this is one of the most voted feature requests, there is one plugin available, by Victor Kropp, that adds support to makefiles:
Makefile support plugin for IntelliJ IDEA
You can install directly from the official repository:
Settings > Plugins > search for makefile
> Search in repositories > Install > Restart
There are at least three different ways to run:
It opens a pane named Run target with the output.
Sometimes, this error pops up because of the kernel has reached its limit. Try to restart the kernel redo the necessary steps.
It's not really a function of git, msys, or bash; every windows console program is stuck using the same cumbersome copy/paste mechanism for historical reasons. Turning on QuickEdit mode can help -- or you can install a nice alternative console like this one, and change your git bash shortcut to use it instead.
body.bg {
background-size: cover;
background-repeat: no-repeat;
min-height: 100vh;
background: white url(../images/bg-404.jpg) center center no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
Try This
_x000D_
_x000D_
body.bg {_x000D_
background-size: cover;_x000D_
background-repeat: no-repeat;_x000D_
min-height: 100vh;_x000D_
background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
}
_x000D_
<body class="bg">_x000D_
_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_
Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".
The easiest way to do this would be to export the project as a template and save it to the default template location. Then, copy the template into the exact same directory on the location you want to move it to. After that, open up visual studio on the new location, create a new project, and you will get a prompt to search for a template. Search for whatever you named the template, select it and you're done!
I had a similar bug, but while using a fixed number for height and not a percentage. It was also a flex container within the body (which has no specified height). It appeared that on Safari, my flex container had a height of 9px for some reason, but in all other browsers it displayed the correct 100px height specified in the stylesheet.
I managed to get it to work by adding both the height
and min-height
properties to the CSS class.
The following worked for me on both Safari 13.0.4 and Chrome 79.0.3945.130:
.flex-container {
display: flex;
flex-direction: column;
min-height: 100px;
height: 100px;
}
Hope this helps!
For the current MS SQL JDBC driver (6.4.0) tested under Windows 7 from within DataGrip:
server.your.domain
not just server
; the documentation also mentions the possibility to specify serverSpn=MSSQLSvc/fqdn:port@REALM
, but I can not provide you with details on how to use this. When specifying a fqdn as host the spn is auto-generated.authenticationScheme=JavaKerberos
integratedSecurity=true
As this is using JavaKerberos I would appreciate feedback on whether or not this works from outside Windows. I believe that no .dll is needed, but as I used DataGrip to create the connection I am uncertain; I would also appreciate Feedback on this!
As has, to some extent, been mentioned before, an enum is a java class with the special condition that its definition must start with at least one "enum constant".
Apart from that, and that enums cant can't be extended or used to extend other classes, an enum is a class like any class and you use it by adding methods below the constant definitions:
public enum MySingleton {
INSTANCE;
public void doSomething() { ... }
public synchronized String getSomething() { return something; }
private String something;
}
You access the singleton's methods along these lines:
MySingleton.INSTANCE.doSomething();
String something = MySingleton.INSTANCE.getSomething();
The use of an enum, instead of a class, is, as has been mentioned in other answers, mostly about a thread-safe instantiation of the singleton and a guarantee that it will always only be one copy.
And, perhaps, most importantly, that this behavior is guaranteed by the JVM itself and the Java specification.
Here's a section from the Java specification on how multiple instances of an enum instance is prevented:
An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.
Worth noting is that after the instantiation any thread-safety concerns must be handled like in any other class with the synchronized keyword etc.
Cant update the DB row. I was facing the same error. Now working with following code:
_context.Entry(_SendGridSetting).CurrentValues.SetValues(vm);
await _context.SaveChangesAsync();
This error also appears if the partition on which tmpdir
resides fills up (due to an alter table or other
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
slf4j is only an API. You should have a concrete implementation (for example log4j). This concrete implementation has a config file which tells you where to store the logs.
When slf4j catches a log messages with a logger, it is given to an appender which decides what to do with the message. By default, the ConsoleAppender displays the message in the console.
The default configuration file is :
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<!-- By default => console -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
If you put a configuration file available in the classpath, then your concrete implementation (in your case, log4j) will find and use it. See Log4J documentation.
Example of file appender :
<Appenders>
<File name="File" fileName="${filename}">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
...
</Appenders>
Complete example with a file appender :
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="File" fileName="${filename}">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
Inside the DataTemplate
you're working in the context of a Rule
, that's why you cannot bind to SelectedRule.Name
-- there is no such property on a Rule
.
To bind to the original data context (which is your ViewModel) you can write:
<TextBlock Text="{Binding ElementName=lbRules, Path=DataContext.SelectedRule.Name}" />
UPDATE: regarding the SelectedItem property binding, it looks perfectly valid, I tried the same on my machine and it works fine. Here is my full test app:
XAML:
<Window x:Class="TestWpfApplication.ListBoxSelectedItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ListBoxSelectedItem" Height="300" Width="300"
xmlns:app="clr-namespace:TestWpfApplication">
<Window.DataContext>
<app:ListBoxSelectedItemViewModel/>
</Window.DataContext>
<ListBox ItemsSource="{Binding Path=Rules}" SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:" />
<TextBox Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
Code behind:
namespace TestWpfApplication
{
/// <summary>
/// Interaction logic for ListBoxSelectedItem.xaml
/// </summary>
public partial class ListBoxSelectedItem : Window
{
public ListBoxSelectedItem()
{
InitializeComponent();
}
}
public class Rule
{
public string Name { get; set; }
}
public class ListBoxSelectedItemViewModel
{
public ListBoxSelectedItemViewModel()
{
Rules = new ObservableCollection<Rule>()
{
new Rule() { Name = "Rule 1"},
new Rule() { Name = "Rule 2"},
new Rule() { Name = "Rule 3"},
};
}
public ObservableCollection<Rule> Rules { get; private set; }
private Rule selectedRule;
public Rule SelectedRule
{
get { return selectedRule; }
set
{
selectedRule = value;
}
}
}
}
Try this regex:
"href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))"
You will get more help from discussions over:
Regular expression to extract URL from an HTML link
and
Regex to get the link in href. [asp.net]
Hope its helpful.
$('#summary').load('ajax.php', function() {
alert('Loaded.');
});
let's say if we have python 3.7 and python 3.6 installed.
they are respectively stored in following folder by default.
C:\Users\name\AppData\Local\Programs\Python\Python36 C:\Users\name\AppData\Local\Programs\Python\Python37
if we want to use cmd prompt to install/run command in any of the above specific environment do this:
There should be python.exe in each of the above folder.
so when we try running any file for ex. (see image1) python hello.py
. we call that respective python.exe. by default it picks lower version of file. (means in this case it will use from python 3.6 )
so if we want to run using python3.7. just change the .exe file name. for ex. if I change to python37.exe and i want to use python3.7 to run hello.py
I will use python37 hello.py
. or if i want to use python3.7 by default i will change the python.exe filename in python3.6 folder to something else . so that it will use python3.7 each time when I use only python hello.py
No. But there are other options out there like Overlib, and jQuery that allow you this freedom.
Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).
What I am thinking is having webpack would be easy when production release.
You can use find_package to search for available boost libraries. It defers searching for Boost to FindBoost.cmake, which is default installed with CMake.
Upon finding Boost, the find_package()
call will have filled many variables (check the reference for FindBoost.cmake). Among these are BOOST_INCLUDE_DIRS
, Boost_LIBRARIES and Boost_XXX_LIBRARY variabels, with XXX replaced with specific Boost libraries. You can use these to specify include_directories and target_link_libraries.
For example, suppose you would need boost::program_options and boost::regex, you would do something like:
find_package( Boost REQUIRED COMPONENTS program_options regex )
include_directories( ${Boost_INCLUDE_DIRS} )
add_executable( run main.cpp ) # Example application based on main.cpp
# Alternatively you could use ${Boost_LIBRARIES} here.
target_link_libraries( run ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_REGEX_LIBRARY} )
Some general tips:
On
: Boost_USE_STATIC_LIBS
, Boost_USE_MULTITHREADED
, Boost_USE_STATIC_RUNTIME
add_definitions( -DBOOST_ALL_NO_LIB )
add_definitions( -DBOOST_ALL_DYN_LINK )
If you already define your view in your layout(xml) file, only want to change the weight programmatically, this way is better
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);
new a LayoutParams overwrites other params defined in you xml file like margins, or you need to specify all of them in LayoutParams.
I had the same issue with Excel, I was trying to use a 32 COM DLL with an Excel 64 bits version and I got this error. I rebuild the COM dll to a 64 bits version and the error disappears. So be sure that your COM dll has the same architecture (x86 vs x64) than your application.
From the Java Documentation:
[...] More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:
<T extends Annotation> T getAnnotation(Class<T> annotationType);
This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:
Author a = Othello.class.getAnnotation(Author.class);
Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation. [...]
Well, I never had to use this kind of stuff. Anyone?
Update after 6 years: now I consider that the approach below is pretty bad. To create a retry logic we should consider to use a library like Polly.
My async
implementation of the retry method:
public static async Task<T> DoAsync<T>(Func<dynamic> action, TimeSpan retryInterval, int retryCount = 3)
{
var exceptions = new List<Exception>();
for (int retry = 0; retry < retryCount; retry++)
{
try
{
return await action().ConfigureAwait(false);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
await Task.Delay(retryInterval).ConfigureAwait(false);
}
throw new AggregateException(exceptions);
}
Key points: I used .ConfigureAwait(false);
and Func<dynamic>
instead Func<T>
you could do this, if you want to use the old syntax (or don't want to rewrite every template)
@for $i from 1 through $grid-columns {
@include media-breakpoint-up(xs) {
.col-xs-#{$i} {
@include make-col-ready();
@include make-col($i);
}
}
}
I had similar situation. I found that one of my config maps was duplicated. I had two configmaps for the same namespace. One had the correct namespace reference, the other was pointing to the wrong namespace.
I deleted and recreated the configmap with the correct file (or fixed file). I am only using one, and that seemed to make the particular cluster happier.
So I would check the files for any typos or duplicate items that could be causing conflict.
This seems to work:
$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);
theDiv.slideDown().removeClass("hidden");
//Add this...
$("#theSelect option:selected").attr('disabled', 'disabled');
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
//...and this.
$("#theSelect option:disabled").removeAttr('disabled');
});
^
for start of the string pattern,
?
for allowing 0 or 1 time repeat. ie., s?
s can exist 1 time or no need to exist at all.
/
is a special character in regex so it needs to be escaped by a backslash \/
/^https?:\/\//.test('https://www.bbc.co.uk/sport/cricket'); // true
/^https?:\/\//.test('http://www.bbc.co.uk/sport/cricket'); // true
/^https?:\/\//.test('ftp://www.bbc.co.uk/sport/cricket'); // false
In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:
def max(*values)
values.max
end
Output:
max(7, 1234, 9, -78, 156)
=> 1234
This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil
, since calling Enumerable#max on an empty array object returns nil
.
If you want to define this method on the Math module, this should do the trick:
module Math
def self.max(*values)
values.max
end
end
Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:
). See Dave Morse's answer for a simpler and faster method.
Using DevTools in the latest Chrome (v29) I find these two tips very helpful for debugging events:
Listing jQuery events of the last selected DOM element
$._data($0, "events") //assuming jQuery 1.7+
Utilizing the monitorEvents() command
Please don't use printf("%s", your_string.c_str());
Use cout << your_string;
instead. Short, simple and typesafe. In fact, when you're writing C++, you generally want to avoid printf
entirely -- it's a leftover from C that's rarely needed or useful in C++.
As to why you should use cout
instead of printf
, the reasons are numerous. Here's a sampling of a few of the most obvious:
printf
isn't type-safe. If the type you pass differs from that given in the conversion specifier, printf
will try to use whatever it finds on the stack as if it were the specified type, giving undefined behavior. Some compilers can warn about this under some circumstances, but some compilers can't/won't at all, and none can under all circumstances.printf
isn't extensible. You can only pass primitive types to it. The set of conversion specifiers it understands is hard-coded in its implementation, and there's no way for you to add more/others. Most well-written C++ should use these types primarily to implement types oriented toward the problem being solved.It makes decent formatting much more difficult. For an obvious example, when you're printing numbers for people to read, you typically want to insert thousands separators every few digits. The exact number of digits and the characters used as separators varies, but cout
has that covered as well. For example:
std::locale loc("");
std::cout.imbue(loc);
std::cout << 123456.78;
The nameless locale (the "") picks a locale based on the user's configuration. Therefore, on my machine (configured for US English) this prints out as 123,456.78
. For somebody who has their computer configured for (say) Germany, it would print out something like 123.456,78
. For somebody with it configured for India, it would print out as 1,23,456.78
(and of course there are many others). With printf
I get exactly one result: 123456.78
. It is consistent, but it's consistently wrong for everybody everywhere. Essentially the only way to work around it is to do the formatting separately, then pass the result as a string to printf
, because printf
itself simply will not do the job correctly.
printf
format strings can be quite unreadable. Even among C programmers who use printf
virtually every day, I'd guess at least 99% would need to look things up to be sure what the #
in %#x
means, and how that differs from what the #
in %#f
means (and yes, they mean entirely different things).This code will work for all cases:
int[] a1 ={3,4,5,6};
int[] a2 = {4,7,9};
int i = a1.Length-1;
int j = a2.Length-1;
int resultIndex= i+j+1;
Array.Resize(ref a2, a1.Length +a2.Length);
while(resultIndex >=0)
{
if(i != 0 && j !=0)
{
if(a1[i] > a2[j])
{
a2[resultIndex--] = a[i--];
}
else
{
a2[resultIndex--] = a[j--];
}
}
else if(i>=0 && j<=0)
{
a2[resultIndex--] = a[i--];
}
else if(j>=0 && i <=0)
{
a2[resultIndex--] = a[j--];
}
}
Change table's default charset:
ALTER TABLE etape_prospection
CHARACTER SET utf8,
COLLATE utf8_general_ci;
To change string column charset exceute this query:
ALTER TABLE etape_prospection
CHANGE COLUMN etape_prosp_comment etape_prosp_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;
Here is an example of using Reflections library to recursively scan classpath by regex name pattern augmented with a couple of Guava perks to to fetch resources contents:
Reflections reflections = new Reflections("com.example.package", new ResourcesScanner());
Set<String> paths = reflections.getResources(Pattern.compile(".*\\.template$"));
Map<String, String> templates = new LinkedHashMap<>();
for (String path : paths) {
log.info("Found " + path);
String templateName = Files.getNameWithoutExtension(path);
URL resource = getClass().getClassLoader().getResource(path);
String text = Resources.toString(resource, StandardCharsets.UTF_8);
templates.put(templateName, text);
}
This works with both jars and exploded classes.
I found the mouseleave
will not fire when weird things happen, like the window focus changes suddenly, then the user comes back to the browser. In cases like that, mouseleave
will never fire until the cursor goes over and leaves the element again.
This solution I came up with relies on mouseenter
on the window
object, so it disappears when the mouse is moved anywhere else on the page.
This was designed to work with having multiple elements on the page that will trigger it (like in a table).
var allMenus = $(".menus");
allMenus.popover({
html: true,
trigger: "manual",
placement: "bottom",
content: $("#menuContent")[0].outerHTML
}).on("mouseenter", (e) => {
allMenus.not(e.target).popover("hide");
$(e.target).popover("show");
e.stopPropagation();
}).on("shown.bs.popover", () => {
$(window).on("mouseenter.hidepopover", (e) => {
if ($(e.target).parents(".popover").length === 0) {
allMenus.popover("hide");
$(window).off("mouseenter.hidepopover");
}
});
});
This is basic code to find and play an audio file in Swift.
Add your audio file to your Xcode and add the code below.
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer() // declare globally
override func viewDidLoad() {
super.viewDidLoad()
guard let sound = Bundle.main.path(forResource: "audiofilename", ofType: "mp3") else {
print("Error getting the mp3 file from the main bundle.")
return
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
} catch {
print("Audio file error.")
}
audioPlayer.play()
}
@IBAction func notePressed(_ sender: UIButton) { // Button action
audioPlayer.stop()
}
}
This solution is from command line mysql
mysql>USE information_schema;
In below query just change <--DATABASE_NAME--> to your database and <--TABLENAME--> to your table name where you just want Field values of DESCRIBE statement
mysql> SELECT COLUMN_NAME FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND TABLE_NAME='<--TABLENAME-->';
This what helped me:
List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);
Taken from Java 8 Finding Specific Element in List with Lambda
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>
In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.
// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];
for (i=0; i < cacheBust.length; i++){
var el = document.createElement('script');
el.src = cacheBust[i]+"?v=" + Math.random();
document.getElementsByTagName('head')[0].appendChild(el);
}
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
You may want to remove the space to the second String:
separated[1] = separated[1].trim();
If you want to split the string with a special character like dot(.) you should use escape character \ before the dot
Example:
String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"
There are other ways to do it. For instance, you can use the StringTokenizer
class (from java.util
):
StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
You'll want to add a Symbolic Breakpoint
. Apple provides an excellent guide on how to do this.
cmd+7
(cmd+8
in Xcode 9)Add
button in the lower leftAdd Symbolic Breakpoint...
Symbol
just type in UIViewAlertForUnsatisfiableConstraints
You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.
Some interesting excerpts from the bash manpage:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the
--login
option, it first reads and executes commands from the file/etc/profile
, if that file exists. After reading that file, it looks for~/.bash_profile
,~/.bash_login
, and~/.profile
, in that order, and reads and executes commands from the first one that exists and is readable. The--noprofile
option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from/etc/bash.bashrc
and~/.bashrc
, if these files exist. This may be inhibited by using the--norc
option. The--rcfile
file option will force bash to read and execute commands from file instead of/etc/bash.bashrc
and~/.bashrc
.
So have a look at /etc/profile
or /etc/bash.bashrc
, these files are the right places for global settings. Put something like this in them to set up an environement variable:
export MY_VAR=xxx
Got it to work go to the local.properties file under your build.gradle files to find out the PATH to your SDK, from the SDK location go into the platform-tools folder and look and see if you have adb.exe.
If not go to http://adbshell.com/downloads and download ADB KITS. Copy the zip folder's contents into the platform-tools folder and re-make your project.
I didn't need to update the PATH in the Extended Controls Settings section on the emulator, I left Use detected ADB location settings on. Hope this makes this faster for you !
Didn't find a complete code snippet of how to use $http.post method to send data to the server and why it was not working in this case.
Explanations of below code snippet...
Setting the Content-Type in the config variable that will be passed along with the request of angularJS $http.post that instruct the server that we are sending data in www post format.
Notice the $htttp.post method, where I am sending 1st parameter as url, 2nd parameter as data (serialized) and 3rd parameter as config.
Remaining code is self understood.
$scope.SendData = function () {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
fName: $scope.firstName,
lName: $scope.lastName
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('/ServerRequest/PostDataResponse', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
Look at the code example of $http.post method here.
Interesting to note, all sources emphasize that @Column(nullable=false) is used only for DDL generation.
However, even if there is no @NotNull annotation, and hibernate.check_nullability option is set to true, Hibernate will perform validation of entities to be persisted.
It will throw PropertyValueException saying that "not-null property references a null or transient value", if nullable=false attributes do not have values, even if such restrictions are not implemented in the database layer.
More information about hibernate.check_nullability option is available here: http://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/Hibernate_User_Guide.html#configurations-mapping.
On the Developers bugs Facebook site, the last answer about that (parameters with sharer.php
), makes me believe it was a bug that was going to be resolved. Am I right?
https://developers.facebook.com/x/bugs/357750474364812/
Ibrahim Faour · · Facebook Platform Team
Apologies for the inconvenience. We aim to update our external reports as soon as we get a resolution on issues. I do understand that sometimes the answer provided may not be satisfying, but we are eager to keep our platform as stable and efficient as possible. Thanks!
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:
>>> print "%.16f" % 2.51
2.5099999999999998
>>> 2.51*100
250.99999999999997
>>> 4.02*100
401.99999999999994
If you use int, which truncates the numbers, you get:
250
401
Have a look at the Decimal type.
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
Open phpmyadmin, go to database and corresponding table to find it out.
In regards to deleting the symbolic links, I found this to be useful.
find /usr/local/bin -lname '../../../Library/Frameworks/Python.framework/Versions/2.7/*' -delete
app[func].apply(this, args);
Most of the answers are from the Xcode 4-5 era. I recommend an ignore file in a modern style.
# Xcode Project
**/*.xcodeproj/xcuserdata/
**/*.xcworkspace/xcuserdata/
**/*.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
**/*.xcworkspace/xcshareddata/*.xccheckout
**/*.xcworkspace/xcshareddata/*.xcscmblueprint
**/*.playground/**/timeline.xctimeline
.idea/
# Build
build/
DerivedData/
*.ipa
# CocoaPods
Pods/
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/sign&cert
# CSV
*.orig
.svn
# Other
*~
.DS_Store
*.swp
*.save
._*
*.bak
Keep it updated from: https://github.com/BB9z/iOS-Project-Template/blob/master/.gitignore