Only MyISAM allows for FULLTEXT, as seen here.
Try this:
CREATE TABLE gamemech_chat (
id bigint(20) unsigned NOT NULL auto_increment,
from_userid varchar(50) NOT NULL default '0',
to_userid varchar(50) NOT NULL default '0',
text text NOT NULL,
systemtext text NOT NULL,
timestamp datetime NOT NULL default '0000-00-00 00:00:00',
chatroom bigint(20) NOT NULL default '0',
PRIMARY KEY (id),
KEY from_userid (from_userid),
FULLTEXT KEY from_userid_2 (from_userid),
KEY chatroom (chatroom),
KEY timestamp (timestamp)
) ENGINE=MyISAM;
WebSockets:
Ratified IETF standard (6455) with support across all modern browsers and even legacy browsers using web-socket-js polyfill.
Uses HTTP compatible handshake and default ports making it much easier to use with existing firewall, proxy and web server infrastructure.
Much simpler browser API. Basically one constructor with a couple of callbacks.
Client/browser to server only.
Only supports reliable, in-order transport because it is built On TCP. This means packet drops can delay all subsequent packets.
WebRTC:
Just beginning to be supported by Chrome and Firefox. MS has proposed an incompatible variant. The DataChannel component is not yet compatible between Firefox and Chrome.
WebRTC is browser to browser in ideal circumstances but even then almost always requires a signaling server to setup the connections. The most common signaling server solutions right now use WebSockets.
Transport layer is configurable with application able to choose if connection is in-order and/or reliable.
Complex and multilayered browser API. There are JS libs to provide a simpler API but these are young and rapidly changing (just like WebRTC itself).
It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator
, std::front_insert_iterator
, std::insert_iterator
) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.
For example, when you are performing a series of insertion operations into a std::vector
by using std::insert_iterator
it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.
This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.
For example, this code
std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);
for (unsigned n = 20; n > 0; --n)
*it_ins++ = rand();
is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it
will obviously become invalid, but it_ins
will continue to remain valid.
On the standard front:
a translation unit is the combination of a source files, included headers and source files less any source lines skipped by conditional inclusion preprocessor directive.
the standard defines 9 phases in the translation. The first four correspond to preprocessing, the next three are the compilation, the next one is the instantiation of templates (producing instantiation units) and the last one is the linking.
In practice the eighth phase (the instantiation of templates) is often done during the compilation process but some compilers delay it to the linking phase and some spread it in the two.
Programmers often confuse multidimensional arrays with arrays of pointers.
Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".
When using named multidimensional arrays, all dimensions must be known at compile time:
int H = read_int();
int W = read_int();
int connect_four[6][7]; // okay
int connect_four[H][7]; // ISO C++ forbids variable length array
int connect_four[6][W]; // ISO C++ forbids variable length array
int connect_four[H][W]; // ISO C++ forbids variable length array
This is how a named multidimensional array looks like in memory:
+---+---+---+---+---+---+---+
connect_four: | | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6]
and connect_four[1][0]
are neighbors in memory. In fact, connect_four[0][7]
and connect_four[1][0]
denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:
int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);
With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:
int (*p)[7] = new int[6][7]; // okay
int (*p)[7] = new int[H][7]; // okay
int (*p)[W] = new int[6][W]; // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W]; // ISO C++ forbids variable length array
This is how an anonymous multidimensional array looks like in memory:
+---+---+---+---+---+---+---+
+---> | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
|
+-|-+
p: | | |
+---+
Note that the array itself is still allocated as a single block in memory.
You can overcome the restriction of fixed width by introducing another level of indirection.
Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:
int* triangle[5];
for (int i = 0; i < 5; ++i)
{
triangle[i] = new int[5 - i];
}
// ...
for (int i = 0; i < 5; ++i)
{
delete[] triangle[i];
}
And here is how it looks like in memory:
+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+
^
| +---+---+---+---+
| | | | | |
| +---+---+---+---+
| ^
| | +---+---+---+
| | | | | |
| | +---+---+---+
| | ^
| | | +---+---+
| | | | | |
| | | +---+---+
| | | ^
| | | | +---+
| | | | | |
| | | | +---+
| | | | ^
| | | | |
| | | | |
+-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
+---+---+---+---+---+
Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.
Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:
int n = calculate_five(); // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
p[i] = new int[n - i];
}
// ...
for (int i = 0; i < n; ++i)
{
delete[] p[i];
}
delete[] p; // note the extra delete[] !
And here is how it looks like in memory:
+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+
^
| +---+---+---+---+
| | | | | |
| +---+---+---+---+
| ^
| | +---+---+---+
| | | | | |
| | +---+---+---+
| | ^
| | | +---+---+
| | | | | |
| | | +---+---+
| | | ^
| | | | +---+
| | | | | |
| | | | +---+
| | | | ^
| | | | |
| | | | |
+-|-+-|-+-|-+-|-+-|-+
| | | | | | | | | | |
+---+---+---+---+---+
^
|
|
+-|-+
p: | | |
+---+
Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:
int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;
int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;
However, there is no implicit conversion from T[h][w]
to T**
. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h
pointers to T
(each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:
int connect_four[6][7];
int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
p[i] = connect_four[i];
}
// ...
delete[] p;
Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:
int connect_four[6][7];
int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
p[i] = new int[7];
std::copy(connect_four[i], connect_four[i + 1], p[i]);
}
// ...
for (int i = 0; i < 6; ++i)
{
delete[] p[i];
}
delete[] p;
The binary operators =
(assignment), []
(array subscription), ->
(member access), as well as the n-ary ()
(function call) operator, must always be implemented as member functions, because the syntax of the language requires them to.
Other operators can be implemented either as members or as non-members. Some of them, however, usually have to be implemented as non-member functions, because their left operand cannot be modified by you. The most prominent of these are the input and output operators <<
and >>
, whose left operands are stream classes from the standard library which you cannot change.
For all operators where you have to choose to either implement them as a member function or a non-member function, use the following rules of thumb to decide:
Of course, as with all rules of thumb, there are exceptions. If you have a type
enum Month {Jan, Feb, ..., Nov, Dec}
and you want to overload the increment and decrement operators for it, you cannot do this as a member functions, since in C++, enum types cannot have member functions. So you have to overload it as a free function. And operator<()
for a class template nested within a class template is much easier to write and read when done as a member function inline in the class definition. But these are indeed rare exceptions.
(However, if you make an exception, do not forget the issue of const
-ness for the operand that, for member functions, becomes the implicit this
argument. If the operator as a non-member function would take its left-most argument as a const
reference, the same operator as a member function needs to have a const
at the end to make *this
a const
reference.)
Continue to Common operators to overload.
C++17 (N4659
) includes a proposal Refining Expression Evaluation Order for Idiomatic C++
which defines a stricter order of expression evaluation.
In particular, the following sentence
8.18 Assignment and compound assignment operators:
....In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.
together with the following clarification
An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
make several cases of previously undefined behavior valid, including the one in question:
a[++i] = i;
However several other similar cases still lead to undefined behavior.
In N4140
:
i = i++ + 1; // the behavior is undefined
But in N4659
i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined
Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.
Wouldn't this work:
SELECT email FROM table1 t1
where UNIQUE(SELECT * FROM table1 t2);
With C#, Microsoft Framework Design Guidelines suggest not using the underscore character for public members. For private members, underscores are OK to use. In fact, Jeffrey Richter (often cited in the guidelines) uses an m_ for instance and a "s_" for private static memberss.
Personally, I use just _ to mark my private members. "m_" and "s_" verge on Hungarian notation which is not only frowned upon in .NET, but can be quite verbose and I find classes with many members difficult to do a quick eye scan alphabetically (imagine 10 variables all starting with m_).
In my case, I got this when trying to run Django tests through PyCharm. I think it is because PyCharm does not load the initial Django project settings, i.e. those that manage.py shell
runs initially. One can add them to the start of the testing script or just run the tests using manage.py test
.
Versions:
If you want to allow the user to browse for a file, you need to have an input type="file"
The closest you could get to your requirement would be to place the input type="file"
on the page and hide it. Then, trigger the click event of the input when the button is clicked:
#myFileInput {
display:none;
}
<input type="file" id="myFileInput" />
<input type="button"
onclick="document.getElementById('myFileInput').click()"
value="Select a File" />
Here's a working fiddle.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
I just ran out of stack at work, it was a database and it was running some threads, basically the previous developer had thrown a big array on the stack, and the stack was low anyway. The software was compiled using Microsoft Visual Studio 2015.
Even though the thread had run out of stack, it silently failed and continued on, it only stack overflowed when it came to access the contents of the data on the stack.
The best advice i can give is to not declare arrays on the stack - especially in complex applications and particularly in threads, instead use heap. That's what it's there for ;)
Also just keep in mind it may not fail immediately when declaring the stack, but only on access. My guess is that the compiler declares stack under windows "optimistically", i.e. it will assume that the stack has been declared and is sufficiently sized until it comes to use it and then finds out that the stack isn't there.
Different operating systems may have different stack declaration policies. Please leave a comment if you know what these policies are.
Use the Date get methods.
http://www.tizag.com/javascriptT/javascriptdate.php
http://www.htmlgoodies.com/beyond/javascript/article.php/3470841
var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();
You are overwriting your object file runexp.o
by running this command :
gcc -o runexp.o scd.o data_proc.o -lm -fopenmp
In fact, the -o
is for the output file.
You need to run :
gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp
runexp.out will be you binary file.
Why do you pass -c
? That will just show the number of matches. Similarly, there is no reason to use -r
. I suggest you read man grep
.
To grep for 2 words existing on the same line, simply do:
grep "word1" FILE | grep "word2"
grep "word1" FILE
will print all lines that have word1 in them from FILE, and then grep "word2"
will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2.
If you just want a count of how many lines had the 2 words on the same line, do:
grep "word1" FILE | grep -c "word2"
Also, to address your question why does it get stuck : in grep -c "word1"
, you did not specify a file. Therefore, grep
expects input from stdin
, which is why it seems to hang. You can press Ctrl+D to send an EOF (end-of-file) so that it quits.
For now, this is the best way.
this.setState(previousState => ({
myArray: [...previousState.myArray, 'new value']
}));
This is a hack for program using Spring Data JPA before Version 2.0.4.
Code has worked with PostgreSQL and MySQL :
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1 ORDER BY ?#{#pageable}",
countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
nativeQuery = true)
Page<User> findByLastname(String lastname, Pageable pageable);
}
ORDER BY ?#{#pageable}
is for Pageable
.
countQuery
is for Page<User>
.
Below error seems like Gits didn't find .git file in current directory so throwing error message.
Therefore change to directory to repository directory where you have checkout the code from git and then run this command.
Just as a small addition, you can also do an apply if you have a complex function that you apply to a single column:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html
df[b] = df[a].apply(lambda col: do stuff with col here)
System.Convert.ChangeType(jtoken.ToString(), targetType);
or
JsonConvert.DeserializeObject(jtoken.ToString(), targetType);
--EDIT--
Uzair, Here is a complete example just to show you they work
string json = @"{
""id"" : 77239923,
""username"" : ""UzEE"",
""email"" : ""[email protected]"",
""name"" : ""Uzair Sajid"",
""twitter_screen_name"" : ""UzEE"",
""join_date"" : ""2012-08-13T05:30:23Z05+00"",
""timezone"" : 5.5,
""access_token"" : {
""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
""scope"" : [ ""read"", ""write"", ""bake pies"" ],
""expires"" : 57723
},
""friends"" : [{
""id"" : 2347484,
""name"" : ""Bruce Wayne""
},
{
""id"" : 996236,
""name"" : ""Clark Kent""
}]
}";
var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(int);
var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
I just want to fill only 80% of the screen for that I did like this below
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.80);
setContentView(R.layout.mylayout);
getWindow().setLayout(screenWidth, LayoutParams.WRAP_CONTENT); //set below the setContentview
it works only when I put the getwindow().setLayout... line below the setContentView(..)
thanks @Matthias
var attr = $(this).attr('name');
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
// ...
}
when you decompile and change the code you have to go on the root folder of your eclipse project and check your class in bin folder wich is on the same level as src. then open you original jar with zip tool ( 7zip is good for that ) and put the modified class in tha same package inside the jar.
The other answer describing arrays of arrays are correct.
BUT if you are planning of doing a anything mathematical with the arrays - or need something special like sparse matrices you should look at one of the many maths libs like TNT before re-inventing too many wheels
For boot2docker, we can set it on /var/lib/boot2docker/profile
, for instance:
ulimit -n 2018
Be warned not to set this limit too high as it will slow down apt-get! See bug #1332440. I had it with debian jessie.
In Bootstrap 4:
to center the child horizontally, use bootstrap-4 class:
justify-content-center
to center the child vertically, use bootstrap-4 class:
align-items-center
but remember don't forget to use d-flex class with these it's a bootstrap-4 utility class, like so
<div class="d-flex justify-content-center align-items-center" style="height:100px;">
<span class="bg-primary">MIDDLE</span>
</div>
Note: make sure to add bootstrap-4 utilities if this code does not work
I know it's not the direct answer to this question but it may help someone
If the values are integer then you can use [2-3]
or you can use [5,7,8]
for non continuous values.
#!/bin/bash
while [ $# -gt 0 ];
do
case $1 in
1)
echo "one"
;;
[2-3])
echo "two or three"
;;
[4-6])
echo "four to six"
;;
[7,9])
echo "seven or nine"
;;
*)
echo "others"
;;
esac
shift
done
If the values are string then you can use |
.
#!/bin/bash
while [ $# -gt 0 ];
do
case $1 in
"one")
echo "one"
;;
"two" | "three")
echo "two or three"
;;
*)
echo "others"
;;
esac
shift
done
The accepted answer is correct, but not complete.
In order for Select All
to be the default option, the Available Values dataset must contain at least 2 columns: value and label. They can return the same data, but their names have to be different. The Default Values dataset will then use value column and then Select All
will be the default value. If the dataset returns only 1 column, only the last record's value will be selected in the drop down of the parameter.
git reset --hard
This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.
If you want to pull the new changes from remote and want to ignore the local changes during this pull then,
git stash
It will stash all the local changes, now you can pull the remote changes,
git pull
Now, you can bring back your local changes by,
git stash pop
This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct
)
drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]
Where x
is a dataframe and pct
is the threshold of NA
-filled data you want to get rid of.
pct = 1
means remove rows that have 100% of its values NA
.
pct = .5
means remome rows that have at least half its values NA
I prefer this (below):
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
}
Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.
You seem to be using grep()
like the Unix grep
utility, which is wrong.
Perl's grep()
in scalar context evaluates the expression for each element of a list and returns the number of times the expression was true.
So when $match
contains any "true" value, grep($match, @array)
in scalar context will always return the number of elements in @array
.
Instead, try using the pattern matching operator:
if (grep /$match/, @array) {
print "found it\n";
}
Well, timing to the rescue again. It seems switch
is generally faster than if
statements.
So that, and the fact that the code is shorter/neater with a switch
statement leans in favor of switch
:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
You're probably returning an object that's on the stack. That is, return_Object()
probably looks like this:
Object& return_Object()
{
Object object_to_return;
// ... do stuff ...
return object_to_return;
}
If this is what you're doing, you're out of luck - object_to_return
has gone out of scope and been destructed at the end of return_Object
, so myObject
refers to a non-existent object. You either need to return by value, or return an Object
declared in a wider scope or new
ed onto the heap.
I've created an example to show how to. Updated state
definition would be:
$stateProvider
.state('home', {
url: '/:foo?bar',
views: {
'': {
templateUrl: 'tpl.home.html',
controller: 'MainRootCtrl'
},
...
}
And this would be the controller:
.controller('MainRootCtrl', function($scope, $state, $stateParams) {
//..
var foo = $stateParams.foo; //getting fooVal
var bar = $stateParams.bar; //getting barVal
//..
$scope.state = $state.current
$scope.params = $stateParams;
})
What we can see is that the state home now has url defined as:
url: '/:foo?bar',
which means, that the params in url are expected as
/fooVal?bar=barValue
These two links will correctly pass arguments into the controller:
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">
Also, the controller does consume $stateParams
instead of $stateParam
.
Link to doc:
You can check it here
params : {}
There is also new, more granular setting params : {}
. As we've already seen, we can declare parameters as part of url
. But with params : {}
configuration - we can extend this definition or even introduce paramters which are not part of the url:
.state('other', {
url: '/other/:foo?bar',
params: {
// here we define default value for foo
// we also set squash to false, to force injecting
// even the default value into url
foo: {
value: 'defaultValue',
squash: false,
},
// this parameter is now array
// we can pass more items, and expect them as []
bar : {
array : true,
},
// this param is not part of url
// it could be passed with $state.go or ui-sref
hiddenParam: 'YES',
},
...
Settings available for params are described in the documentation of the $stateProvider
Below is just an extract
We can call these params this way:
// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">
Check it in action here
The python 2.X paths can be set from few of the above instructions. Python 3 by default will be installed in C:\Users\\AppData\Local\Programs\Python\Python35-32\ So this path has to be added to Path variable in windows environment.
Use String.replace()
, e.g.
var str = "a,d,k";
str = str.replace( /,/g, "" );
Note the g
(global) flag on the regular expression, which matches all instances of ",".
This feature already exists in Ubuntu and Debian, in the command-not-found
package.
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer.
Example: applicationContext.xml
<context:property-placeholder location="classpath:test.properties"/>
Component class
private @Value("${propertyName}") String propertyField;
Use round
, floor
or ceil
methods to round it to the closest integer, along with intval()
which is limited.
http://php.net/manual/en/function.round.php
if you just want any letters:
'a'*10 # gives 'aaaaaaaaaa'
if you want consecutive letters (up to 26):
''.join(['%c' % x for x in range(97, 97+10)]) # gives 'abcdefghij'
It works fine for me, but it's a little tricky :)
Now you have settings for this session set (every time you load session it will be logged).
Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel
And for PDF
generation use http://princexml.com/
I'm going out on a limb here , since your question was not very detailed, that a) your receipt printer is a thermal printer that needs raw data, b) that "from javascript" you are talking about printing from the web browser and c) that you do not have access to send raw data from browser
Here is a Java Applet that solves all that for you , if I'm correct about those assumptions then you need either Java, Flash, or Silverlight http://code.google.com/p/jzebra/
To get employee names starting with A or B listed in order...
select employee_name
from employees
where employee_name LIKE 'A%' OR employee_name LIKE 'B%'
order by employee_name
If you are using Microsoft SQL Server you could use
....
where employee_name LIKE '[A-B]%'
order by employee_name
This is not standard SQL though it just gets translated to the following which is.
WHERE employee_name >= 'A'
AND employee_name < 'C'
For all variants you would need to consider whether you want to include accented variants such as Á
and test whether the queries above do what you want with these on your RDBMS and collation options.
You only use the M
for a numeric literal, when you cast it's just:
decimal dtot = (decimal)doubleTotal;
Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal
you may get rounding errors. You may want to convert the numbers to Decimal
before adding them together, or make sure that the numbers aren't floating point numbers in the first place.
In Pass By Reference You only add "ref" in the function parameters and one
more thing you should be declaring function "static" because of main is static(#public void main(String[] args)
)!
namespace preparation
{
public class Program
{
public static void swap(ref int lhs,ref int rhs)
{
int temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a = 10;
int b = 80;
Console.WriteLine("a is before sort " + a);
Console.WriteLine("b is before sort " + b);
swap(ref a, ref b);
Console.WriteLine("");
Console.WriteLine("a is after sort " + a);
Console.WriteLine("b is after sort " + b);
}
}
}
Of course slideDown
and slideUp
don't do what you want, you said you want it to be left/right, not top/down.
If your edit to your question adding the jquery-ui
tag means you're using jQuery UI, I'd go with nnnnnn's solution, using jQuery UI's slide
effect.
If not:
Assuming the menu starts out visible (edit: oops, I see that isn't a valid assumption; see note below), if you want it to slide out to the left and then later slide back in from the left, you could do this: Live Example | Live Source
$(document).ready(function() {
// Hide menu once we know its width
$('#showmenu').click(function() {
var $menu = $('.menu');
if ($menu.is(':visible')) {
// Slide away
$menu.animate({left: -($menu.outerWidth() + 10)}, function() {
$menu.hide();
});
}
else {
// Slide in
$menu.show().animate({left: 0});
}
});
});
You'll need to put position: relative
on the menu element.
Note that I replaced your toggle
with click
, because that form of toggle
was removed from jQuery.
If you want the menu to start out hidden, you can adjust the above. You want to know the element's width, basically, when putting it off-page.
This version doesn't care whether the menu is initially-visible or not: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none; position: relative;"><ul><li>Button1</li><li>Button2</li><li>Button3</li></ul></div>
<script>
$(document).ready(function() {
var first = true;
// Hide menu once we know its width
$('#showmenu').click(function() {
var $menu = $('.menu');
if ($menu.is(':visible')) {
// Slide away
$menu.animate({left: -($menu.outerWidth() + 10)}, function() {
$menu.hide();
});
}
else {
// Slide in
$menu.show().css("left", -($menu.outerWidth() + 10)).animate({left: 0});
}
});
});
</script>
</body>
</html>
Answer is very simple use the .NET Framework tools sn.exe
. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,
Use the following command,
sn –T myDLL.dll
This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.
Example
C:\WINNT\Microsoft.NET\Framework\v3.5>sn -T EdmGen.exe Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Public key token is b77a5c561934e089
No, the String.isEmpty()
method looks as following:
public boolean isEmpty() {
return this.value.length == 0;
}
as you can see it checks the length of the string so you definitely have to check if the string is null before.
The cleanest way you can find is with Lodash#pick
const _ = require('lodash');
const allowed = ['item1', 'item3'];
const obj = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
}
const filteredObj = _.pick(obj, allowed)
After insertion code,
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
For understanding innerHTML property you first need to go through the basics of the javascript object and HTML DOM(Document object model). I will try to explain:
Now coming to your Question:
HTML code:
<p id= "myPara"> We love to Code.</p>
JavaScript code:
alert(document.getElementById("myPara").innerHTML);
here, document.getElementById("myPara") will return our html element as a javascript object which has pre-defined property innerHTML. innerHTML property contains the content of HTML tag.
Hope this will help.
You can run following HTML code in your browser to understand it:
<html>
<body>
<p id= "myPara"> We love to Code.</p>
<script>
alert(document.getElementById("myPara").innerHTML);
</script>
</body>
</html>
So none of the other answers seems to get it right.
The Good Behaviored Keyboard on iOS should:
My code use a NSLayoutConstraint
declared as an @IBOutlet
@IBOutlet private var bottomLayoutConstraint: NSLayoutConstraint!
You could also use transforms, view offsets, .... I think it's easier with the constraint tho. It works by setting a constraint to the bottom, you might need to alter the code if your constant is not 0/Not to the bottom.
Here is the code:
// In ViewDidLoad
NotificationCenter.default.addObserver(self, selector: #selector(?MyViewController.keyboardDidChange), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
@objc func keyboardDidChange(notification: Notification) {
let userInfo = notification.userInfo! as [AnyHashable: Any]
let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber
let animationCurve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber
bottomLayoutConstraint.constant = view.frame.height - endFrame.origin.y - view.safeAreaInsets.bottom // If your constraint is not defined as a safeArea constraint you might want to skip the last part.
// Prevents iPad undocked keyboard.
guard endFrame.height != 0, view.frame.height == endFrame.height + endFrame.origin.y else {
bottomLayoutConstraint.constant = 0
return
}
UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: animationCurve.intValue)!)
UIView.animate(withDuration: animationDuration.doubleValue) {
self.view.layoutIfNeeded()
// Do additional tasks such as scrolling in a UICollectionView
}
}
Copy the files to the default directory for your other database files. To find out what that is, you can use the sp_helpfile procedure in SSMS. On my machine it is: C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA
. By copying the files to this directory, they automatically get permissions applied that will allow the attach to succeed.
Here is a very good explanation :
You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="@+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Add" />
</RelativeLayout>
Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int pos) {
return list.get(pos);
}
@Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_custom_list_layout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
Hope this helps!
There is no default method within HTML itself to insert todays date into the input field. However, like any other input field it will accept a value.
You can use PHP to fetch todays date and input it into the value field of the form element.
<?php
// Fetch the year, month and day
$year = date(Y);
$month = date(m);
$day = date(d);
// Merge them into a string accepted by the input field
$date_string = "$year-$month-$day";
// Send to the browser the input field with the value set with the date string
echo "<input type='date' value='$date_string' />";
?>
The value field accepts the format YYYY-MM-DD as an input so simply by creating a variable $date_string
in the same format that the input value accepts and fill it with the year, month and day fetched from todays date and voilá! You have yourself a preselected date!
Hope this helps :)
Edit:
If you would like to have the input field nested within HTML rather than PHP you could do the following.
<?php
// Fetch the year, month and day
$year = date(Y);
$month = date(m);
$day = date(d);
// Merge them into a string accepted by the input field
$date_string = "$year-$month-$day";
?>
<html>
<head>...</head>
<body>
<form>
<input type="date" value="<?php print($date_string); ?>" />
</form>
</body>
</html>
I realise this question was asked a while back (2 years ago) but it still took me a while to find a definite answer out on the internet, so this goes to serve anyone who is looking for the answer whenever it may be and hope it helps everyone greatly :)
Another Edit:
Almost forgot, something thats been a royal pain for me in the past is always forgetting to set the default timezone whenever making a script in PHP that makes use of the date() function.
The syntax is date_default_timezone_set(...);
. Documentation can be found here at PHP.net and the list of supported timezones to insert into the function can be found here. This was always annoying since I am in Australia, everything is always pushed back 10 hours if I didn't set this properly as it defaults to UTC+0000 where I need UTC+1000 so just be cautious :)
Since the assembly resides in a temporary cache, you should combine the path to get the dll's config:
var appConfig = ConfigurationManager.OpenExeConfiguration(
Path.Combine(Environment.CurrentDirectory, Assembly.GetExecutingAssembly().ManifestModule.Name));
About prototype bean(s) :
The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.
So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.
So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.
In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.
public interface IThingFactory
{
Thing GetThing(string theString);
}
public class ThingFactory : IThingFactory
{
public Thing GetThing(string theString)
{
return new Thing(theString, firstDependency, secondDependency);
}
}
So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.
Adding mode:'no-cors'
to the request header guarantees that no response will be available in the response
Adding a "non standard" header, line 'access-control-allow-origin'
will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent
You're also doing fetch
wrong ... fetch
returns a "promise" for a Response
object which has promise creators for json
, text
, etc. depending on the content type...
In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.json();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
});
}
however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.text();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = muutuja;
});
}
Help -> About Eclipse Platform
For Eclipse Mars - you can check Eclipse -> About Eclipse
or Help -> Installation Details
, then you should see the version:
The following will place the cursor back at beginning of the previous row. It's up to you to place it in the right horizontal position (using $pos.X to move it sideways):
$pos = $host.ui.RawUI.get_cursorPosition()
$pos.Y -= 1
$host.UI.RawUI.set_cursorPosition($Pos)
Your current output is 27 spaces over, so $pos.X = 27 might work.
None of the above answers worked "out of the box" for me, however, the following function, obtained by copying the ideas of the other answers works:
apply_func_2_cols = @(f,M) cell2mat(cellfun(f,num2cell(M,1), 'UniformOutput',0));
It takes a function f
and applies it to every column of the matrix M
.
So for example:
f = @(v) [0 1;1 0]*v + [0 0.1]';
apply_func_2_cols(f,[0 0 1 1;0 1 0 1])
ans =
0.00000 1.00000 0.00000 1.00000
0.10000 0.10000 1.10000 1.10000
Radio buttons are meant to be used in groups, as defined by their sharing the same name
attribute. Then clicking on one of them deselects the currently selected one. To allow the user to cancel a “real” selection he has made, you can include a radio button that corresponds to a null choice, like “Do not know” or “No answer”.
If you want a single button that can be checked or unchecked, use a checkbox.
It is possible (but normally not relevant) to uncheck a radio button in JavaScript, simply by setting its checked
property to false, e.g.
<input type=radio name=foo id=foo value=var>
<input type=button value="Uncheck" onclick=
"document.getElementById('foo').checked = false">
I ran into this same problem. I found my answer by downloading the source code for Collections.sort
in the java framework. The answer I used was to put the <T>
generic in the method, not in the class definition.
So this worked:
public class QuickSortArray {
public static <T extends Comparable> void quickSort(T[] array, int bottom, int top){
//do it
}
}
Of course, after reading the answers above I realized that this would be an acceptable alternative without using a generic class:
public static void quickSort(Comparable[] array, int bottom, int top){
//do it
}
Just wanted to add a little bit more on this.
With the new angular 2.0.0 final release (sept 14, 2016), if you use custom html tags then it will report that Template parse errors
. A custom tag is a tag you use in your HTML that's not one of these tags.
It looks like the line schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
need to be added to each component where you are using custom HTML tags.
EDIT: The schemas
declaration needs to be in a @NgModule
decorator. The example below shows a custom module with a custom component CustomComponent
which allows any html tag in the html template for that one component.
custom.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomComponent } from './custom.component';
@NgModule({
declarations: [ CustomComponent ],
exports: [ CustomComponent ],
imports: [ CommonModule ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class CustomModule {}
custom.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-custom-component',
templateUrl: 'custom.component.html'
})
export class CustomComponent implements OnInit {
constructor () {}
ngOnInit () {}
}
custom.component.html
In here you can use any HTML tag you want.
<div class="container">
<boogey-man></boogey-man>
<my-minion class="one-eyed">
<job class="plumber"></job>
</my-minion>
</div>
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").
From the command line, you can type
python setup.py --help
...to get a list of commands. What you are looking to do is...
python setup.py install
Update: Nowadays installing is done with pip, but libyaml is still required to build the C extension (on mac):
brew install libyaml
python -m pip install pyyaml
Outdated method:
For MacOSX (mavericks), the following seems to work:
brew install libyaml
sudo python -m easy_install pyyaml
<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>
css:
.smallDiv { height: 150px; width: 150px; }
Using only standard python libs:
from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()
Works on Windows (if you are on drive C), Mac or Linux
Alternatively, you could remove one line with an immediate invocation:
from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
Simplest way is to add a target tag.
<a href="http://www.starfall.com/" target="Starfall">Starfall</a>
Use a different value for the target attribute for each link if you want them to open in different tabs, the same value for the target attribute if you want them to replace the other ones.
With TypeScript, it is easy to find what you want with the right type.
import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.com')
.then(response: AxiosResponse => {
// Handle response
})
.catch((reason: AxiosError) => {
if (reason.response!.status === 400) {
// Handle 400
} else {
// Handle else
}
console.log(reason.message)
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Change Image on Hover in CSS</title>
<style type="text/css">
.card {
width: 130px;
height: 195px;
background: url("../images/pic.jpg") no-repeat;
margin: 50px;
}
.card:hover {
background: url("../images/anotherpic.jpg") no-repeat;
}
</style>
</head>
<body>
<div class="card"></div>
</body>
</html>
// change "name" and "value" according to your array data.
// Change "yourDataArrayName" name accroding to your array(NSArray).
let resultPredicate = NSPredicate(format: "SELF.name contains[c] %@", "value")
if let sortedDta = yourDataArrayName.filtered(using: resultPredicate) as? NSArray {
//enter code here.
print(sortedDta)
}
There is an easy way to sort a dictionary.
According to your question,
The solution is :
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
(Where c,is the name of your dictionary.)
This program gives the following output:
[(1, 89), (2, 3), (3, 0), (4, 5)]
like u wanted.
Another example is:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
Gives the output:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
Gives the output:[18, 24, 32, 36, 41]
z=sorted(d.items())
print z
Gives the output:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
Hence by changing it into keys, values and items , you can print like what u wanted.Hope this helps!
This is another solution with lambda:
#include <cmath>
#include <limits>
auto Compare = [](float a, float b, float epsilon = std::numeric_limits<float>::epsilon()){ return (std::fabs(a - b) <= epsilon); };
android:focusedByDefault="true"
If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.
Restrict specials characters on keypress. Here's a test page for key codes: http://www.asquare.net/javascript/tests/KeyCode.html
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
some_element.bind("keypress", function(event) {
// prevent if in array
if($.inArray(event.which,specialChars) != -1) {
event.preventDefault();
}
});
In Angular, I needed a proper currency format in my textfield. My solution:
var angularApp = angular.module('Application', []);
...
// new angular directive
angularApp.directive('onlyNum', function() {
return function( scope, element, attrs) {
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
// prevent these special characters
element.bind("keypress", function(event) {
if($.inArray(event.which,specialChars) != -1) {
prevent( scope, event, attrs)
}
});
var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
,57,96,97,98,99,100,101,102,103,104,105,110,190];
element.bind("keydown", function(event) {
if($.inArray(event.which,allowableKeys) == -1) {
prevent( scope, event, attrs)
}
});
};
})
// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
scope.$apply(function(){
scope.$eval(attrs.onlyNum);
event.preventDefault();
});
event.preventDefault();
}
In the html add the directive
<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">
and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'
...
this.updateRequest = function() {
amount = $scope.amount;
if (amount != undefined) {
document.getElementById('spcf').onkeypress = function (e) {
// only allow one period in currency
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
// Remove "." When Last Character and round the number on blur
$("#amount").on("blur", function() {
if (this.value.charAt(this.value.length-1) == ".") {
this.value.replace(".","");
$("#amount").val(this.value);
}
var num = parseFloat(this.value);
// check for 'NaN' if its safe continue
if (!isNaN(num)) {
var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
$("#amount").val(num);
}
});
this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}
...
Try to use it
$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});
str
is text representation in bytes, unicode
is text representation in characters.
You decode text from bytes to unicode and encode a unicode into bytes with some encoding.
That is:
>>> 'abc'.decode('utf-8') # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'
UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str
was renamed to bytes
, and unicode
was renamed to str
.
>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'
I just had this issue today and I found that I didn't open VS as 'Run as Administrator'. After doing this, I was able to publish the Service.
I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
/**
* Created by hu0983 on 2016.01.13..
*/
public class StringNotEmptyTesting {
public static void main(String[] args){
String a = " ";
String b = "";
String c=null;
System.out.println("Apache:");
if(!StringUtils.isNotBlank(a)){
System.out.println(" a is blank");
}
if(!StringUtils.isNotBlank(b)){
System.out.println(" b is blank");
}
if(!StringUtils.isNotBlank(c)){
System.out.println(" c is blank");
}
System.out.println("Google:");
if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
System.out.println(" a is NullOrEmpty");
}
if(Strings.isNullOrEmpty(b)){
System.out.println(" b is NullOrEmpty");
}
if(Strings.isNullOrEmpty(c)){
System.out.println(" c is NullOrEmpty");
}
}
}
Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty
On Debian/Ubuntu use:
sudo apt-get install g++-multilib libc6-dev-i386
innerText is the winner! http://jsperf.com/innerhtml-vs-removechild/133. At all previous tests inner dom of parent node were deleted at first iteration and then innerHTML or removeChild where applied to empty div.
As a more general answer http://sourceforge.net/p/predef/wiki/Home/ maintains a list of macros for detecting specicic compilers, operating systems, architectures, standards and more.
There's a client profile usable version, System.Net.WebUtility class, present in client profile System.dll. Here's the MSDN Link:
Why not try this
na.zero <- function (x) {
x[is.na(x)] <- 0
return(x)
}
na.zero(df)
I am posting a complete example which I finally got working. Here I am reading in a file rooms/rooms.txt
from a script rooms/rooms.js
var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
console.log(data);
});
Just incase you are working with a FirebaseRecyclerAdapter this post works as a charm https://stackoverflow.com/a/39058636/6507009
It removes whatever already-compiled files are in your project so that you can do a complete fresh rebuild.
i had this issue years back..but I got this. All you need to do is set the width and the height of the image to whatever you want..what i mean is your image in your carousel inner ...don't add the style attribut like "style:"(no not this) but something like this and make sure your codes ar correct its gonna work...Good luck
int array[ROW][COLUMN]={1};
This initialises only the first element to 1. Everything else gets a 0.
In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.
The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.
With a char
array you could use memset
to set every byte, but this will not generally work with an int
array (though it's fine for 0).
A general for
loop will do this quickly:
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COLUMN; j++)
array[i][j] = 1;
Or possibly quicker (depending on the compiler)
for (int i = 0; i < ROW*COLUMN; i++)
*((int*)a + i) = 1;
Replace following
curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');
With
curl_setopt ($ch, CURLOPT_SSLVERSION, 6);
Should work flawlessly.
You just need to access to Gemfile with root access. Before vi
:
command:
sudo su -
then:
vi ~/...
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.
Connect with SSH and follow these instructions to install Node on a shared hosting
In short you first install NVM, then you install the Node version of your choice with NVM.
wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash
Your restart your shell (close and reopen your sessions). Then you
nvm install stable
to install the latest stable version for example. You can install any version of your choice. Check node --version
for the node version you are currently using and nvm list
to see what you've installed.
In bonus you can switch version very easily (nvm use <version>
)
There's no need of PHP or whichever tricky workaround if you have SSH.
You could just make the join and after that select the wanted columns https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=dataframe%20join#pyspark.sql.DataFrame.join
I have tried to make note about these and have collected and written examples from a java perspective.
Putting it here for any java developer who is looking into the same subject.
Assuming you have a jre folder, which contains bin, lib, etc files copied from a Java Runtime distribution, in the same folder as eclipse.ini, you can set in your eclilpse.ini
-vm
jre\bin\javaw.exe
For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.
The extern
declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern
in a header file like:
extern struct a myAValue;
Then, in one source file, define the actual variable:
struct a myAValue;
If you forget to do this or accidentally define it in two source files, the linker will let you know about this.
I'm not exactly sure what's causing this. You can try looking in your socket.py (mine is a different version, so line numbers from the trace don't match, and I'm afraid some other details might not match as well).
Anyway, it seems like a good practice to put your url fetching code in a try: ... except: ...
block, and handle this with a short pause and a retry. The URL you're trying to fetch may be down, or too loaded, and that's stuff you'll only be able to handle in with a retry anyway.
Looks like divs will not go outside of their body's width. Even within another div.
I threw this up to test (without a doctype though) and it does not work as thought.
.slideContainer {_x000D_
overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
<div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
<div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
<div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.
Because the method erase in vector return the next iterator of the passed iterator.
I will give example of how to remove element in vector when iterating.
void test_del_vector(){
std::vector<int> vecInt{0, 1, 2, 3, 4, 5};
//method 1
for(auto it = vecInt.begin();it != vecInt.end();){
if(*it % 2){// remove all the odds
it = vecInt.erase(it); // note it will = next(it) after erase
} else{
++it;
}
}
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
// recreate vecInt, and use method 2
vecInt = {0, 1, 2, 3, 4, 5};
//method 2
for(auto it=std::begin(vecInt);it!=std::end(vecInt);){
if (*it % 2){
it = vecInt.erase(it);
}else{
++it;
}
}
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
// recreate vecInt, and use method 3
vecInt = {0, 1, 2, 3, 4, 5};
//method 3
vecInt.erase(std::remove_if(vecInt.begin(), vecInt.end(),
[](const int a){return a % 2;}),
vecInt.end());
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
}
output aw below:
024
024
024
A more generate method:
template<class Container, class F>
void erase_where(Container& c, F&& f)
{
c.erase(std::remove_if(c.begin(), c.end(),std::forward<F>(f)),
c.end());
}
void test_del_vector(){
std::vector<int> vecInt{0, 1, 2, 3, 4, 5};
//method 4
auto is_odd = [](int x){return x % 2;};
erase_where(vecInt, is_odd);
// output all the remaining elements
for(auto const& it:vecInt)std::cout<<it;
std::cout<<std::endl;
}
Your "application/xrds+xml"
was giving me issues, I was receiving a Content-Length of 0 (no response).
After removing that, you can access the response using response.GetResponseStream()
.
HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;
//request.Accept = "application/xrds+xml";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
select to_char(actual_start_date,'DD-MON-YYYY hh24:mi:ss') start_time,
to_char(actual_completion_date,'DD-MON-YYYY hh24:mi:ss') end_time,
floor((actual_completion_date-actual_start_date)*24*60)||'.'||round(mod((actual_completion_date-actual_start_date)*24*60*60,60)) diff_time
from fnd_concurrent_requests
order by request_id desc;
I would recommend the call_user_func()
or call_user_func_array
php methods.
You can check them out here (call_user_func_array , call_user_func).
example
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
//or
call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array
If you have arguments you are passing to the method , then use the call_user_func_array()
function.
example.
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}
// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));
If you really want to use linq, you can do something like this
li= (from tl in li
select new Myclass
{
name = tl.name,
age = (tl.name == "di" ? 10 : (tl.name == "marks" ? 20 : 30))
}).ToList();
or
li = li.Select(ex => new MyClass { name = ex.name, age = (ex.name == "di" ? 10 : (ex.name == "marks" ? 20 : 30)) }).ToList();
This assumes that there are only 3 types of name
. I would externalize that part into a function to make it more manageable.
Set the aaSorting
option to an empty array. It will disable initial sorting, whilst still allowing manual sorting when you click on a column.
"aaSorting": []
The aaSorting array should contain an array for each column to be sorted initially containing the column's index and a direction string ('asc' or 'desc').
This best for XML Deserialize
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
return xSerializer.Deserialize(str);
}
}
requests
supports so called event hooks (as of 2.23 there's actually only response
hook). The hook can be used on a request to print full request-response pair's data, including effective URL, headers and bodies, like:
import textwrap
import requests
def print_roundtrip(response, *args, **kwargs):
format_headers = lambda d: '\n'.join(f'{k}: {v}' for k, v in d.items())
print(textwrap.dedent('''
---------------- request ----------------
{req.method} {req.url}
{reqhdrs}
{req.body}
---------------- response ----------------
{res.status_code} {res.reason} {res.url}
{reshdrs}
{res.text}
''').format(
req=response.request,
res=response,
reqhdrs=format_headers(response.request.headers),
reshdrs=format_headers(response.headers),
))
requests.get('https://httpbin.org/', hooks={'response': print_roundtrip})
Running it prints:
---------------- request ----------------
GET https://httpbin.org/
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
None
---------------- response ----------------
200 OK https://httpbin.org/
Date: Thu, 14 May 2020 17:16:13 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 9593
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
<!DOCTYPE html>
<html lang="en">
...
</html>
You may want to change res.text
to res.content
if the response is binary.
This works:
var event = jQuery.Event('keypress');
event.which = 13;
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event);
you can simple use some div
to make a container and the display: flex;
to make the content appear side-by-side like this:
CSS
.splitscreen {
display:flex;
}
.splitscreen .left {
flex: 1;
}
.splitscreen .right {
flex: 1;
}
HTML
<div class="splitscreen">
<div class="left">
<!-- content -->
</div>
<div class="right">
<!-- content -->
</div>
</div>
using flex
you say who will use more space on the screen.
For bootstrap 3, the class navbar-static-top
instead of navbar-fixed-top
prevents this issue, unless you need the navbar to always be visible.
You can indeed place create a block of statements to execute after a conditional. But you have the syntax wrong. The parentheses must be used exactly as shown:
if <statement> (
do something
) else (
do something else
)
However, I do not believe that there is any built-in syntax for else-if
statements. You will unfortunately need to create nested blocks of if
statements to handle that.
Secondly, that %GPMANAGER_FOUND% == true
test looks mighty suspicious to me. I don't know what the environment variable is set to or how you're setting it, but I very much doubt that the code you've shown will produce the result you're looking for.
The following sample code works fine for me:
@echo off
if ERRORLEVEL == 0 (
echo GP Manager is up
goto Continue7
)
echo GP Manager is down
:Continue7
Please note a few specific details about my sample code:
@echo off
to keep from seeing all of the statements printed to the console as they execute, and instead just see the output of those that specifically begin with echo
.ERRORLEVEL
variable just as a test. Read more hereFor me upgrading pip from 8.1.1 to 9.0.1 solved this problem.
You can run something like sudo -H pip2 install --upgrade pip
to upgrade your pip version.
break x if ((int)strcmp(y, "hello")) == 0
On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!
Use the ViewPager.onPageChangeListener
:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
If you are experienced with SQL Server, I would recommend ASP.NET.
ADO.NET gives you good access to SQL Server, and with SMO, you will also have just about the best access to SQL Server features. You can access SQL Server from other environments, but nothing is quite as integrated or predictable.
You can call your stored procs with SqlCommand and process the results the SqlDataReader and you'll be in business.
Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.
document.body.style.cursor = 'wait';
It is very simple. For example : in you JS controller use this:
$scope.inputngmodel.$valid = false;
or
$scope.inputngmodel.$invalid = true;
or
$scope.formname.inputngmodel.$valid = false;
or
$scope.formname.inputngmodel.$invalid = true;
All works for me for different requirement. Hit up if this solve your problem.
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
Another way to find it quickly via the GUI on any windows system:
create a text file, type a word or two (or random text) in it, and save it.
Right-click on the file to show Properties.
"Size on disk" = allocation unit.
$epoch = 1483228800;
$dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00
In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:
r ----- Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c ----- 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y ----- Mar/15/2017
d-m-Y ----- 15-03-2017
Y-m-d H:i:s ----- 2017-03-15 12:00:00
Follow the Instructions from the Ruby Installer Developer Kit Wiki:
cd C:\Ruby193\DevKit
ruby dk.rb init
ruby dk.rb review
ruby dk.rb install
To return to the problem at hand, you should be able to install JSON (or otherwise test that your DevKit successfully installed) by running the following commands which will perform an install of the JSON gem and then use it:
gem install json --platform=ruby
ruby -rubygems -e "require 'json'; puts JSON.load('[42]').inspect"
Here is a basic example that explains the callback()
function in JavaScript:
var x = 0;_x000D_
_x000D_
function testCallBack(param1, param2, callback) {_x000D_
alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);_x000D_
if (callback && typeof(callback) === "function") {_x000D_
x += 1;_x000D_
alert("Calla Back x= " + x);_x000D_
x += 1;_x000D_
callback();_x000D_
}_x000D_
}_x000D_
_x000D_
testCallBack('ham', 'cheese', function() {_x000D_
alert("Function X= " + x);_x000D_
});
_x000D_
workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
}
});
XML Copy Editor is perfect for this type of thing.
function isString (obj) {
return (Object.prototype.toString.call(obj) === '[object String]');
}
I saw that here:
http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
cellspacing (distance between cells) parameter of the TABLE tag is precisely what you want. The disadvantage is it's one value, used both for x and y, you can't choose different spacing or padding vertically/horizontally. There is a CSS property too, but it's not widely supported.
I believe you can only initialize the dialog one time. The example above is trying to initialize the dialog every time #terms is clicked. This will cause problems. Instead, the initialization should occur outside of the click event. Your example should probably look something like this:
$(document).ready(function() {
// dialog init
$('#terms').dialog({
autoOpen: false,
resizable: false,
modal: true,
width: 400,
height: 450,
overlay: { backgroundColor: "#000", opacity: 0.5 },
buttons: { "Close": function() { $(this).dialog('close'); } },
close: function(ev, ui) { $(this).close(); }
});
// click event
$('#showTerms').click(function(){
$('#terms').dialog('open').css('display','inline');
});
// date picker
$('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });
});
I'm thinking that once you clear that up, it should fix the 'open from link' issue you described.
In android-N, this feature is included in it. check Number-blocking update for android N
Android N now supports number-blocking in the platform and provides a framework API to let service providers maintain a blocked-number list. The default SMS app, the default phone app, and provider apps can read from and write to the blocked-number list. The list is not accessible to other app.
advantage of are:
For more information, see android.provider.BlockedNumberContract
Update an existing project.
To compile your app against the Android N platform, you need to use the Java 8 Developer Kit (JDK 8), and in order to use some tools with Android Studio 2.1, you need to install the Java 8 Runtime Environment (JRE 8).
Open the build.gradle file for your module and update the values as follows:
android {
compileSdkVersion 'android-N'
buildToolsVersion 24.0.0 rc1
...
defaultConfig {
minSdkVersion 'N'
targetSdkVersion 'N'
...
}
...
}
Starting from iOS 13 Apple has changed [deviceToken description]
output. Now it is like this {length=32,bytes=0x0b8823aec3460e1724e795cba45d22e8...af8c09f971d0dabc}
which is incorrect for device token.
I suggest to use this code snippet to resolve a problem:
+ (NSString *)stringFromDeviceToken:(NSData *)deviceToken {
NSUInteger length = deviceToken.length;
if (length == 0) {
return nil;
}
const unsigned char *buffer = deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(length * 2)];
for (int i = 0; i < length; ++i) {
[hexString appendFormat:@"%02x", buffer[i]];
}
return [hexString copy];
}
It will work for iOS13 and lower.
All these answers date back to 2016 or earlier... There's a new web standard for this using flex-boxes
. In general floats
for these sorts of problems is now frowned upon.
HTML
<div class="image-txt-container">
<img src="https://images4.alphacoders.com/206/thumb-350-20658.jpg">
<h2>
Text here
</h2>
</div>
CSS
.image-txt-container {
display: flex;
align-items: center;
flex-direction: row;
}
Example fiddle: https://jsfiddle.net/r8zgokeb/1/
You can di this:
#axs[1].plot(clust_data[:,0],clust_data[:,1]) # Remove this if you don't need it
axs[1].axis("off") # This will leave the table alone in the window
Try cloning before doing the checkout.
do git clone "whee to find it" then after cloning check out the branch
Simple and elegant solution:
const date = new Date(`${year}-${month}-${day} 00:00`)
const isValidDate = (Boolean(+date) && date.getDate() == day)
sources:
[1] https://medium.com/@esganzerla/simple-date-validation-with-javascript-caea0f71883c
You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.
@RequestParam(required = false)String name
If you use console.clear()
, that seems to work in chrome. Note, it will output a "Console was cleared" message.
Note, I got an error right after clearing the console, so it doesn't disable the console, only clears it. Also, I have only tried this in chrome, so I dont know how cross-browser it is.
EDIT: I tested this in Chrome, IE, Firefox, and Opera. It works in Chrome, MSIE and Opera's default consoles, but not in Firefox's, however, it does work in Firebug.
Below solution is a clean work around.It does not compromises security because we are using same strict firewall.
The Steps for fixing is as below:
STEP 1 : Create a Class overriding StrictHttpFirewall as below.
package com.biz.brains.project.security.firewall;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;
public class CustomStrictHttpFirewall implements HttpFirewall {
private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());
private static final String ENCODED_PERCENT = "%25";
private static final String PERCENT = "%";
private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));
private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));
private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));
private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));
private Set<String> encodedUrlBlacklist = new HashSet<String>();
private Set<String> decodedUrlBlacklist = new HashSet<String>();
private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();
public CustomStrictHttpFirewall() {
urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
this.encodedUrlBlacklist.add(ENCODED_PERCENT);
this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
this.decodedUrlBlacklist.add(PERCENT);
}
public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
}
public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
if (allowedHttpMethods == null) {
throw new IllegalArgumentException("allowedHttpMethods cannot be null");
}
if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
} else {
this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
}
}
public void setAllowSemicolon(boolean allowSemicolon) {
if (allowSemicolon) {
urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
} else {
urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
}
}
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
if (allowUrlEncodedSlash) {
urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
} else {
urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
}
}
public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
if (allowUrlEncodedPeriod) {
this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
} else {
this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
}
}
public void setAllowBackSlash(boolean allowBackSlash) {
if (allowBackSlash) {
urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
} else {
urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
}
}
public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
if (allowUrlEncodedPercent) {
this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
this.decodedUrlBlacklist.remove(PERCENT);
} else {
this.encodedUrlBlacklist.add(ENCODED_PERCENT);
this.decodedUrlBlacklist.add(PERCENT);
}
}
private void urlBlacklistsAddAll(Collection<String> values) {
this.encodedUrlBlacklist.addAll(values);
this.decodedUrlBlacklist.addAll(values);
}
private void urlBlacklistsRemoveAll(Collection<String> values) {
this.encodedUrlBlacklist.removeAll(values);
this.decodedUrlBlacklist.removeAll(values);
}
@Override
public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
rejectForbiddenHttpMethod(request);
rejectedBlacklistedUrls(request);
if (!isNormalized(request)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
}
String requestUri = request.getRequestURI();
if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
request.setAttribute("isNormalized", new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
}
return new FirewalledRequest(request) {
@Override
public void reset() {
}
};
}
private void rejectForbiddenHttpMethod(HttpServletRequest request) {
if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
return;
}
if (!this.allowedHttpMethods.contains(request.getMethod())) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the HTTP method \"" +
request.getMethod() +
"\" was not included within the whitelist " +
this.allowedHttpMethods));
}
}
private void rejectedBlacklistedUrls(HttpServletRequest request) {
for (String forbidden : this.encodedUrlBlacklist) {
if (encodedUrlContains(request, forbidden)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
}
}
for (String forbidden : this.decodedUrlBlacklist) {
if (decodedUrlContains(request, forbidden)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
}
}
}
@Override
public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
return new FirewalledResponse(response);
}
private static Set<String> createDefaultAllowedHttpMethods() {
Set<String> result = new HashSet<>();
result.add(HttpMethod.DELETE.name());
result.add(HttpMethod.GET.name());
result.add(HttpMethod.HEAD.name());
result.add(HttpMethod.OPTIONS.name());
result.add(HttpMethod.PATCH.name());
result.add(HttpMethod.POST.name());
result.add(HttpMethod.PUT.name());
return result;
}
private static boolean isNormalized(HttpServletRequest request) {
if (!isNormalized(request.getRequestURI())) {
return false;
}
if (!isNormalized(request.getContextPath())) {
return false;
}
if (!isNormalized(request.getServletPath())) {
return false;
}
if (!isNormalized(request.getPathInfo())) {
return false;
}
return true;
}
private static boolean encodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getContextPath(), value)) {
return true;
}
return valueContains(request.getRequestURI(), value);
}
private static boolean decodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getServletPath(), value)) {
return true;
}
if (valueContains(request.getPathInfo(), value)) {
return true;
}
return false;
}
private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
int length = uri.length();
for (int i = 0; i < length; i++) {
char c = uri.charAt(i);
if (c < '\u0020' || c > '\u007e') {
return false;
}
}
return true;
}
private static boolean valueContains(String value, String contains) {
return value != null && value.contains(contains);
}
private static boolean isNormalized(String path) {
if (path == null) {
return true;
}
if (path.indexOf("//") > -1) {
return false;
}
for (int j = path.length(); j > 0;) {
int i = path.lastIndexOf('/', j - 1);
int gap = j - i;
if (gap == 2 && path.charAt(i + 1) == '.') {
// ".", "/./" or "/."
return false;
} else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
return false;
}
j = i;
}
return true;
}
}
STEP 2 : Create a FirewalledResponse class
package com.biz.brains.project.security.firewall;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
class FirewalledResponse extends HttpServletResponseWrapper {
private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
private static final String LOCATION_HEADER = "Location";
private static final String SET_COOKIE_HEADER = "Set-Cookie";
public FirewalledResponse(HttpServletResponse response) {
super(response);
}
@Override
public void sendRedirect(String location) throws IOException {
// TODO: implement pluggable validation, instead of simple blacklisting.
// SEC-1790. Prevent redirects containing CRLF
validateCrlf(LOCATION_HEADER, location);
super.sendRedirect(location);
}
@Override
public void setHeader(String name, String value) {
validateCrlf(name, value);
super.setHeader(name, value);
}
@Override
public void addHeader(String name, String value) {
validateCrlf(name, value);
super.addHeader(name, value);
}
@Override
public void addCookie(Cookie cookie) {
if (cookie != null) {
validateCrlf(SET_COOKIE_HEADER, cookie.getName());
validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
}
super.addCookie(cookie);
}
void validateCrlf(String name, String value) {
if (hasCrlf(name) || hasCrlf(value)) {
throw new IllegalArgumentException(
"Invalid characters (CR/LF) in header " + name);
}
}
private boolean hasCrlf(String value) {
return value != null && CR_OR_LF.matcher(value).find();
}
}
STEP 3: Create a custom Filter to suppress the RejectedException
package com.biz.brains.project.security.filter;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
if(Objects.nonNull(requestRejectedException)) {
throw requestRejectedException;
}else {
filterChain.doFilter(servletRequest, servletResponse);
}
} catch (RequestRejectedException requestRejectedException) {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
log
.error(
"request_rejected: remote={}, user_agent={}, request_url={}",
httpServletRequest.getRemoteHost(),
httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
httpServletRequest.getRequestURL(),
requestRejectedException
);
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
STEP 4: Add the custom filter to spring filter chain in security configuration
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new RequestRejectedExceptionFilter(),
ChannelProcessingFilter.class);
}
Now using above fix, we can handle RequestRejectedException
with Error 404 page.
Usually you can use the .animate() method to manipulate arbitrary CSS properties, but for background colors you need to use the color plugin. Once you include this plugin, you can use something like others have indicated $('div').animate({backgroundColor: '#f00'})
to change the color.
As others have written, some of this can be done using the jQuery UI library as well.
There are different ways in which properties can be overridden. Assuming you have
.left { background: blue }
e.g. any of the following would override it:
a.background-none { background: none; }
body .background-none { background: none; }
.background-none { background: none !important; }
The first two “win” by selector specificity; the third one wins by !important
, a blunt instrument.
You could also organize your style sheets so that e.g. the rule
.background-none { background: none; }
wins simply by order, i.e. by being after an otherwise equally “powerful” rule. But this imposes restrictions and requires you to be careful in any reorganization of style sheets.
These are all examples of the CSS Cascade, a crucial but widely misunderstood concept. It defines the exact rules for resolving conflicts between style sheet rules.
P.S. I used left
and background-none
as they were used in the question. They are examples of class names that should not be used, since they reflect specific rendering and not structural or semantic roles.
tick_params is very useful for setting tick properties. Labels can be moved to the top with:
ax.tick_params(labelbottom=False,labeltop=True)
ref :- http://developer.android.com/training/sharing/send.html#send-multiple-content
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));
I found an issue with someone using PDO and the answer was to use this for the PDO connection string:
$pdo = new PDO(
'mysql:host=mysql.example.com;dbname=example_db',
"username",
"password",
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
The site I took this from is down, but I was able to get it using the Google cache, luckily.
1)
total = 0;
for i=1:size(A,1)
for j=1:size(A,2)
total = total + A(i,j);
end
end
2)
total = sum(A(:));
Use textView
instead then conform with its delegate, call the textViewDidChange
method inside of that method call tableView.beginUpdates()
and tableView.endUpdates()
and don't forget to set rowHeight
and estimatedRowHeight
to UITableView.automaticDimension
.
You can use javascript Number method to parse it to an number,
var num=Number (num_str);
This worked for me:
line-height: 80%;
It seems you've found your answer already but since you mentioned the active form I'll contribute with one more, even if it differs only ever so slightly.
<?php
$form = ActiveForm::begin();
echo $form->field($model, 'attribute')
->dropDownList(
$items, // Flat array ('id'=>'label')
['prompt'=>''] // options
);
ActiveForm::end();
?>
1) You can wrap your text as CDATA like this:
<mytag>
<![CDATA[Your text goes here. Btw: 5<6 and 6>5]]>
</mytag>
see http://www.w3schools.com/xml/xml_cdata.asp
2) As already someone said: Escape those chars. E.g. like so:
5<6 and 6>5
This worked for me, just try this:
const id = req.params.id;
YourSchema
.remove({_id: id})
.exec()
.then(result => {
res.status(200).json({
message: 'deleted',
request: {
type: 'POST',
url: 'http://localhost:3000/yourroutes/'
}
})
})
.catch(err => {
res.status(500).json({
error: err
})
});
grep
patterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.
However you can find empty lines like this:
grep '^$' file
grep '^[[:space:]]*$' file # include white spaces
I am not the OP of this answer but it helped me so:
I wanted to change the color of the next/previous buttons of the bootstrap carousel on my homepage.
Solution: Copy the selector names from bootstrap.css and move them to your own style.css (with your own prefrences..) :
.carousel-control-prev-icon,
.carousel-control-next-icon {
height: 100px;
width: 100px;
outline: black;
background-size: 100%, 100%;
border-radius: 50%;
border: 1px solid black;
background-image: none;
}
.carousel-control-next-icon:after
{
content: '>';
font-size: 55px;
color: red;
}
.carousel-control-prev-icon:after {
content: '<';
font-size: 55px;
color: red;
}
_x000D_
The finalize
method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection.
Note that it's entirely possible that an object never gets garbage collected (and thus finalize
is never called). This can happen when the object never becomes eligible for gc (because it's reachable through the entire lifetime of the JVM) or when no garbage collection actually runs between the time the object become eligible and the time the JVM stops running (this often occurs with simple test programs).
There are ways to tell the JVM to run finalize
on objects that it wasn't called on yet, but using them isn't a good idea either (the guarantees of that method aren't very strong either).
If you rely on finalize
for the correct operation of your application, then you're doing something wrong. finalize
should only be used for cleanup of (usually non-Java) resources. And that's exactly because the JVM doesn't guarantee that finalize
is ever called on any object.
From java docs(String class source),
/**
* Returns a copy of the string, with leading and trailing whitespace
* omitted.
* <p>
* If this <code>String</code> object represents an empty character
* sequence, or the first and last characters of character sequence
* represented by this <code>String</code> object both have codes
* greater than <code>'\u0020'</code> (the space character), then a
* reference to this <code>String</code> object is returned.
* <p>
* Otherwise, if there is no character with a code greater than
* <code>'\u0020'</code> in the string, then a new
* <code>String</code> object representing an empty string is created
* and returned.
* <p>
* Otherwise, let <i>k</i> be the index of the first character in the
* string whose code is greater than <code>'\u0020'</code>, and let
* <i>m</i> be the index of the last character in the string whose code
* is greater than <code>'\u0020'</code>. A new <code>String</code>
* object is created, representing the substring of this string that
* begins with the character at index <i>k</i> and ends with the
* character at index <i>m</i>-that is, the result of
* <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
* <p>
* This method may be used to trim whitespace (as defined above) from
* the beginning and end of a string.
*
* @return A copy of this string with leading and trailing white
* space removed, or this string if it has no leading or
* trailing white space.
*/
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
Note that after getting start and length it calls the substring method of String class.
In Python 2.x this is not guaranteed as it is possible for True
and False
to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.
In Python 3.x True
and False
are keywords and will always be equal to 1
and 0
.
Under normal circumstances in Python 2, and always in Python 3:
False
object is of type bool
which is a subclass of int
:
object
|
int
|
bool
It is the only reason why in your example, ['zero', 'one'][False]
does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__
method (thanks mark-dickinson).
Edit:
It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:
There are two types of integers: [...] Integers (int) [...] Booleans (bool)
and in the boolean subsection:
Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
There is also, for Python 2:
In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.
So booleans are explicitly considered as integers in Python 2 and 3.
So you're safe until Python 4 comes along. ;-)
Using pathlib you can get the folder in which the current file is located. __file__
is the pathname of the file from which the module was loaded.
Ref: docs
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
Doc ref: link
The opposite of .append()
is .prepend()
.
From the jQuery documentation for prepend…
The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).
I realize this doesn’t answer the OP’s specific case. But it does answer the question heading. :) And it’s the first hit on Google for “jquery opposite append”.
I had this exact problem and I solved it this way:
library(openxlsx) # loads library and doesn't require Java installed
your_df_list <- c("df1", "df2", ..., "dfn")
for(name in your_df_list){
write.xlsx(x = get(name),
file = "your_spreadsheet_name.xlsx",
sheetName = name)
}
That way you won't have to create a very long list manually if you have tons of dataframes to write to Excel.
You won't gain anything by checking that the key exists. This is the code of HashMap
:
@Override
public boolean containsKey(Object key) {
Entry<K, V> m = getEntry(key);
return m != null;
}
@Override
public V get(Object key) {
Entry<K, V> m = getEntry(key);
if (m != null) {
return m.value;
}
return null;
}
Just check if the return value for get()
is different from null
.
This is the HashMap source code.
Resources :
I just used this:
grep -c $'\x0c' filename
To search for and count a page control character in the file..
So to include an offset in the output:
grep -b -o $'\x0c' filename | less
I am just piping the result to less because the character I am greping for does not print well and the less displays the results cleanly. Output example:
21:^L
23:^L
2005:^L
I made a new checkout from the same project to a different location then copied the .svn folder from it and replaced with my old .svn folder. After that called the svn update function and everything were synced properly up to date.
Committing in git can be a multiple step process or one step depending on the situation.
This situation is where you have multiple file updated and wants to commit:
You have to add all the modified files before you commit anything.
git add -A
or
git add --all
After that you can use commit all the added files
git commit
with this you have to add the message for this commit.
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
ArrayList list = null;
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
while (result.next()) {
list.add(result.getInt(1));
}
statement.close();
int id[] = new int[list.size()];
for (int i = 0; i < id.length; i++) {
try {
id[i] = ((Integer) list.get(i)).intValue();
} catch(NullPointerException ne) {
} catch(ClassCastException ch) {}
}
return id;
}
// enter code here
This code shows why ArrayList
is important and why we use it. Simply casting int
from Object
. May be its helpful.
The correct syntax is:
FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
, LCASE( SUBSTRING( NEW.bname, 2 ) ) )
Just overwriting of getInputStream()
did not work in my case. My server implementation seems to parse parameters without calling this method. I did not find any other way, but re-implement the all four getParameter* methods as well. Here is the code of getParameterMap
(Apache Http Client and Google Guava library used):
@Override
public Map<String, String[]> getParameterMap() {
Iterable<NameValuePair> params = URLEncodedUtils.parse(getQueryString(), NullUtils.UTF8);
try {
String cts = getContentType();
if (cts != null) {
ContentType ct = ContentType.parse(cts);
if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
List<NameValuePair> postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()), NullUtils.UTF8);
params = Iterables.concat(params, postParams);
}
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
Map<String, String[]> result = toMap(params);
return result;
}
public static Map<String, String[]> toMap(Iterable<NameValuePair> body) {
Map<String, String[]> result = new LinkedHashMap<>();
for (NameValuePair e : body) {
String key = e.getName();
String value = e.getValue();
if (result.containsKey(key)) {
String[] newValue = ObjectArrays.concat(result.get(key), value);
result.remove(key);
result.put(key, newValue);
} else {
result.put(key, new String[] {value});
}
}
return result;
}
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
Something like this?
<a href="#" onClick="MyWindow=window.open('http://www.google.com','MyWindow','width=600,height=300'); return false;">Click Here</a>
I think Rubens' class is a good idea so thought to make an immutable sample of his Time class with basic validation.
class Time
{
public int Hours { get; private set; }
public int Minutes { get; private set; }
public int Seconds { get; private set; }
public Time(uint h, uint m, uint s)
{
if(h > 23 || m > 59 || s > 59)
{
throw new ArgumentException("Invalid time specified");
}
Hours = (int)h; Minutes = (int)m; Seconds = (int)s;
}
public Time(DateTime dt)
{
Hours = dt.Hour;
Minutes = dt.Minute;
Seconds = dt.Second;
}
public override string ToString()
{
return String.Format(
"{0:00}:{1:00}:{2:00}",
this.Hours, this.Minutes, this.Seconds);
}
}
In my case i have changed the root folder in which the Eclipse project were stored. I have discovered tha when i have runned :
cat .plugins/org.eclip.resources/.projects/<projectname>/.location
SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name
Try preventing default on mousedown event:
<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>
or
<div onmousedown="return false">asd</div>
If you have to do group by
using hibernate criteria use projections.groupPropery
like the following,
@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;
Also in iOS 7 for proper working of all of mentioned methods add this in your view controller viewDidLoad
method:
if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
self.automaticallyAdjustsScrollViewInsets = NO;
}
Otherwise neither of methods would work as it should.
Another (less javascriptish) approach, that I did, goes something like this:
public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
{
var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
// Above gets the following: <input name="__RequestVerificationToken" type="hidden" value="PnQE7R0MIBBAzC7SqtVvwrJpGbRvPgzWHo5dSyoSaZoabRjf9pCyzjujYBU_qKDJmwIOiPRDwBV1TNVdXFVgzAvN9_l2yt9-nf4Owif0qIDz7WRAmydVPIm6_pmJAI--wvvFQO7g0VvoFArFtAR2v6Ch1wmXCZ89v0-lNOGZLZc1" />
var removedStart = antiForgeryInputTag.Replace(@"<input name=""__RequestVerificationToken"" type=""hidden"" value=""", "");
var tokenValue = removedStart.Replace(@""" />", "");
if (antiForgeryInputTag == removedStart || removedStart == tokenValue)
throw new InvalidOperationException("Oops! The Html.AntiForgeryToken() method seems to return something I did not expect.");
return new MvcHtmlString(string.Format(@"{0}:""{1}""", "__RequestVerificationToken", tokenValue));
}
__RequestVerificationToken:"P5g2D8vRyE3aBn7qQKfVVVAsQc853s-naENvpUAPZLipuw0pa_ffBf9cINzFgIRPwsf7Ykjt46ttJy5ox5r3mzpqvmgNYdnKc1125jphQV0NnM5nGFtcXXqoY3RpusTH_WcHPzH4S4l1PmB8Uu7ubZBftqFdxCLC5n-xT0fHcAY1"
$(function () {
$("#submit-list").click(function () {
$.ajax({
url: '@Url.Action("SortDataSourceLibraries")',
data: { items: $(".sortable").sortable('toArray'), @Html.AntiForgeryTokenForAjaxPost() },
type: 'post',
traditional: true
});
});
});
And it seems to work!
Can be related to https://github.com/bundler/bundler-features/issues/34 if you are running the command inside another bundle exec
. Try using Bundler.with_original_env
if that is the case.
for(int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}
This changed a bit in babel v6.
From the docs:
The polyfill will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node.
Installation:
$ npm install babel-polyfill
Usage in Node / Browserify / Webpack:
To include the polyfill you need to require it at the top of the entry point to your application.
require("babel-polyfill");
Usage in Browser:
Available from the dist/polyfill.js
file within a babel-polyfill
npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script>
before it.
NOTE: Do not require
this via browserify etc, use babel-polyfill
.
Do this.
var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);
Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this..
EDIT : ServiceRegistryBuilder is deprecated. you must use StandardServiceRegistryBuilder
public void testConnection() throws Exception {
logger.info("Trying to create a test connection with the database.");
Configuration configuration = new Configuration();
configuration.configure("hibernate_sp.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
Session session = sessionFactory.openSession();
logger.info("Test connection with the database created successfuly.");
}
For more reference and in depth detail, you can check the hibernate's official test case at https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java function (buildSessionFactory()).
The better solution is to simply move the position of the viewport based on the change in the zoom. The zoom point is simply the point in the old zoom and the new zoom that you want to remain the same. Which is to say the viewport pre-zoomed and the viewport post-zoomed have the same zoompoint relative to the viewport. Given that we're scaling relative to the origin. You can adjust the viewport position accordingly:
scalechange = newscale - oldscale;
offsetX = -(zoomPointX * scalechange);
offsetY = -(zoomPointY * scalechange);
So really you can just pan over down and to the right when you zoom in, by a factor of how much you zoomed in, relative to the point you zoomed at.
If you are in ES6 just use the "static" keyword on your method from your example would be the following: static alertMessage: function() {
...
},
Hope can help anyone out there :)
for AND you use
if ($status = 'clear' && $pRent == 0) {
mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
}
for OR you use
if ($status = 'clear' || $pRent == 0) {
mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
}
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
Most database servers have a COALESCE function, which will return the first argument that is non-null, so the following should do what you want:
SELECT COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
Since there seems to be a lot of discussion about
COALESCE/ISNULL will still return NULL if no rows match, try this query you can copy-and-paste into SQL Server directly as-is:
SELECT coalesce(SUM(column_id),0) AS TotalPrice
FROM sys.columns
WHERE (object_id BETWEEN -1 AND -2)
Note that the where clause excludes all the rows from sys.columns from consideration, but the 'sum' operator still results in a single row being returned that is null, which coalesce fixes to be a single row with a 0.
The break
statement exists the current looping control structure and jumps behind it while the continue
exits too but jumping back to the looping condition.
using git rm -r --cached .idea
in your terminal worked great for me. It disables the change tracking and unset a number of files under the rubymine folder (idea/) that I could then add and commit to git, thus removing the comparison and allowing the gitignore setting of .idea/
to work.
The "a:hover
" literally tells the browser to change the properties for the <a>
-tag, when the mouse is hovered over it. What you perhaps meant was "the div:hover
" instead, which would trigger when the div was chosen.
Just to make sure, if you want to change only one particular div, give it an id ("<div id='something'>
") and use the CSS "#something:hover {...}
" instead. If you want to edit a group of divs, make them into a class ("<div class='else'>
") and use the CSS ".else {...}
" in this case (note the period before the class' name!)
I had a similar problem for Android 4 Phone, but worked for versions above this. I had added "multidexEnabled=true" line to gradle script due to some reasons before. And now I deleted this line and it worked for both versions (Android 4 and above). But I didn't understand why I added that line and how it works now.
You can search your hard drive for one of the programs that's installed with the SDK. For instance, if you search for aapt.exe
or adb.exe
, they will be in the platform-tools
directory underneath the installation directory (which is what you're after).
^$ -- regex to accept empty string.And it wont match "/n" or "foobar/n" as you mentioned. You could test this regex on https://www.regextester.com/1924.
If you have your existing regex use or(|) in your regex to match empty string. For example /^[A-Za-z0-9&._ ]+$|^$/
You have two ways:
First go to the particular path of Android SDK:
1) Open your command prompt and traverse to the platform-tools directory through it such as
$ cd Frameworks\Android-Sdk\platform-tools
2) Run your adb commands now such as to know that your adb is working properly :
$ adb devices OR adb logcat OR simply adb
Second way is :
1) Right click on your My Computer.
2) Open Environment variables.
3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).
4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.
5) Restart your computer once.
6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.
Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"
You could use iotop. It doesn't rely on a kernel patch. It Works with stock Ubuntu kernel
There is a package for it in the Ubuntu repos. You can install it using
sudo apt-get install iotop
The "vw" solution has a problem when going to very small screens. You can set the base size and go up from there with calc():
font-size: calc(16px + 0.4vw);
There is no lawbreaking or outlaw standard other than common sense. If we abstract this like two people talking, the standard is the best way they can accurately understand each other in minimum words in minimum time. In our case, 'minimum words' is optimizing bandwidth for transport efficiency and 'accurately understand' is the structure for parser efficiency; which ultimately ends up with the less the data, and the common the structure; so that it can go through a pin hole and can be parsed through a common scope (at least initially).
Almost in every cases suggested, I see separate responses for 'Success' and 'Error' scenario, which is kind of ambiguity to me. If responses are different in these two cases, then why do we really need to put a 'Success' flag there? Is it not obvious that the absence of 'Error' is a 'Success'? Is it possible to have a response where 'Success' is TRUE with an 'Error' set? Or the way, 'Success' is FALSE with no 'Error' set? Just one flag is not enough? I would prefer to have the 'Error' flag only, because I believe there will be less 'Error' than 'Success'.
Also, should we really make the 'Error' a flag? What about if I want to respond with multiple validation errors? So, I find it more efficient to have an 'Error' node with each error as child to that node; where an empty (counts to zero) 'Error' node would denote a 'Success'.
If you're removing the path for Python 3 specifically, I found it in ~/.zprofile
and ~/.zshrc.
Load state from localStorage if exist:
constructor(props) {
super(props);
this.state = JSON.parse(localStorage.getItem('state'))
? JSON.parse(localStorage.getItem('state'))
: initialState
override this.setState
to automatically save state after each update :
const orginial = this.setState;
this.setState = function() {
let arguments0 = arguments[0];
let arguments1 = () => (arguments[1], localStorage.setItem('state', JSON.stringify(this.state)));
orginial.bind(this)(arguments0, arguments1);
};
Keep in mind that if you're doing a cross-domain Ajax call (by using JSONP) - you can't do it synchronously, the async
flag will be ignored by jQuery.
$.ajax({
url: "testserver.php",
dataType: 'jsonp', // jsonp
async: false //IGNORED!!
});
For JSONP-calls you could use:
Consider whether you really need all this data explicitly, or can the matrix be sparse? There is good support in R (see Matrix
package for e.g.) for sparse matrices.
Keep all other processes and objects in R to a minimum when you need to make objects of this size. Use gc()
to clear now unused memory, or, better only create the object you need in one session.
If the above cannot help, get a 64-bit machine with as much RAM as you can afford, and install 64-bit R.
If you cannot do that there are many online services for remote computing.
If you cannot do that the memory-mapping tools like package ff
(or bigmemory
as Sascha mentions) will help you build a new solution. In my limited experience ff
is the more advanced package, but you should read the High Performance Computing
topic on CRAN Task Views.
I have try a lot of ways. this work for me perfectly.
If you choose pictrue from Gallery. You need to be ware of getting Uri
from intent.clipdata
or intent.data
, because one of them may be null in different version.
private fun onChoosePicture(data: Intent?):Bitmap {
data?.let {
var fileUri:Uri? = null
data.clipData?.let {clip->
if(clip.itemCount>0){
fileUri = clip.getItemAt(0).uri
}
}
it.data?.let {uri->
fileUri = uri
}
return MediaStore.Images.Media.getBitmap(this.contentResolver, fileUri )
}