Your problem is that you have declare twice the exec-maven-plugin :
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-
integration\src\main\java\example\Main< /mainClass>
</configuration>
</plugin>
...
< plugin>
< groupId>org.codehaus.mojo</groupId>
< artifactId>exec-maven-plugin</artifactId>
< version>1.2</version>
< /plugin>
The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.
Some reasons why this might happen:
If the problem is related to timeout settings, you may be able to resolve it by investigating the following:
private function sendHttpRequest($host, $path, $query, $port=80){
header("POST $path HTTP/1.1\r\n" );
header("Host: $host\r\n" );
header("Content-type: application/x-www-form-urlencoded\r\n" );
header("Content-length: " . strlen($query) . "\r\n" );
header("Connection: close\r\n\r\n" );
header($query);
}
This will get you right away
from above solutions, Nothing worked for me. This worked:
$('#client_filter').html(' '); //this worked
Why is that? :)
$.ajax({
type: 'POST',
url: xyz_ajax,
dataType: "json",
data : { csrfmiddlewaretoken: csrftoken,
instancess : selected_instances },
success: function(response) {
//clear the client DD
$('#client_filter').val('').trigger('change') ; //not working
$('#client_filter').val('').trigger('chosen:updated') ; //not working
$('#client_filter').val('').trigger('liszt:updated') ; //not working
$('#client_filter').html(' '); //this worked
jQuery.each(response, function(index, item) {
$('#client_filter').append('<option value="'+item.id+'">' + item.text + '</option>');
});
$('#client_filter').trigger("chosen:updated");
}
});
}
if you want to check the run code for a particular version of swift you can use
#if compiler(>=5.1) //4.2, 3.0, 2.0 replace whatever swft version you wants to check
#endif
Try running all targets individually to check that all are running correct
run ant target name to run a target individually
e.g. ant build-project
Also the default target you specified is
project basedir="." default="build" name="iControlSilk4J"
This will only execute build-subprojects,build-project and init
Note: With ConcurrentMap you can use the more efficient
values.putIfAbsent(NoteColumns.CREATED_DATE, now);
I prefer the less verbose solution and avoid methods like IsTrue or IsFalse or their like.
Here's a simple one liner for removing an object by property from an array of objects.
delete this.items[this.items.findIndex(item => item.item_id == item_id)];
or
this.items = this.items.filter(item => item.item_id !== item.item_id);
If you are not wanting to use async
you can add .Result
to force the code to execute synchronously:
private string GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
var contents = response.Content.ReadAsStringAsync().Result;
return contents;
}
Similar to answer by @Jeff_Alieffson, but not relying on default Locale
:
Use DecimalFormatSymbols
for explicit locale:
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(new Locale("ru", "RU"));
Or explicit separator symbols:
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(' ');
Then:
new DecimalFormat("#,##0.00", decimalFormatSymbols).format(new BigDecimal("12345"));
Result:
12 345.00
You can do it with 1 printf
:
System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);
I suspect looking at the excerpt that the function trustSrc
from trustSrc(currentProject.url)
is not defined in the controller.
You need to inject the $sce
service in the controller and trustAsResourceUrl
the url
there.
In the controller:
function AppCtrl($scope, $sce) {
// ...
$scope.setProject = function (id) {
$scope.currentProject = $scope.projects[id];
$scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
}
}
In the Template:
<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>
If it helps, You can also create an alias in your .bashrc
or .bash_profile
.
function dsize()
{
dir=$(pwd)
if [ "$1" != "" ]; then
dir=$1
fi
echo $(du -hs $dir)
}
This prints the size of the current directory or the directory you have passed as an argument.
In my opinion, turning off the -e
option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e
Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.
If you have a line in your script where failure is expected, like a grep or a find, then just add || true
to the end of that line. That ensures that line will always return success.
If you need to use that exit code, you can either hoist the command into your if statement:
grep foo bar; if [ $? == 0 ]; then ... --> if grep foo bar; then ...
Or you can capture the return code in your ||
clause:
grep foo bar || ret=$?
Just do it:
The C++ string class is std::string
. To use it you need to include the <string>
header.
For the fundamentals of how to use std::string
, you'll want to consult a good introductory C++ book.
The keyword extends
can be used for interfaces and classes only.
If you just want to declare a type that has additional properties, you can use intersection type:
type UserEvent = Event & {UserId: string}
UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:
type Event = {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
It does not work the other way round - UserEvent
must be declared as interface, not a type
if you want to use extends
syntax.
And it's still impossible to use extend
with arbitrary types - for example, it does not work if Event
is a type parameter without any constraints.
With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.
Add programatically noborder class to specific row to hide it
<style>
.noborder
{
border:none;
}
</style>
<table>
<tr>
<th>heading1</th>
<th>heading2</th>
</tr>
<tr>
<td>content1</td>
<td>content2</td>
</tr>
/*no border for this row */
<tr class="noborder">
<td>content1</td>
<td>content2</td>
</tr>
</table>
There are two reasons you might get this message:
%FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i
. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:
c.sendall()
instead of c.send()
to prevent possible issues where you may not have sent the entire msg with one call (see docs).'b'
for bytes string: c.sendall(b'Thank you for connecting')
Best solution (should work w/both 2.x & 3.x):
output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))
Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.
You need to compile the bibtex file.
Suppose you have article.tex
and article.bib
. You need to run:
latex article.tex
(this will generate a document with question marks in place of unknown references)bibtex article
(this will parse all the .bib files that were included in the article and generate metainformation regarding references)latex article.tex
(this will generate document with all the references in the correct places)latex article.tex
(just in case if adding references broke page numbering somewhere)You can use "find" for remove all files in the /objects
directory with 0 in size with the command:
find .git/objects/ -size 0 -delete
Backup is recommended.
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
I'm surprised that this hasn't shown up yet:
In [34]: sentence = "I really like python, it's pretty awesome.".split()
In [35]: N = 4
In [36]: grams = [sentence[i:i+N] for i in xrange(len(sentence)-N+1)]
In [37]: for gram in grams: print gram
['I', 'really', 'like', 'python,']
['really', 'like', 'python,', "it's"]
['like', 'python,', "it's", 'pretty']
['python,', "it's", 'pretty', 'awesome.']
You could use getopt.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int bflag = 0;
int sflag = 0;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "bs")) != -1)
switch (c)
{
case 'b':
bflag = 1;
break;
case 's':
sflag = 1;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("bflag = %d, sflag = %d\n", bflag, sflag);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
@unutbu's answer is quite close to the right answer.
By default, plt.imshow() will try to scale your (MxN) array data to 0.0~1.0. And then map to 0~255. For most natural taken images, this is fine, you won't see a different. But if you have narrow range of pixel value image, say the min pixel is 156 and the max pixel is 234. The gray image will looks totally wrong. The right way to show an image in gray is
from matplotlib.colors import NoNorm
...
plt.imshow(img,cmap='gray',norm=NoNorm())
...
Let's see an example:
this is the origianl image: original
this is using defaul norm setting,which is None: wrong pic
this is using NoNorm setting,which is NoNorm(): right pic
In Oracle database we can achieve like this.
CREATE TABLE Student(
StudentID Number(38, 0) not null,
DepartmentID Number(38, 0) not null,
PRIMARY KEY (StudentID, DepartmentID)
);
In my case the problem was using the language tag "en_US" in Locale.forLanguageTag(..)
instead of "en-US" - use a dash instead of underline!
Also use Locale.forLanguageTag("en-US")
instead of new Locale("en_US")
or new Locale("en_US")
to define a language ("en") with a region ("US") - but new Locale("en")
works.
For debian, from the 10gen repo, between 2.4.x and 2.6.x, they renamed the init script /etc/init.d/mongodb to /etc/init.d/mongod, and the default config file from /etc/mongodb.conf to /etc/mongod.conf, and the PID and lock files from "mongodb" to "mongod" too. This made upgrading a pain, and I don't see it mentioned in their docs anywhere. Anyway, the solution is to remove the old "mongodb" versions:
update-rc.d -f mongodb remove
rm /etc/init.d/mongodb
rm /var/run/mongodb.pid
diff -ur /etc/mongodb.conf /etc/mongod.conf
Now, look and see what config changes you need to keep, and put them in mongod.conf.
Then:
rm /etc/mongodb.conf
Now you can:
service mongod restart
Aside from @see
, a more general way of refering to another class and possibly method of that class is {@link somepackage.SomeClass#someMethod(paramTypes)}
. This has the benefit of being usable in the middle of a javadoc description.
From the javadoc documentation (description of the @link tag):
This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.
Google turned up a page on the Sun site that discusses this a bit.
You're right about the variable; this
can indeed be used to differentiate a method variable from a class field.
private int x;
public void setX(int x) {
this.x=x;
}
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX) {
x=newX;
}
Same results, but with no chance of a bug where you accidentally refer to x
when you really meant to be referring to x
instead.
As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
There is another issue to be considered here. Some people expect that adding custom method to your repository will automatically expose them as REST services under '/search' link. This is unfortunately not the case. Spring doesn't support that currently.
This is 'by design' feature, spring data rest explicitly checks if method is a custom method and doesn't expose it as a REST search link:
private boolean isQueryMethodCandidate(Method method) {
return isQueryAnnotationPresentOn(method) || !isCustomMethod(method) && !isBaseClassMethod(method);
}
This is a qoute of Oliver Gierke:
This is by design. Custom repository methods are no query methods as they can effectively implement any behavior. Thus, it's currently impossible for us to decide about the HTTP method to expose the method under. POST would be the safest option but that's not in line with the generic query methods (which receive GET).
For more details see this issue: https://jira.spring.io/browse/DATAREST-206
Another simple method is using Python Server in Ubuntu.
Generate server.xml with the following command in terminal:
openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
Note: Assuming you have openssl installed.
Save below code in a file named simple-https-server.py
in any directory you want to run the server.
import BaseHTTPServer, SimpleHTTPServer
import ssl
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()
Run the server from terminal:
python simple-https-server.py
Visit the page at:
https://localhost:4443
Extra notes::
You can change the port in simple-https-server.py
file in line
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
You can change localhost
to your IP in the same line above:
httpd = BaseHTTPServer.HTTPServer(('10.7.1.3', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
and access the page on any device your network connected. This is very handy in cases like "you have to test HTML5 GeoLocation API in a mobile, and Chrome restricts the API in secure connections only".
Gist: https://gist.github.com/dergachev/7028596
http://www.piware.de/2011/01/creating-an-https-server-in-python/
Might not help you right now, but JDK 7 is intended to have glob and regex file name matching as part of "More NIO Features".
Here's a quick local task to permanently set key/values on /etc/environment
(which is system-wide, all users):
- name: populate /etc/environment
lineinfile:
dest: "/etc/environment"
state: present
regexp: "^{{ item.key }}="
line: "{{ item.key }}={{ item.value}}"
with_items: "{{ os_environment }}"
and the vars for it:
os_environment:
- key: DJANGO_SETTINGS_MODULE
value : websec.prod_settings
- key: DJANGO_SUPER_USER
value : admin
and, yes, if you ssh out and back in, env
shows the new environment variables.
df_buy['BUY'] = df_buy['BUY'].astype('float')
df_buy['BUY'] = ['€ {:,.2f}'.format(i) for i in list(df_buy['BUY'])]
One way is to create a handler function. Define the handler early on, and put the handler below all the methods you need to call.
Then when you invoke the handler method to call your functions, they will always be available.
The handler could take an argument nameOfMethodToCall
. Then uses a bunch of if statements to call the right method.
This would solve your issue.
def foo():
print("foo")
#take input
nextAction=input('What would you like to do next?:')
return nextAction
def bar():
print("bar")
nextAction=input('What would you like to do next?:')
return nextAction
def handler(action):
if(action=="foo"):
nextAction = foo()
elif(action=="bar"):
nextAction = bar()
else:
print("You entered invalid input, defaulting to bar")
nextAction = "bar"
return nextAction
nextAction=input('What would you like to do next?:')
while 1:
nextAction = handler(nextAction)
Simple! The folder named ..
is the parent folder, so you can make the path to the file you need as such
var foobar = require('../config/dev/foobar.json');
If you needed to go up two levels, you would write ../../
etc
Some more details about this in this SO answer and it's comments
Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:
for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )
Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:
wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath
Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:
for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )
The default behaviour for error_log() is to output to the Apache error log. If this isn't happening check your php.ini settings for the error_log directive. Leave it unset to use the Apache log file for the current vhost.
You can use the monitoring program glances with its GPU monitoring plug-in:
sudo apt-get install -y python-pip; sudo pip install glances[gpu]
sudo glances
It also monitors the CPU, disk IO, disk space, network, and a few other things:
Yes, it should be overridden. If you think you need to override equals()
, then you need to override hashCode()
and vice versa. The general contract of hashCode() is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
If the value assigned to a static final boolean
field is known at compile-time, it is a constant. Fields of primitive or
String
type can be compile-time constants. A constant will be inlined in any code that references the field. Since the field is not actually read at runtime, changing it then will have no effect.
The Java language specification says this:
If a field is a constant variable (§4.12.4), then deleting the keyword final or changing its value will not break compatibility with pre-existing binaries by causing them not to run, but they will not see any new value for the usage of the field unless they are recompiled. This is true even if the usage itself is not a compile-time constant expression (§15.28)
Here's an example:
class Flag {
static final boolean FLAG = true;
}
class Checker {
public static void main(String... argv) {
System.out.println(Flag.FLAG);
}
}
If you decompile Checker
, you'll see that instead of referencing Flag.FLAG
, the code simply pushes a value of 1 (true
) onto the stack (instruction #3).
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: iconst_1
4: invokevirtual #3; //Method java/io/PrintStream.println:(Z)V
7: return
You might want to also consider making use of Cygwin, it has mysql python libraries in the repository.
You can join to the same table on the fields that would be duplicated and then anti-join on the id field. Select the id field from the first table alias (tn1) and then use the array_agg function on the id field of the second table alias. Finally, for the array_agg function to work properly, you will group the results by the tn1.id field. This will produce a result set that contains the the id of a record and an array of all the id's that fit the join conditions.
select tn1.id,
array_agg(tn2.id) as duplicate_entries,
from table_name tn1 join table_name tn2 on
tn1.year = tn2.year
and tn1.sid = tn2.sid
and tn1.user_id = tn2.user_id
and tn1.cid = tn2.cid
and tn1.id <> tn2.id
group by tn1.id;
Obviously, id's that will be in the duplicate_entries array for one id, will also have their own entries in the result set. You will have to use this result set to decide which id you want to become the source of 'truth.' The one record that shouldn't get deleted. Maybe you could do something like this:
with dupe_set as (
select tn1.id,
array_agg(tn2.id) as duplicate_entries,
from table_name tn1 join table_name tn2 on
tn1.year = tn2.year
and tn1.sid = tn2.sid
and tn1.user_id = tn2.user_id
and tn1.cid = tn2.cid
and tn1.id <> tn2.id
group by tn1.id
order by tn1.id asc)
select ds.id from dupe_set ds where not exists
(select de from unnest(ds.duplicate_entries) as de where de < ds.id)
Selects the lowest number ID's that have duplicates (assuming the ID is increasing int PK). These would be the ID's that you would keep around.
Make sure the scp command is available on both sides - both on the client and on the server.
BOTH Server and Client, otherwise you will encounter this kind of (weird)error message on your client: scp: command not found
or something similar even though though you have it all configured locally.
Keystore only has one password. You can change it using keytool:
keytool -storepasswd -keystore my.keystore
To change the key's password:
keytool -keypasswd -alias <key_name> -keystore my.keystore
The cowplot
package gives you a nice way to do this, in a manner that suits publication.
x <- rnorm(100)
eps <- rnorm(100,0,.2)
A = qplot(x,3*x+eps, geom = c("point", "smooth"))+theme_gray()
B = qplot(x,2*x+eps, geom = c("point", "smooth"))+theme_gray()
cowplot::plot_grid(A, B, labels = c("A", "B"), align = "v")
In addtion to Sinan Ünür comprehensive listing of string comparison operators, Perl 5.10 adds the smart match operator.
The smart match operator compares two items based on their type. See the chart below for the 5.10 behavior (I believe this behavior is changing slightly in 5.10.1):
perldoc perlsyn
"Smart matching in detail":The behaviour of a smart match depends on what type of thing its arguments are. It is always commutative, i.e.
$a ~~ $b
behaves the same as$b ~~ $a
. The behaviour is determined by the following table: the first row that applies, in either order, determines the match behaviour.
$a $b Type of Match Implied Matching Code ====== ===== ===================== ============= (overloading trumps everything) Code[+] Code[+] referential equality $a == $b Any Code[+] scalar sub truth $b->($a) Hash Hash hash keys identical [sort keys %$a]~~[sort keys %$b] Hash Array hash slice existence grep {exists $a->{$_}} @$b Hash Regex hash key grep grep /$b/, keys %$a Hash Any hash entry existence exists $a->{$b} Array Array arrays are identical[*] Array Regex array grep grep /$b/, @$a Array Num array contains number grep $_ == $b, @$a Array Any array contains string grep $_ eq $b, @$a Any undef undefined !defined $a Any Regex pattern match $a =~ /$b/ Code() Code() results are equal $a->() eq $b->() Any Code() simple closure truth $b->() # ignoring $a Num numish[!] numeric equality $a == $b Any Str string equality $a eq $b Any Num numeric equality $a == $b Any Any string equality $a eq $b + - this must be a code reference whose prototype (if present) is not "" (subs with a "" prototype are dealt with by the 'Code()' entry lower down) * - that is, each element matches the element of same index in the other array. If a circular reference is found, we fall back to referential equality. ! - either a real number, or a string that looks like a numberThe "matching code" doesn't represent the real matching code, of course: it's just there to explain the intended meaning. Unlike grep, the smart match operator will short-circuit whenever it can.
Custom matching via overloading You can change the way that an object is matched by overloading the
~~
operator. This trumps the usual smart match semantics. Seeoverload
.
You can provide a new testContext.xml in which the @Autowired
bean you define is of the type you need for your test.
Sounds like you need to change the path to your java
executable to match the newest version.
Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.
Do the following (see in photo)
right-click and choose "Add New Launch Image"
del array[0]
where 0
is the index of the object in the list (there is no array in python)
You can subclass UIButton
and add @IBInspectable
variables to it so you can configure the custom button parameters via the StoryBoard "Attribute Inspector". Below I write down that code.
@IBDesignable
class BHButton: UIButton {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable lazy var isRoundRectButton : Bool = false
@IBInspectable public var cornerRadius : CGFloat = 0.0 {
didSet{
setUpView()
}
}
@IBInspectable public var borderColor : UIColor = UIColor.clear {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable public var borderWidth : CGFloat = 0.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
// MARK: Awake From Nib
override func awakeFromNib() {
super.awakeFromNib()
setUpView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setUpView()
}
func setUpView() {
if isRoundRectButton {
self.layer.cornerRadius = self.bounds.height/2;
self.clipsToBounds = true
}
else{
self.layer.cornerRadius = self.cornerRadius;
self.clipsToBounds = true
}
}
}
Yes:
#include <iostream>
#include <functional>
struct null_ref_t {
template <typename T>
operator T&() {
union TypeSafetyBreaker {
T *ptr;
// see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
std::reference_wrapper<T> ref;
};
TypeSafetyBreaker ptr = {.ptr = nullptr};
// unwrap the reference
return ptr.ref.get();
}
};
null_ref_t nullref;
int main() {
int &a = nullref;
// Segmentation fault
a = 4;
return 0;
}
By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”
It is generally best to explicitly specify essential attributes such as type=text
instead of defaulting them. The reason is that there is no simple reliable way to refer to the input
elements with defaulted type
attribute.
First you compile the regex, then you have to use it with match
, find
, or some other method to actually run it against some input.
import os
import re
import shutil
def test():
os.chdir("C:/Users/David/Desktop/Test/MyFiles")
files = os.listdir(".")
os.mkdir("C:/Users/David/Desktop/Test/MyFiles2")
pattern = re.compile(regex_txt, re.IGNORECASE)
for x in (files):
with open((x), 'r') as input_file:
for line in input_file:
if pattern.search(line):
shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")
break
I just simply place select statements in key areas of the stored procedure to check on current status of data sets, and then comment them out (--select...) or remove them before production.
Handy way: Using Browser Printing/Preview
Supposing data is a char*. Working example using std::hex:
for(int i=0; i<data_length; ++i)
std::cout << std::hex << (int)data[i];
Or if you want to keep it all in a string:
std::stringstream ss;
for(int i=0; i<data_length; ++i)
ss << std::hex << (int)data[i];
std::string mystr = ss.str();
I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:
import pandas as pd
pd.set_option('display.max_columns', <number of columns>)
You can do the same for the rows too:
pd.set_option('display.max_rows', <number of rows>)
This saves importing IPython, and there are more options in the pandas.set_option documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html
To chip in a pandas-based solution I use:
import pandas as pd
import numpy as np
def random_date(start, end, position=None):
start, end = pd.Timestamp(start), pd.Timestamp(end)
delta = (end - start).total_seconds()
if position is None:
offset = np.random.uniform(0., delta)
else:
offset = position * delta
offset = pd.offsets.Second(offset)
t = start + offset
return t
I like it, because of the nice pd.Timestamp
features that allow me to throw different stuff and formats at it. Consider the following few examples...
Your signature.
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM", position=0.34)
Timestamp('2008-05-04 21:06:48', tz=None)
Random position.
>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM")
Timestamp('2008-10-21 05:30:10', tz=None)
Different format.
>>> random_date('2008-01-01 13:30', '2009-01-01 4:50')
Timestamp('2008-11-18 17:20:19', tz=None)
Passing pandas/datetime objects directly.
>>> random_date(pd.datetime.now(), pd.datetime.now() + pd.offsets.Hour(3))
Timestamp('2014-03-06 14:51:16.035965', tz=None)
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
this work for me
<meta name="author" content="Alan van Buuren @("@Alan_van_Buuren")">
Or yoy can use: @@Alan_van_Buuren
:D
Get fields where a timestamp is greater than date in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > to_date('05 Dec 2000', 'DD Mon YYYY');
Subtract minutes from timestamp in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > current_timestamp - interval '5 minutes'
Subtract hours from timestamp in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > current_timestamp - interval '5 hours'
You can easily draw simple svg
s onto a canvas by:
Note: The only drawback of the method is that it cannot draw images embedded in the svg
. (see demo)
(Note that the embedded image is only visible in the svg
)
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
<rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
<image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
_x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
Rob's solution is the right one--use @require
with the jQuery library and be sure to reinstall your script so the directive gets processed.
One thing I think is worth adding is that you can use jQuery normally once you have included it in your script, except for AJAX methods. By default jQuery looks for XMLHttpRequest, which doesn't exist in the Greasemonkey context. I wrote about a workaround where you create a wrapper for GM_xmlhttpRequest (the Greasemonkey version of XHR) and use jQuery's ajaxSetup()
to specify your wrapped version as the default. Once you do this, you can use $.get
and $.post
as usual.
You may also have problems with jQuery's $.getJSON
because it loads JSONP using <script>
tags. This leads to errors because jQuery defines the callback function in the scope of the Greasemonkey window, and the loaded scripts looks for the callback in the scope of the main window. Your best bet is to use $.get
instead and parse the result with JSON.parse()
.
Actually something like
function scrollTo(prop){
$('html,body').animate({scrollTop: $("#"+prop).offset().top +
parseInt($("#"+prop).css('padding-top'),10) },'slow');
}
will work nicely and support padding. You can also support margins easily - for completion see below
function scrollTo(prop){
$('html,body').animate({scrollTop: $("#"+prop).offset().top
+ parseInt($("#"+prop).css('padding-top'),10)
+ parseInt($("#"+prop).css('margin-top'),10) +},'slow');
}
IF EXISTS (SELECT NAME FROM SYS.OBJECTS WHERE object_id = OBJECT_ID(N'Scores') AND TYPE in (N'U'))
DROP TABLE Scores
GO
Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.
class Child extends React.Component {
constructor(){}
dismiss() {
this.props.unmountMe();
}
render(){
// code
}
}
class Parent ...
constructor(){
super(props)
this.state = {renderChild: true};
this.handleChildUnmount = this.handleChildUnmount.bind(this);
}
handleChildUnmount(){
this.setState({renderChild: false});
}
render(){
// code
{this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
}
}
this is a very simple example. but you can see a rough way to pass through to the parent an action
That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render
I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.
Few things to note first. this is in typescript so you would need to remove the type declarations :)
I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.
The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol()
. This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.
import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';
interface IDispatchType {
type: string;
payload?: any;
remove?: Symbol;
}
export const notifySuccess = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const notifyFailure = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const clearNotification = (notifyId: Symbol) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
};
};
const defaultState = {
userNotifications: []
};
export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
switch (action.type) {
case USER_SYSTEM_NOTIFICATION:
const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
if (_.has(action, 'remove')) {
const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
if (key) {
// mutate list and remove the specified item
list.splice(key, 1);
}
} else {
list.push(action.payload);
}
return _.assign({}, state, { userNotifications: list });
}
return state;
};
in the base render for your application you would render the notifications
render() {
const { systemNotifications } = this.props;
return (
<div>
<AppHeader />
<div className="user-notify-wrap">
{ _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
: null
}
</div>
<div className="content">
{this.props.children}
</div>
</div>
);
}
user notification class
/*
Simple notification class.
Usage:
<SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
these two functions are actions and should be props when the component is connect()ed
call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
this.props.notifySuccess('it Works!!!', 2);
this.props.notifySuccess(<SomeComponentHere />, 15);
this.props.notifyFailure(<div>You dun goofed</div>);
*/
interface IUserNotifyProps {
data: any;
clearNotification(notifyID: symbol): any;
}
export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
public notifyRef = null;
private timeout = null;
componentDidMount() {
const duration: number = _.get(this.props, 'data.duration', '');
this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';
// fallback incase the animation event doesn't fire
const timeoutDuration = (duration * 1000) + 500;
this.timeout = setTimeout(() => {
this.notifyRef.classList.add('hidden');
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}, timeoutDuration);
TransitionEvents.addEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
componentWillUnmount() {
clearTimeout(this.timeout);
TransitionEvents.removeEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
onAmimationComplete = (e) => {
if (_.get(e, 'animationName') === 'fadeInAndOut') {
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
}
handleCloseClick = (e) => {
e.preventDefault();
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
assignNotifyRef = target => this.notifyRef = target;
render() {
const {data, clearNotification} = this.props;
return (
<div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
{!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
<div className="close-message" onClick={this.handleCloseClick}>+</div>
</div>
);
}
}
That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.
In Java I used to work around this by using a map and implementing my own take on Key-Value coding.
http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html
It's worth mentioning that you can specify argument ranges with this syntax.
function example() {
echo "line1 ${@:1:1}"; #First argument
echo "line2 ${@:2:1}"; #Second argument
echo "line3 ${@:3}"; #Third argument onwards
}
I hadn't seen it mentioned.
Take a look at my solution here, it should work. The idea is to remove all the unwanted symbols from the words, then separate those words and store them in some other variable, i was using ArrayList. By adjusting the "excludedSymbols" variable you can add more symbols which you would like to be excluded from the words.
public static void countWords () {
String textFileLocation ="c:\\yourFileLocation";
String readWords ="";
ArrayList<String> extractOnlyWordsFromTextFile = new ArrayList<>();
// excludedSymbols can be extended to whatever you want to exclude from the file
String[] excludedSymbols = {" ", "," , "." , "/" , ":" , ";" , "<" , ">", "\n"};
String readByteCharByChar = "";
boolean testIfWord = false;
try {
InputStream inputStream = new FileInputStream(textFileLocation);
byte byte1 = (byte) inputStream.read();
while (byte1 != -1) {
readByteCharByChar +=String.valueOf((char)byte1);
for(int i=0;i<excludedSymbols.length;i++) {
if(readByteCharByChar.equals(excludedSymbols[i])) {
if(!readWords.equals("")) {
extractOnlyWordsFromTextFile.add(readWords);
}
readWords ="";
testIfWord = true;
break;
}
}
if(!testIfWord) {
readWords+=(char)byte1;
}
readByteCharByChar = "";
testIfWord = false;
byte1 = (byte)inputStream.read();
if(byte1 == -1 && !readWords.equals("")) {
extractOnlyWordsFromTextFile.add(readWords);
}
}
inputStream.close();
System.out.println(extractOnlyWordsFromTextFile);
System.out.println("The number of words in the choosen text file are: " + extractOnlyWordsFromTextFile.size());
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
UPDATE: As of Bootstrap 3.0, the input-*
classes described below for setting the width of input elements were removed. Instead use the col-*
classes to set the width of input elements. Examples are provided in the documentation.
In Bootstrap 2.3, you'd use the input classes for setting the width.
<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>?
<textarea class="input-block-level"></textarea>?
Do a find for "Control sizing" for examples in the documentation.
But for height I think you'd still use the rows attribute.
You don't have to use dynamic SQL
update
R
set
Assoc_Item_1 = CASE WHEN @curr_row = 1 THEN foo.relsku ELSE Assoc_Item_1 END,
Assoc_Item_2 = CASE WHEN @curr_row = 2 THEN foo.relsku ELSE Assoc_Item_2 END,
Assoc_Item_3 = CASE WHEN @curr_row = 3 THEN foo.relsku ELSE Assoc_Item_3 END,
Assoc_Item_4 = CASE WHEN @curr_row = 4 THEN foo.relsku ELSE Assoc_Item_4 END,
Assoc_Item_5 = CASE WHEN @curr_row = 5 THEN foo.relsku ELSE Assoc_Item_5 END,
...
from
(Select relsku From @TSku Where tid = @curr_row1) foo
CROSS JOIN
@RelPro R
Where
R.RowID = @curr_row;
I was getting a same error. I found out the solution that I had created the primary key in the main table as BIGINT UNSIGNED and was declaring it as a foreign key in the second table as only BIGINT.
When I declared my foreign key as BIGINT UNSIGED in second table, everything worked fine, even didn't need any indexes to be created.
So it was a datatype mismatch between the primary key and the foreign key :)
Navigate via shell inside of your project folder and run following command:
mvn -U clean install
Usually this should already solve your problem.
If you see a message like this:
Could not resolve dependencies for project :war:0.0.1-SNAPSHOT: Failed to collect dependencies at com.sun.jersey:jersey-server:jar:1.9
Then execute:
export MAVEN_OPTS=-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2
followed by:
mvn -U clean install
again to finally update your dependencies.
Afterwards perform clean maven build:
maven clean install
benefit.indexOf(map4)
It either returns an index or -1 if the items is not found.
I strongly recommend wrapping the map in some object and use generics if possible.
This is more precise implementation:
def ReLU(x):
return abs(x) * (x > 0)
dependencies {
compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
def (g, m) = i.tokenize( ':' )
dep.exclude group: g , module: m
}
}
}
You cannot use items
instead iteritems
in all places in Python. For example, the following code:
class C:
def __init__(self, a):
self.a = a
def __iter__(self):
return self.a.iteritems()
>>> c = C(dict(a=1, b=2, c=3))
>>> [v for v in c]
[('a', 1), ('c', 3), ('b', 2)]
will break if you use items
:
class D:
def __init__(self, a):
self.a = a
def __iter__(self):
return self.a.items()
>>> d = D(dict(a=1, b=2, c=3))
>>> [v for v in d]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __iter__ returned non-iterator of type 'list'
The same is true for viewitems, which is available in Python 3.
Also, since items returns a copy of the dictionary’s list of (key, value)
pairs, it is less efficient, unless you want to create a copy anyway.
In Python 2, it is best to use iteritems
for iteration. The 2to3
tool can replace it with items
if you ever decide to upgrade to Python 3.
Eclipse has no impact on Mac OS beyond it directory, so there is no problem uninstalling.
I think that What you are facing is the result of Eclipse switching the plugin distribution system recently. There are now two redundant and not very compatible means of installing plugins. It's a complete mess. You may be better off (if possible) installing a more recent version of Eclipse (maybe even the 3.5 milestones) as they seem to be more stable in that regard.
You can try this if you want date time string:
use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"
If you want timestamp, you can try:
use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328
try changing this part,
<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter
for this
<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up for newsletter
you might wanna try this:
$conda install -c conda-forge tensorflow
Instead of trying to create an abstract base class, consider using a protocol (similar to a Java interface). This allows you to define a set of methods, and then accept all objects that conform to the protocol and implement the methods. For example, I can define an Operation protocol, and then have a function like this:
- (void)performOperation:(id<Operation>)op
{
// do something with operation
}
Where op can be any object implementing the Operation protocol.
If you need your abstract base class to do more than simply define methods, you can create a regular Objective-C class and prevent it from being instantiated. Just override the - (id)init function and make it return nil or assert(false). It's not a very clean solution, but since Objective-C is fully dynamic, there's really no direct equivalent to an abstract base class.
Since the ASCII codes for '0','1','2'.... are placed from 48 to 57 they are essentially continuous. Now the arithmetic operations require conversion of char datatype to int datatype.Hence what you are basically doing is: 53-48 and hence it stores the value 5 with which you can do any integer operations.Note that while converting back from int to char the compiler gives no error but just performs a modulo 256 operation to put the value in its acceptable range
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
All of the above answer are only partially correct. Specially in region like Australia, they always include pole and calculate a very large rectangle even for 10kms.
Specially the algorithm by Jan Philip Matuschek at http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#UsingIndex included a very large rectangle from (-37, -90, -180, 180) for almost every point in Australia. This hits a large users in database and distance have to be calculated for all of the users in almost half the country.
I found that the Drupal API Earth Algorithm by Rochester Institute of Technology works better around pole as well as elsewhere and is much easier to implement.
https://www.rit.edu/drupal/api/drupal/sites%21all%21modules%21location%21earth.inc/7.54
Use earth_latitude_range
and earth_longitude_range
from the above algorithm for calculating bounding rectangle
And use the distance calculation formula documented by google maps to calculate distance
To search by kilometers instead of miles, replace 3959 with 6371. For (Lat, Lng) = (37, -122) and a Markers table with columns lat and lng, the formula is:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
Read my detailed answer at https://stackoverflow.com/a/45950426/5076414
You can use this code:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
public static int generatRandomPositiveNegitiveValue(int max , int min) {
//Random rand = new Random();
int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
return ii;
}
If you have Java 5, use char c = ...; String s = String.format ("\\u%04x", (int)c);
If your source isn't a Unicode character (char
) but a String, you must use charAt(index)
to get the Unicode character at position index
.
Don't use codePointAt(index)
because that will return 24bit values (full Unicode) which can't be represented with just 4 hex digits (it needs 6). See the docs for an explanation.
[EDIT] To make it clear: This answer doesn't use Unicode but the method which Java uses to represent Unicode characters (i.e. surrogate pairs) since char is 16bit and Unicode is 24bit. The question should be: "How can I convert char
to a 4-digit hex number", since it's not (really) about Unicode.
I really don't like the fact that, because of the "promise" way of doing things, the consumer of the service that uses $http has to "know" about how to unpack the response.
I just want to call something and get the data out, similar to the old $scope.items = Data.getData();
way, which is now deprecated.
I tried for a while and didn't come up with a perfect solution, but here's my best shot (Plunker). It may be useful to someone.
app.factory('myService', function($http) {
var _data; // cache data rather than promise
var myService = {};
myService.getData = function(obj) {
if(!_data) {
$http.get('test.json').then(function(result){
_data = result.data;
console.log(_data); // prove that it executes once
angular.extend(obj, _data);
});
} else {
angular.extend(obj, _data);
}
};
return myService;
});
Then controller:
app.controller('MainCtrl', function( myService,$scope) {
$scope.clearData = function() {
$scope.data = Object.create(null);
};
$scope.getData = function() {
$scope.clearData(); // also important: need to prepare input to getData as an object
myService.getData($scope.data); // **important bit** pass in object you want to augment
};
});
Flaws I can already spot are
getData
can only accept the obj
parameter in the form of an object (although it could also accept an array), which won't be a problem for many applications, but it's a sore limitation$scope.data
with = {}
to make it an object (essentially what $scope.clearData()
does above), or = []
for an array, or it won't work (we're already having to assume something about what data is coming). I tried to do this preparation step IN getData
, but no luck.Nevertheless, it provides a pattern which removes controller "promise unwrap" boilerplate, and might be useful in cases when you want to use certain data obtained from $http in more than one place while keeping it DRY.
Once I had this problem after renaming a file. I renamed the file from within Xcode, but afterwards Xcode couldn't find the function in the file. Even a clean rebuild didn't fix the problem, but closing and then re-opening the project got the build to work.
Alternatively:
var exception = err as Web2PDFException;
if ( excecption != null )
{
Web2PDFException wex = exception;
....
}
I know this is a little late, but if someone else comes across this looking, you can now use public_path(); in Laravel 4, it has been added to the helper.php file in the support folder see here.
Both rebase
(and cherry-pick
) and merge
have their advantages and disadvantages. I argue for merge
here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase
is preferred.)
merge
is preferred over cherry-pick
and rebase
for a couple of reasons.
merge
workflow fairly easily. rebase
tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.Even with a merge-heavy workflow rebase
and cherry-pick
are still useful for particular cases:
merge
is cluttered history. rebase
prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase
code that you have shared with other repositories. Once a commit is push
ed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.cherry-pick
is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.
The method suggested by @roe and @MohitNanda work, but if the right div is set as float:right;
, then it must come first in the HTML source. This breaks the left-to-right read order, which could be confusing if the page is displayed with styles turned off. If that's the case, it might be better to use a wrapper div and absolute positioning:
<div id="wrap" style="position:relative;">
<div id="left" style="margin-right:201px;border:1px solid red;">left</div>
<div id="right" style="position:absolute;width:200px;right:0;top:0;border:1px solid blue;">right</div>
</div>
Demonstrated:
left rightEdit: Hmm, interesting. The preview window shows the correctly formatted divs, but the rendered post item does not. Sorry then, you'll have to try it for yourself.
$(".first").addClass("second");
If you'd like to add it on an event, you can do so easily as well. An example with the click event:
$(".first").click(function() {
$(this).addClass("second");
});
I had this issue with WebStorm recently (February/2018) and none of the (then) previous solutions worked for me. After spending some hours on troubleshooting and researching, I installed the 2018 EAP version and now it works!
A new issue reported on December/2017 on IntelliJ Idea > VCS/Git subsystem which was fixed in build 181.2445 (or any latest build after 31/Jan/2018).
See also the post Update-ssh-key-to-use-new-passphrase
If you want 08:30 ( HH:MM) format then try this,
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, RIGHT('0' + CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60),2) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
as TotalHours from times Order By EmplID, DateVisited
You can use the with
template tag.
{% with name="World" %}
<html>
<div>Hello {{name}}!</div>
</html>
{% endwith %}
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.
I use ruamel.yaml. Details & debate here.
from ruamel import yaml
with open(filename, 'r') as fp:
read_data = yaml.load(fp)
Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use
from ruamel import yaml
instead of
import yaml
and it will fix most of your problems.
EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.
If you want to concatenate your "text" in a list:
df.groupby(['name', 'month'], as_index = False).agg({'text': list})
You need to store all of the extra rows in the files in your dictionary, not just one of them:
dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}
Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:
w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])
Steps for creating unsigned APK
Steps for creating unsigned APK_x000D_
_x000D_
• Click the dropdown menu in the toolbar at the top_x000D_
• Select "Edit Configurations"_x000D_
• Click the "+"_x000D_
• Select "Gradle"_x000D_
• Choose your module as a Gradle project_x000D_
• In Tasks: enter assemble_x000D_
• Press Run_x000D_
• Your unsigned APK is now located in - ProjectName\app\build\outputs\apk_x000D_
_x000D_
Note : Technically, what you want is an APK signed with a debug key. An APK that is actually unsigned will be refused by the device. So, Unsigned APK will give error if you install in device.
_x000D_
Note : Technically, what you want is an APK signed with a debug key. An APK that is actually unsigned will be refused by the device. So, Unsigned APK will give error if you install in device.
Do git help gitignore
You will get the help page with following line:
A line starting with # serves as a comment.
If error comes for ".settings/language.settings.xml" or any such file you don't need to git.
Now if Staged file list empty, and Unstaged file list all files are marked as Ignored. You can pull. Otherwise, follow other answers.
All answers in one method
static boolean checkEmulator()
{
try
{
String buildDetails = (Build.FINGERPRINT + Build.DEVICE + Build.MODEL + Build.BRAND + Build.PRODUCT + Build.MANUFACTURER + Build.HARDWARE).toLowerCase();
if (buildDetails.contains("generic")
|| buildDetails.contains("unknown")
|| buildDetails.contains("emulator")
|| buildDetails.contains("sdk")
|| buildDetails.contains("genymotion")
|| buildDetails.contains("x86") // this includes vbox86
|| buildDetails.contains("goldfish")
|| buildDetails.contains("test-keys"))
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
try
{
TelephonyManager tm = (TelephonyManager) App.context.getSystemService(Context.TELEPHONY_SERVICE);
String non = tm.getNetworkOperatorName().toLowerCase();
if (non.equals("android"))
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
try
{
if (new File ("/init.goldfish.rc").exists())
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
return false;
}
Question 1:
vectorOfGamers.push_back(Player)
This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:
vectorOfGamers.push_back(Player(name, id))
//^^assuming name and id are parameters to the vector, call Player constructor
//^^In other words, push `instance` of Player class into vector
Question 2:
These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?
Yes you can. You can create a vector of pointers that points to the base class Gamer
.
A good choice is to use a vector of smart_pointer
, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer
, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?
A few of the options are deprecated as of today. So watch out for those.
If you try <input onkeypress="blockSpecialCharacters(event)" />
, an IDE like WebStorm
will slash out event and tell you:
Deprecated symbol used, consults docs for better alternative
Then when you get to the JavaScript, console.log(e.keyCode)
will also give keyCode and say:
Deprecated symbol used, consults docs for better alternative
Anyways I did it using jQuery.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<input id="theInput" />
<script>
function blockSpecialCharacters(e) {
let key = e.key;
let keyCharCode = key.charCodeAt(0);
// 0-9
if(keyCharCode >= 48 && keyCharCode <= 57) {
return key;
}
// A-Z
if(keyCharCode >= 65 && keyCharCode <= 90) {
return key;
}
// a-z
if(keyCharCode >= 97 && keyCharCode <= 122) {
return key;
}
return false;
}
$('#theInput').keypress(function(e) {
blockSpecialCharacters(e);
});
</script>
You can do it with a simple css/jq workaround: Create a fake button which triggers the browse button that is hidden.
HTML
<input type="file"/>
<button>Open</button>
CSS
input { display: none }
jQuery
$( 'button' ).click( function(e) {
e.preventDefault(); // prevents submitting
$( 'input' ).trigger( 'click' );
} );
You can check SelectedIndex or SelectedValue or SelectedItem property in the SelectionChanged event of the Combobox control.
For extracting Text from PDF use below code
import PyPDF2
pdfFileObj = open('mypdf.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print(pdfReader.numPages)
pageObj = pdfReader.getPage(0)
a = pageObj.extractText()
print(a)
Everything has many properties and behaviours so take whatever object you want TV, Mobile, Car, Human or anything.
ABSTRACT everything you need and ENCAPSULATE everything you don't need ;)
Maybe the author of that unnamed book has read that a > 0
runs faster than a >= 1
and thinks that is true universally.
But it is because a 0
is involved (because CMP
can, depending on the architecture, replaced e.g. with OR
) and not because of the <
.
To complete Sunit's answer, you can use a selector, not to the text string but to the textColorHint. You must add this attribute on your editText:
android:textColorHint="@color/text_hint_selector"
And your text_hint_selector should be:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="@android:color/transparent" />
<item android:color="@color/hint_color" />
</selector>
Try to use the latest com.fasterxml.jackson.core/jackson-databind
.
I upgraded it to 2.9.4
and it works now.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
The commands from WEFX worked for me after I enabled the parent features RemoteServerAdministrationTools, RemoteServerAdministrationTools-Roles, and RemoteServerAdministrationTools-Roles-AD
Here's a quick sample:
//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = strCommand;
//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = strCommandParameters;
pProcess.StartInfo.UseShellExecute = false;
//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;
//Optional
pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;
//Start the process
pProcess.Start();
//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();
//Wait for process to finish
pProcess.WaitForExit();
Check your dependencies for uses of +
in the versions. Some dependency could be using com.android.support:appcompat-v7:+
. This leads to problems when a new version gets released and could break features.
The solution for this would be to either use com.android.support:appcompat-v7:{compileSdkVersion}.+
or don't use +
at all and use the full version (ex. com.android.support:appcompat-v7:26.1.0
).
If you cannot see a line in your build.gradle files for this, run in android studio terminal to give an overview of what each dependency uses
gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath
(include androidtest dependencies)
OR
gradlew -q dependencies app:dependencies --configuration debugCompileClasspath
(regular dependencies for debug)
which results in something that looks close to this
------------------------------------------------------------
Project :app
------------------------------------------------------------
debugCompileClasspath - Resolved configuration for compilation for variant: debug
...
+--- com.android.support:appcompat-v7:26.1.0
| +--- com.android.support:support-annotations:26.1.0
| +--- com.android.support:support-v4:26.1.0 (*)
| +--- com.android.support:support-vector-drawable:26.1.0
| | +--- com.android.support:support-annotations:26.1.0
| | \--- com.android.support:support-compat:26.1.0 (*)
| \--- com.android.support:animated-vector-drawable:26.1.0
| +--- com.android.support:support-vector-drawable:26.1.0 (*)
| \--- com.android.support:support-core-ui:26.1.0 (*)
+--- com.android.support:design:26.1.0
| +--- com.android.support:support-v4:26.1.0 (*)
| +--- com.android.support:appcompat-v7:26.1.0 (*)
| +--- com.android.support:recyclerview-v7:26.1.0
| | +--- com.android.support:support-annotations:26.1.0
| | +--- com.android.support:support-compat:26.1.0 (*)
| | \--- com.android.support:support-core-ui:26.1.0 (*)
| \--- com.android.support:transition:26.1.0
| +--- com.android.support:support-annotations:26.1.0
| \--- com.android.support:support-v4:26.1.0 (*)
+--- com.android.support.constraint:constraint-layout:1.0.2
| \--- com.android.support.constraint:constraint-layout-solver:1.0.2
(*) - dependencies omitted (listed previously)
If you have no control over changing the version, Try forcing it to use a specific version.
configurations.all {
resolutionStrategy {
force "com.android.support:appcompat-v7:26.1.0"
force "com.android.support:support-v4:26.1.0"
}
}
The force dependency may need to be different depending on what is being set to 28.0.0
<select name=protect_email size=1 style="background: #009966; color: #FFF;" onChange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">
<option value=0 style="background: #009966; color: #FFF;" selected>Protect my email</option>;
<option value=1 style="background: #FF0000; color: #FFF;">Show email on advert</option>;
</select>;
http://pro.org.uk/classified/Directory?act=book&category=120
Tested it in FF,Opera,Konqueror worked fine...
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
Try putting
Display:inline;
In the CSS.
It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.
It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.
Combining Günter Zöchbauer's answer with good-old vanilla-JS, here is a directive with two lines of logic that supports (123) 456-7890 format.
Reactive Forms: Plunk
import { Directive, Output, EventEmitter } from "@angular/core";
import { NgControl } from "@angular/forms";
@Directive({
selector: '[formControlName][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)'
}
})
export class PhoneMaskDirective {
@Output() rawChange:EventEmitter<string> = new EventEmitter<string>();
constructor(public model: NgControl) {}
onInputChange(value) {
var x = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
var y = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
this.model.valueAccessor.writeValue(y);
this.rawChange.emit(rawValue);
}
}
Template-driven Forms: Plunk
import { Directive } from "@angular/core";
import { NgControl } from "@angular/forms";
@Directive({
selector: '[ngModel][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)'
}
})
export class PhoneMaskDirective {
constructor(public model: NgControl) {}
onInputChange(value) {
var x = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
this.model.valueAccessor.writeValue(value);
}
}
From Federico Culloca's note:
Also you cannot use them inside tags
Means; you have to put the comment at the top or bottom of the file - all the places you really want to add comments are at least inside the top level layout tag
http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?
if(strpos( $a , 'some text' ) !== false)
You can disable sql_mode=only_full_group_by by some command you can try this by terminal or MySql IDE
mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Strange that the first button Enter goes always to the first button regardless is visible or not, e.g. using jquery show/hide()
. Adding attribute .attr('disabled', 'disabled')
prevent receiving Enter submit button completely. It's problem for example when adjusting Insert/Edit+Delete button visibility in record dialogs. I found less hackish and simple placing Edit in front of Insert
<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="insert">Insert</button>
<button type="submit" name="action" value="delete">Delete</button>
and use javascript code:
$("#formId button[type='submit'][name='action'][value!='insert']").hide().attr('disabled', 'disabled');
$("#formId button[type='submit'][name='action'][value='insert']").show().removeAttr('disabled');
Got the solution and it's working fine. Set the environment variables as:
CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59
(path where your Apache Tomcat is)JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25;
(path where your JDK is)JRE_Home=C:\Program Files\Java\jre1.8.0_25;
(path where your JRE is)CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib
i think you use this method to compress the bitmap
BitmapFactory.Option imageOpts = new BitmapFactory.Options ();
imageOpts.inSampleSize = 2; // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath, imageOpts), 96, 96, false);
The magic variables %
n contains the arguments used to invoke the file: %0
is the path to the bat-file itself, %1
is the first argument after, %2
is the second and so on.
Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d
is drive, ~p
is the path (without drive), ~n
is the file name. They can be combined so ~dp
is drive+path.
%~dp0
is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.
You can also get other kinds of meta info about the file: ~t
is the timestamp, ~z
is the size.
Look here for a reference for all command line commands. The tilde-magic codes are described under for.
Note that if you use LIKE
to determine if a string is a substring of another string, you must escape the pattern matching characters in your search string.
If your SQL dialect supports CHARINDEX
, it's a lot easier to use it instead:
SELECT * FROM MyTable
WHERE CHARINDEX('word1', Column1) > 0
AND CHARINDEX('word2', Column1) > 0
AND CHARINDEX('word3', Column1) > 0
Also, please keep in mind that this and the method in the accepted answer only cover substring matching rather than word matching. So, for example, the string 'word1word2word3'
would still match.
Use tidy
cat filename.xml | tidy -xml -iq
Redirecting viewing a file with cat to tidy specifying the file type of xml and to indent while quiet output will suppress error output. JSON also works with -json
.
Here is the way I got that:
@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {
/**
* This event is executed as late as conceivably possible to indicate that
* the application is ready to service requests.
*/
@Autowired
private MovieRepositoryImpl movieRepository;
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
seedData();
}
private void seedData() {
movieRepository.save(new Movie("Example"));
// ... add more code
}
}
Thanks to the author of this article:
http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
You can use a third-party importer
to customise @import
semantics.
node-sass-import-once, which works with node-sass (for Node.js) can inline import CSS files.
Example of direct usage:
var sass = require('node-sass');,
importOnce = require('node-sass-import-once');
sass.render({
file: "input.scss",
importer: importOnce,
importOnce: {
css: true,
}
});
Example grunt-sass config:
var importOnce = require("node-sass-import-once");
grunt.loadNpmTasks("grunt-sass");
grunt.initConfig({
sass: {
options: {
sourceMap: true,
importer: importOnce
},
dev: {
files: {
"dist/style.css": "scss/**/*.scss"
}
}
});
Note that node-sass-import-once cannot currently import Sass partials without an explicit leading underscore. For example with the file partials/_partial.scss
:
@import partials/_partial.scss
succeeds@import * partials/partial.scss
failsIn general, be aware that a custom importer could change any import semantics. Read the docs before you start using it.
In the recent go versions from 1.14 onwards, we have to do go mod vendor
before building or running, since by default go appends -mod=vendor
to the go commands.
So after doing go mod vendor
, if we try to build, we won't face this issue.
try running SHOW CREATE VIEW my_view_name
in the sql portion of phpmyadmin and you will have a better idea of what is inside the view
Use list.sort
instead:
list.sort((o1, o2) -> o1.getItem().getValue().compareTo(o2.getItem().getValue()));
and make it more succinct using Comparator.comparing
:
list.sort(Comparator.comparing(o -> o.getItem().getValue()));
After either of these, list
itself will be sorted.
Your issue is that
list.stream.sorted
returns the sorted data, it doesn't sort in place as you're expecting.
First shift the column:
df['gdp'] = df['gdp'].shift(-1)
Second remove the last row which contains an NaN Cell:
df = df[:-1]
Third reset the index:
df = df.reset_index(drop=True)
Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors
If you have installed x-pack to secure elasticseach, the request should contains the valid credential details.
curl -XGET -u "elastic:passwordForElasticUser" 'localhost:9200'
Infact, if the security enabled all the subsequent requests should follow the same pattern (inline credentials should be provided).
I would be careful when using Guava's ComparisonChain
because it creates an instance of it per element been compared so you would be looking at a creation of N x Log N
comparison chains just to compare if you are sorting, or N
instances if you are iterating and checking for equality.
I would instead create a static Comparator
using the newest Java 8 API if possible or Guava's Ordering
API which allows you to do that, here is an example with Java 8:
import java.util.Comparator;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;
private static final Comparator<Person> COMPARATOR = Comparator
.comparing(Person::getName, nullsLast(naturalOrder()))
.thenComparingInt(Person::getAge);
@Override
public int compareTo(@NotNull Person other) {
return COMPARATOR.compare(this, other);
}
Here is how to use the Guava's Ordering
API: https://github.com/google/guava/wiki/OrderingExplained
is it possible have a spinner that loads with nothing selected
Only if there is no data. If you have 1+ items in the SpinnerAdapter
, the Spinner
will always have a selection.
Spinners
are not designed to be command widgets. Users will not expect a selection in a Spinner
to start an activity. Please consider using something else, like a ListView
or GridView
, instead of a Spinner
.
EDIT
BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner
.
I believe this isn't going to work for you as you use C# and my solution includes a Java library, however maybe others will find it helpful.
For capturing custom screenshots you can use the Shutterbug library. The specific call for this purpose would be:
Shutterbug.shootElement(driver, element).save();
Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)
But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:
Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified
by POSIX.)
You can use the following to set the text from the code:
toggleButton.setText(textOff);
// Sets the text for when the button is first created.
toggleButton.setTextOff(textOff);
// Sets the text for when the button is not in the checked state.
toggleButton.setTextOn(textOn);
// Sets the text for when the button is in the checked state.
To set the text using xml, use the following:
android:textOff="The text for the button when it is not checked."
android:textOn="The text for the button when it is checked."
This information is from here
I see both some SQL Server specific and some MySQL specific solutions here, so you might want to clarify which database you need. Though if I had to guess I'd say SQL Server since this is trivial in MySQL.
I also see some solutions that won't work because they fail to take into account the possibility for duplicates, so be careful which ones you accept. Finally, I see a few that will work but that will make two complete scans of the table. You want to make sure the 2nd scan is only looking at 2 values.
SQL Server (pre-2012):
SELECT MIN([column]) AS [column]
FROM (
SELECT TOP 2 [column]
FROM [Table]
GROUP BY [column]
ORDER BY [column] DESC
) a
MySQL:
SELECT `column`
FROM `table`
GROUP BY `column`
ORDER BY `column` DESC
LIMIT 1,1
Update:
SQL Server 2012 now supports a much cleaner (and standard) OFFSET/FETCH syntax:
SELECT TOP 2 [column]
FROM [Table]
GROUP BY [column]
ORDER BY [column] DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;
From Java, using the new AdminZkClient
instead of the deprecated AdminUtils
:
public void reset() {
try (KafkaZkClient zkClient = KafkaZkClient.apply("localhost:2181", false, 200_000,
5000, 10, Time.SYSTEM, "metricGroup", "metricType")) {
for (Map.Entry<String, List<PartitionInfo>> entry : listTopics().entrySet()) {
deleteTopic(entry.getKey(), zkClient);
}
}
}
private void deleteTopic(String topic, KafkaZkClient zkClient) {
// skip Kafka internal topic
if (topic.startsWith("__")) {
return;
}
System.out.println("Resetting Topic: " + topic);
AdminZkClient adminZkClient = new AdminZkClient(zkClient);
adminZkClient.deleteTopic(topic);
// deletions are not instantaneous
boolean success = false;
int maxMs = 5_000;
while (maxMs > 0 && !success) {
try {
maxMs -= 100;
adminZkClient.createTopic(topic, 1, 1, new Properties(), null);
success = true;
} catch (TopicExistsException ignored) {
}
}
if (!success) {
Assert.fail("failed to create " + topic);
}
}
private Map<String, List<PartitionInfo>> listTopics() {
Properties props = new Properties();
props.put("bootstrap.servers", kafkaContainer.getBootstrapServers());
props.put("group.id", "test-container-consumer-group");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
Map<String, List<PartitionInfo>> topics = consumer.listTopics();
consumer.close();
return topics;
}
cp .env.example .env
if there is no .env file present.
php artisan key:generate
command works for me. It generates the encryption key
I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:
// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);
Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?
If there's no time-constraint, this is fairly simple and straight-forward:
def lcm(a,b,c):
for i in range(max(a,b,c), (a*b*c)+1, max(a,b,c)):
if i%a == 0 and i%b == 0 and i%c == 0:
return i
My issue was that I called nltk.download('all')
as the root user, but the process that eventually used nltk was another user who didn't have access to /root/nltk_data where the content was downloaded.
So I simply recursively copied everything from the download location to one of the paths where NLTK was looking to find it like this:
cp -R /root/nltk_data/ /home/ubuntu/nltk_data
Take a look at http://json.org/. It claims a bit different list of escaped characters than Chris proposed.
\"
\\
\/
\b
\f
\n
\r
\t
\u four-hex-digits
stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end
Use
[YourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
The HashMap has forEach
as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:
map.forEach((k,v)-> System.out.println(k+", "+v));
or
map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));
In the google io session about NFC, qa section. There was such a question:
card emulation? No API support for card emulation No consistent user experience when doing card emulation and no compelling story
In Visual Studio and most other half decent IDEs you can simply do SHIFT+TAB. It does the opposite of just TAB.
I would think and hope that the IDEs you mention support this as well.
If you are on Amazon Redshift, where string_agg is not supported, try using listagg.
SELECT company_id, listagg(EMPLOYEE, ', ') as employees
FROM EMPLOYEE_table
GROUP BY company_id;
I suppose this happens due to the max-width of a modal being set to 500px and max-width of modal-lg is 800px I suppose setting it to auto will make your modal responsive
Yeap, you just need to make .
match newline :
$string =~ /(START)(.+?)(END)/s;
Goes to the right and can be used the same way for the left
.yourComponent
{
float: right;
bottom: 0;
}
Try this one -
"SELECT
ID, Salt, password, BannedEndDate
, (
SELECT COUNT(1)
FROM dbo.LoginFails l
WHERE l.UserName = u.UserName
AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter.add("aaaa")
}
}
As far as I know, apart from setting the command or connection timeouts in the client, there is no way to change timeouts on a query by query basis in the server.
You can indeed change the default 600 seconds using sp_configure
, but these are server scoped.
You can use annotate your method with @Scheduled(cron ="0 1 1 * * ?")
.
0 - is for seconds
1- 1 minute
1 - hour of the day.
Updating a pull request in GitHub is as easy as committing the wanted changes into existing branch (that was used with pull request), but often it is also wanted to squash the changes into single commit:
git checkout yourbranch
git rebase -i origin/master
# Edit command names accordingly
pick 1fc6c95 My pull request
squash 6b2481b Hack hack - will be discarded
squash dd1475d Also discarded
git push -f origin yourbranch
...and now the pull request contains only one commit.
Related links about rebasing:
Okay, redis is pretty user friendly but there are some gotchas.
Here are just some easy commands for working with redis on Ubuntu:
install:
sudo apt-get install redis-server
start with conf:
sudo redis-server <path to conf>
sudo redis-server config/redis.conf
stop with conf:
redis-ctl shutdown
(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)
log:
tail -f /var/log/redis/redis-server.log
Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:
/etc/redis/redis.conf
Then paste it at <path to conf>
, tweak as needed and you're good to go.
Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).
However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).
To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
You can double click directly on the .cs file representing your form in the Solution Explorer :
This will open Form1.cs [Design]
, which contains the drag&drop controls.
If you are directly in the code behind (The file named Form1.cs
, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.
From the design view, you can switch back to the Code Behind by pressing F7.
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
Very simply:
$id = substr($url, strrpos($url, '/') + 1);
strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.
As mentioned by redanimalwar if there is no slash this doesn't work correctly since strrpos
returns false. Here's a more robust version:
$pos = strrpos($url, '/');
$id = $pos === false ? $url : substr($url, $pos + 1);
I rise to the challenge of providing the signed answer:
def f(x,y):
import math
return min(y-x, y-x+2*math.pi, y-x-2*math.pi, key=abs)
Daniel answer is right on the spot. If you want to query more than one field do this:
Employee.objects.values_list('eng_name','rank')
This will return list of tuples. You cannot use named=Ture when querying more than one field.
Moreover if you know that only one field exists with that info and you know the pk id then do this:
Employee.objects.values_list('eng_name','rank').get(pk=1)
If each file in your program is first compiled to an object file, then the object files are linked together, you need extern
. It tells the compiler "This function exists, but the code for it is somewhere else. Don't panic."
To see what the problem is, when you get the cryptic error 0 go to ... | More Tools | Developer Tools (Ctrl+Shift+I) in Chrome (on the page giving the error)
Read the red text in the log to get the true error message. If there is too much in there, right-click and Clear Console, then do your last request again.
My first problem was, I was passing in Authorization headers to my own cross-domain web service for the browser for the first time.
I already had:
Access-Control-Allow-Origin: *
But not:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
in the response header of my web service.
After I added that, my error zero was gone from my own web server, as well as when running the index.html file locally without a web server, but was still giving errors in code pen.
Back to ... | More Tools | Developer Tools while getting the error in codepen, and there is clearly explained: codepen uses https, so I cannot make calls to http, as the security is lower.
I need to therefore host my web service on https.
Knowing how to get the true error message - priceless!
You can use margin auto. With flex, the div seems to be centered vertically too.
body,
html {
height: 100%;
margin: 0;
}
.site {
height: 100%;
display: flex;
}
.site .box {
background: #0ff;
max-width: 20vw;
margin: auto;
}
<div class="site">
<div class="box">
<h1>blabla</h1>
<p>blabla</p>
<p>blablabla</p>
<p>lbibdfvkdlvfdks</p>
</div>
</div>
you can use too:
val frases = arrayOf("texto01","texto02 ","anotherText","and ")
for example.
This work if you have an Apache server
PHP Code:
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
Result:
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive
var arr = ['a','b',1];
var results = arr.filter(function(item){
if(typeof item ==='string'){return item;}
});
For 2 and more left joins (left joining creatorUser and initiatorUser )
IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
join candidateUser in authContext.AuthUsers
on r.CandidateId equals candidateUser.Id
join creatorUser in authContext.AuthUsers
on r.CreatorId equals creatorUser.Id into gj
from x in gj.DefaultIfEmpty()
join initiatorUser in authContext.AuthUsers
on r.InitiatorId equals initiatorUser.Id into init
from x1 in init.DefaultIfEmpty()
where candidateUser.UserName.Equals(candidateUsername)
select new CreateRequestModel
{
UserName = candidateUser.UserName,
CreatorId = (x == null ? String.Empty : x.UserName),
InitiatorId = (x1 == null ? String.Empty : x1.UserName),
CandidateId = candidateUser.UserName
};
you could try using a StringIO
import urllib, cStringIO
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
You can try this to get infos like:
git config --get user.name
git config --get user.email
There's nothing like "first name" and "last name" for the user.
Hope this will help.
if you are using the less source, there should be a variable for the navbar height in the variables.less
file. If you are not using the source, then you can customize it using the customize utilty that bootstrap's site provides. And then you can downloaded it and include it in your project. The variable you are looking for is: @navbar-height
There's a Win32 port of the Unix tee
command, that does exactly that. See http://unxutils.sourceforge.net/ or http://getgnuwin32.sourceforge.net/
One more way to get first and last entry of a LinkedHashMap is to use toArray()
method of Set interface.
But I think iterating over the entries in the entry set and getting the first and last entry is a better approach.
The usage of array methods leads to warning of the form " ...needs unchecked conversion to conform to ..." which cannot be fixed [but can be only be suppressed by using the annotation @SuppressWarnings("unchecked")
].
Here is a small example to demonstrate the usage of toArray()
method:
public static void main(final String[] args) {
final Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
orderMap.put(6, "Six");
orderMap.put(7, "Seven");
orderMap.put(3, "Three");
orderMap.put(100, "Hundered");
orderMap.put(10, "Ten");
final Set<Entry<Integer, String>> mapValues = orderMap.entrySet();
final int maplength = mapValues.size();
final Entry<Integer,String>[] test = new Entry[maplength];
mapValues.toArray(test);
System.out.print("First Key:"+test[0].getKey());
System.out.println(" First Value:"+test[0].getValue());
System.out.print("Last Key:"+test[maplength-1].getKey());
System.out.println(" Last Value:"+test[maplength-1].getValue());
}
// the output geneated is :
First Key:6 First Value:Six
Last Key:10 Last Value:Ten
Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-
When we mark a parameter as optional in the action uri using ?
character then we must provide default values to the parameters in the method signature as shown below:
MyMethod(string name = "someDefaultValue", int? Id = null)
This can also be a problem from the improper use of functions like FindNextFile when a FindClose is never executed. The process of the built file is terminated, and the build itself can be deleted, but LNK1168 will prevent a rebuild because of the open handle. This can create a handle leak in Explorer which can be addressed by terminating and restarting Explorer, but in many cases an immediate reboot is necessary.
If you are using eclipse and working on a maven project, then also the above steps work.
Right-click on your root folder.
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> Junit 3/4
Simple query would do
SHOW TABLE STATUS LIKE 'table_name'
Each class will use its own classloader to load other classes. So if ClassA.class
references ClassB.class
then ClassB
needs to be on the classpath of the classloader of ClassA
, or its parents.
The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC
and then passed to a thread owned by ClassLoaderD
. In this case the object needs to use Thread.currentThread().getContextClassLoader()
directly if it wants to load resources that are not available on its own classloader.