You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
The problem is that t.join() blocks the click event, the main thread does not get back to the event loop to process repaints. See Why ttk Progressbar appears after process in Tkinter or TTK progress bar blocked when sending email
A template class is like a macro, only a whole lot less evil.
Think of a template as a macro. The parameters to the template get substituted into a class (or function) definition, when you define a class (or function) using a template.
The difference is that the parameters have "types" and values passed are checked during compilation, like parameters to functions. The types valid are your regular C++ types, like int and char. When you instantiate a template class, you pass a value of the type you specified, and in a new copy of the template class definition this value gets substituted in wherever the parameter name was in the original definition. Just like a macro.
You can also use the "class
" or "typename
" types for parameters (they're really the same). With a parameter of one of these types, you may pass a type name instead of a value. Just like before, everywhere the parameter name was in the template class definition, as soon as you create a new instance, becomes whatever type you pass. This is the most common use for a template class; Everybody that knows anything about C++ templates knows how to do this.
Consider this template class example code:
#include <cstdio>
template <int I>
class foo
{
void print()
{
printf("%i", I);
}
};
int main()
{
foo<26> f;
f.print();
return 0;
}
It's functionally the same as this macro-using code:
#include <cstdio>
#define MAKE_A_FOO(I) class foo_##I \
{ \
void print() \
{ \
printf("%i", I); \
} \
};
MAKE_A_FOO(26)
int main()
{
foo_26 f;
f.print();
return 0;
}
Of course, the template version is a billion times safer and more flexible.
See example here: Input and Output binary streams using JERSEY?
Pseudo code would be something like this (there are a few other similar options in above mentioned post):
@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
//
// 1. Get Stream to file from first server
//
while(<read stream from first server>) {
output.write(<bytes read from first server>)
}
} catch (Exception e) {
throw new WebApplicationException(e);
} finally {
// close input stream
}
}
}
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
Europe is quite huge. I'm not sure if they use the same format all over. However this or this answer will be of help.
String text = "1,234567";
NumberFormat nf_in = NumberFormat.getNumberInstance(Locale.GERMANY);
double val = nf_in.parse(text).doubleValue();
NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK);
nf_out.setMaximumFractionDigits(3);
String output = nf_out.format(val);
I.e. use the correct locale.
The hosting environment comes from the ASPNET_ENV environment variable, which is available during Startup using the IHostingEnvironment.IsEnvironment extension method, or one of the corresponding convenience methods of IsDevelopment or IsProduction. Either save what you need in Startup(), or in ConfigureServices call:
var foo = Environment.GetEnvironmentVariable("ASPNET_ENV");
int &z = 12;
On the right hand side, a temporary object of type int
is created from the integral literal 12
, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:
int &z = int(12); //still same error
Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.
A temporary object can be bound to const reference, which means, you can do this:
const int &z = 12; //ok
For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:
int && z = 12; //C+11 only
Note that there is &&
intead of &
. Also note that const
is not needed anymore, even though the object which z
binds to is a temporary object created out of integral-literal 12
.
Since C++11 has introduced rvalue-reference, int&
is now henceforth called lvalue-reference.
For a single boxplot:
import seaborn as sb
sb.boxplot(data=Array).set_title('Title')
For more boxplot in the same plot:
import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')
e.g.
import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')
From personal experience, the System.Diagnostics.Stopwatch
class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!
Consider the following example:
Stopwatch sw;
for(int index = 0; index < 10; index++)
{
sw = Stopwatch.StartNew();
DoSomething();
Console.WriteLine(sw.ElapsedMilliseconds);
}
sw.Stop();
Example results
132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms
Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"
The answer is that Stopwatch
does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.
What you should really be looking for absolute accuracy is Performance Profiling!
Take a look at the following:
RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling
Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?
I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET
Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branch
Merge Squash: retains the changes but omits the individual commits from history
Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master
More on here
As I posted in the comment you don't need to use both setTimeout()
and setInterval()
, moreover you have a syntax error too (the one extra }
). Correct your code like this:
(edited to add two functions to force the next/previous image to be shown)
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload = "startTimer()">
<img id="img" src="startpicture.jpg"/>
<button type="button" onclick="displayPreviousImage()">Previous</button>
<button type="button" onclick="displayNextImage()">Next</button>
</body>
</html>
The </script>
inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).
To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):
<script type="text/javascript">
<!--
if (jQuery === undefined) {
document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
}
// -->
</script>
...but to be honest, using document.write
is not something I would consider best practice. Why not manipulating the DOM directly?
<script type="text/javascript">
<!--
if (jQuery === undefined) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
document.body.appendChild(script);
}
// -->
</script>
In your case, there's no need to iterate through the list, because you know which object to delete. You have several options. First you can remove the object by index (so if you know, that the object is the second list element):
a.remove(1); // indexes are zero-based
Then, you can remove the first occurence of your string:
a.remove("acbd"); // removes the first String object that is equal to the
// String represented by this literal
Or, remove all strings with a certain value:
while(a.remove("acbd")) {}
It's a bit more complicated, if you have more complex objects in your collection and want to remove instances, that have a certain property. So that you can't remove them by using remove
with an object that is equal to the one you want to delete.
In those case, I usually use a second list to collect all instances that I want to delete and remove them in a second pass:
List<MyBean> deleteCandidates = new ArrayList<>();
List<MyBean> myBeans = getThemFromSomewhere();
// Pass 1 - collect delete candidates
for (MyBean myBean : myBeans) {
if (shallBeDeleted(myBean)) {
deleteCandidates.add(myBean);
}
}
// Pass 2 - delete
for (MyBean deleteCandidate : deleteCandidates) {
myBeans.remove(deleteCandidate);
}
I had the same problem. I solved it by adding the Spring facet (File->Project Structure) for each relevant module, and then add the configuration files. For some projects (spring mvc), the config files where detected automatically. However, for a jar project, I had to add the configuration files manually.
There are different ways for this:
1.Building C# Applications Using csc.exe
While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.
2.Building .NET Applications Using Notepad++
Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports
3.Building .NET Applications Using SharpDevelop
As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.
Short version:
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
$ touch foo bar
$ svn revert foo bar
$ rm foo bar
If the conflict is about directories instead of files then replace touch
with mkdir
and rm
with rm -r
.
Note: the same procedure also work for the following situation:
$ svn st
! C foo
> local delete, incoming delete upon update
! C bar
> local delete, incoming delete upon update
Long version:
This happens when you edit a file while someone else deleted the file and commited first. As a good svn citizen you do an update before a commit. Now you have a conflict. Realising that deleting the file is the right thing to do you delete the file from your working copy. Instead of being content svn now complains that the local files are missing and that there is a conflicting update which ultimately wants to see the files deleted. Good job svn.
Should svn resolve
not work, for whatever reason, you can do the following:
Initial situation: Local files are missing, update is conflicting.
$ svn st
! + C foo
> local edit, incoming delete upon update
! + C bar
> local edit, incoming delete upon update
Recreate the conflicting files:
$ touch foo bar
If the conflict is about directories then replace touch
with mkdir
.
New situation: Local files to be added to the repository (yeah right, svn, whatever you say), update still conflicting.
$ svn st
A + C foo
> local edit, incoming delete upon update
A + C bar
> local edit, incoming delete upon update
Revert the files to the state svn likes them (that means deleted):
$ svn revert foo bar
New situation: Local files not known to svn, update no longer conflicting.
$ svn st
? foo
? bar
Now we can delete the files:
$ rm foo bar
If the conflict is about directories then replace rm
with rm -r
.
svn no longer complains:
$ svn st
Done.
In application.properties
file present in resources:
server.port=8082
For lamdas where your long value is somewhere in an object I recommend using:
.sorted((o1, o2) -> Long.compare(o1.getLong(), o2.getLong()))
or even better:
.sorted(Comparator.comparingLong(MyObject::getLong))
Similarly in Java, you can create a S4 class in R that encapsulates your information:
setClass(Class="Person",
representation(
height="numeric",
age="numeric"
)
)
Then your function can return an instance of this class:
myFunction = function(age=28, height=176){
return(new("Person",
age=age,
height=height))
}
and you can access your information:
aPerson = myFunction()
aPerson@age
aPerson@height
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
You don't need to escape the '
character in a String (wrapped in "
), and you don't have to escape a "
character in a char (wrapped in '
).
The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).
You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.
I personally tried many RegEx expressions without having found the perfect one that match all cases.
I think that regular expressions is hard to configure properly to match all cases properly. Although few persons will not like the namespace (and I was part of them), I propose something that is part of the .Net framework and give me proper results all the times in all cases (mainly managing every double quotes cases very well):
Microsoft.VisualBasic.FileIO.TextFieldParser
Found it here: StackOverflow
Example of usage:
TextReader textReader = new StringReader(simBaseCaseScenario.GetSimStudy().Study.FilesToDeleteWhenComplete);
Microsoft.VisualBasic.FileIO.TextFieldParser textFieldParser = new TextFieldParser(textReader);
textFieldParser.SetDelimiters(new string[] { ";" });
string[] fields = textFieldParser.ReadFields();
foreach (string path in fields)
{
...
Hope it could help.
If you are on Azure you need you can now, you need to have Manag. Studio 2014 and update hotfix: http://blogs.msdn.com/b/sqlreleaseservices/archive/2014/12/18/sql-server-2014-management-studio-updated-support-for-the-latest-azure-sql-database-update-v12-preview.aspx
Just works:
const minute = Math.floor(( milliseconds % (1000 * 60 * 60)) / (1000 * 60));
const second = Math.floor((ms % (1000 * 60)) / 1000);
Why not just run the program from a console ie run the program from cmd.exe if you're using Windows. That way the window stays open after the program finishes.
[EDIT]: When I use KDevelop4 there is a fully fledged instance of Bash (a Linux CLI) running in a tab at the bottom of the IDE. Which is what I use in these sort of circumstances.
For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.
Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.
This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..
Ex:
Table 1
DiffKey Other Val
1 X
1 Y
1 Z
Table 3
DiffKey Key Key2 Tbl3 Other
1 2 6 V
1 2 6 X
1 2 6 Y
1 2 6 Z
Table 2
Key Key2 Other Val
2 6 a
2 6 b
2 6 c
2 6 d
2 6 e
So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.
So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.
SELECT
COUNT(*)
FROM
Table1
INNER JOIN Table3
ON Table1.DifferentKey = Table3.DifferentKey
INNER JOIN Table2
ON Table3.Key =Table2.Key
AND Table3.Key2 = Table2.Key2
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
gitignore - Specifies intentionally untracked files to ignore.
Example to exclude everything except a specific directory foo/bar (note the /* - without the slash, the wildcard would also exclude everything within foo/bar):
$ cat .gitignore
# exclude everything except directory foo/bar
/*
!/foo
/foo/*
!/foo/bar
Another example for WordPress:
!/wp-content
wp-content/*
!/wp-content/plugins
wp-content/plugins/*
!wp-content/plugins/my-awesome-plugin
More informations in here: https://git-scm.com/docs/gitignore
Looks like you are trying to copy to a local machine with that command.
An example scp looks more like the command below:
Copy the file "foobar.txt" from the local host to a remote host
$ scp foobar.txt [email protected]:/some/remote/directory
scp "the_file" your_username@the_remote_host:the/path/to/the/directory
to send a directory:
Copy the directory "foo" from the local host to a remote host's directory "bar"
$ scp -r foo [email protected]:/some/remote/directory/bar
scp -r "the_directory_to_copy" your_username@the_remote_host:the/path/to/the/directory/to/copy/to
and to copy from remote host to local:
Copy the file "foobar.txt" from a remote host to the local host
$ scp [email protected]:foobar.txt /your/local/directory
scp your_username@the_remote_host:the_file /your/local/directory
and to include port number:
Copy the file "foobar.txt" from a remote host with port 8080 to the local host
$ scp -P 8080 [email protected]:foobar.txt /your/local/directory
scp -P port_number your_username@the_remote_host:the_file /your/local/directory
pscp -r <directory_to_copy> username@remotehost:/path/to/directory/on/remote/host
You should chain the replace() together instead of assigning the result and replacing again.
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
.replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
.replace(/.bbbbbb/g,'/world\">Helloworld</a>');
See DEMO.
This is the easiest way:
php -f /home/your_username/public_html/script.php
And if you want to log the script output to a file, add this to the end of the command:
>> /home/your_username/logs/someFile.txt 2>&1
Make sure that the htaccess file is readable by apache:
chmod 644 /var/www/abc/.htaccess
And make sure the directory it's in is readable and executable:
chmod 755 /var/www/abc/
It's the Substring method of String
, with the first argument set to 0.
myString.Substring(0,1);
[The following was added by Almo; see Justin J Stark's comment. —Peter O.]
Warning:
If the string's length is less than the number of characters you're taking, you'll get an ArgumentOutOfRangeException
.
I don't actually get an error with this.
a <- as.data.frame(matrix(c(sample(letters,50, replace=T),runif(100)), nrow=50))
b <- sample(letters,10, replace=T)
c <- cbind(a,b)
I used letters incase joining all numerics had different functionality (which it didn't). Your 'first data frame', which is actually just a vector', is just repeated 5 times in that 4th column...
But all the comments from the gurus to the question are still relevant :)
Edit: The correct way (currently) to use a local AAR file as a build dependency is to use the module import wizard (File | New Module | Import .JAR or .AAR package) which will automatically add the .aar as a library module in your project.
Old Answer
Try this:
allprojects {
repositories {
jcenter()
flatDir {
dirs 'libs'
}
}
}
...
compile(name:'slidingmenu', ext:'aar')
My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...
@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.
<?php
function arrayCopy( array $array ) {
$result = array();
foreach( $array as $key => $val ) {
if( is_array( $val ) ) {
$result[$key] = arrayCopy( $val );
} elseif ( is_object( $val ) ) {
$result[$key] = clone $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
?>
You also can set the width of a audio tag by JavaScript:
audio = document.getElementById('audio-id');
audio.style.width = '200px';
I'd recommend not using images2gif from visvis because it has problems with PIL/Pillow and is not actively maintained (I should know, because I am the author).
Instead, please use imageio, which was developed to solve this problem and more, and is intended to stay.
Quick and dirty solution:
import imageio
images = []
for filename in filenames:
images.append(imageio.imread(filename))
imageio.mimsave('/path/to/movie.gif', images)
For longer movies, use the streaming approach:
import imageio
with imageio.get_writer('/path/to/movie.gif', mode='I') as writer:
for filename in filenames:
image = imageio.imread(filename)
writer.append_data(image)
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
This one is working for me.
If you have the column and the sequence, you first need to populate a new key for all the existing rows. Assuming you don't care which key is assigned to which row
UPDATE table_name
SET new_pk_column = sequence_name.nextval;
Once that's done, you can create the primary key constraint (this assumes that either there is no existing primary key constraint or that you have already dropped the existing primary key constraint)
ALTER TABLE table_name
ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )
If you want to generate the key automatically, you'd need to add a trigger
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
:new.new_pk_column := sequence_name.nextval;
END;
If you are on an older version of Oracle, the syntax is a bit more cumbersome
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
SELECT sequence_name.nextval
INTO :new.new_pk_column
FROM dual;
END;
Can you check value of i
by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.
//Method for Smaller Number Range:
Integer.parseInt("abc",16);
//Method for Bigger Number Range.
Long.parseLong("abc",16);
//Method for Biggest Number Range.
new BigInteger("abc",16);
[innerHtml]
is great option in most cases, but it fails with really large strings or when you need hard-coded styling in html.
I would like to share other approach:
All you need to do, is to create a div in your html file and give it some id:
<div #dataContainer></div>
Then, in your Angular 2 component, create reference to this object (TypeScript here):
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
templateUrl: "some html file"
})
export class MainPageComponent {
@ViewChild('dataContainer') dataContainer: ElementRef;
loadData(data) {
this.dataContainer.nativeElement.innerHTML = data;
}
}
Then simply use loadData
function to append some text to html element.
It's just a way that you would do it using native javascript, but in Angular environment. I don't recommend it, because makes code more messy, but sometimes there is no other option.
See also Angular 2 - innerHTML styling
This statement will definitely help you:
env = env.OrderByDescending(c => c.ReportDate).ToList();
Update 23 March'15 :
Official multiple SIM API is available now from Android 5.1 onwards
Other possible option :
You can use Java reflection to get both IMEI numbers.
Using these IMEI numbers you can check whether the phone is a DUAL SIM or not.
Try following activity :
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this);
String imeiSIM1 = telephonyInfo.getImsiSIM1();
String imeiSIM2 = telephonyInfo.getImsiSIM2();
boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
boolean isSIM2Ready = telephonyInfo.isSIM2Ready();
boolean isDualSIM = telephonyInfo.isDualSIM();
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(" IME1 : " + imeiSIM1 + "\n" +
" IME2 : " + imeiSIM2 + "\n" +
" IS DUAL SIM : " + isDualSIM + "\n" +
" IS SIM1 READY : " + isSIM1Ready + "\n" +
" IS SIM2 READY : " + isSIM2Ready + "\n");
}
}
And here is TelephonyInfo.java
:
import java.lang.reflect.Method;
import android.content.Context;
import android.telephony.TelephonyManager;
public final class TelephonyInfo {
private static TelephonyInfo telephonyInfo;
private String imeiSIM1;
private String imeiSIM2;
private boolean isSIM1Ready;
private boolean isSIM2Ready;
public String getImsiSIM1() {
return imeiSIM1;
}
/*public static void setImsiSIM1(String imeiSIM1) {
TelephonyInfo.imeiSIM1 = imeiSIM1;
}*/
public String getImsiSIM2() {
return imeiSIM2;
}
/*public static void setImsiSIM2(String imeiSIM2) {
TelephonyInfo.imeiSIM2 = imeiSIM2;
}*/
public boolean isSIM1Ready() {
return isSIM1Ready;
}
/*public static void setSIM1Ready(boolean isSIM1Ready) {
TelephonyInfo.isSIM1Ready = isSIM1Ready;
}*/
public boolean isSIM2Ready() {
return isSIM2Ready;
}
/*public static void setSIM2Ready(boolean isSIM2Ready) {
TelephonyInfo.isSIM2Ready = isSIM2Ready;
}*/
public boolean isDualSIM() {
return imeiSIM2 != null;
}
private TelephonyInfo() {
}
public static TelephonyInfo getInstance(Context context){
if(telephonyInfo == null) {
telephonyInfo = new TelephonyInfo();
TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
telephonyInfo.imeiSIM1 = telephonyManager.getDeviceId();;
telephonyInfo.imeiSIM2 = null;
try {
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1);
} catch (GeminiMethodNotFoundException e) {
e.printStackTrace();
try {
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1);
} catch (GeminiMethodNotFoundException e1) {
//Call here for next manufacturer's predicted method name if you wish
e1.printStackTrace();
}
}
telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
telephonyInfo.isSIM2Ready = false;
try {
telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0);
telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1);
} catch (GeminiMethodNotFoundException e) {
e.printStackTrace();
try {
telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0);
telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1);
} catch (GeminiMethodNotFoundException e1) {
//Call here for next manufacturer's predicted method name if you wish
e1.printStackTrace();
}
}
}
return telephonyInfo;
}
private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {
String imei = null;
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimID.invoke(telephony, obParameter);
if(ob_phone != null){
imei = ob_phone.toString();
}
} catch (Exception e) {
e.printStackTrace();
throw new GeminiMethodNotFoundException(predictedMethodName);
}
return imei;
}
private static boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {
boolean isReady = false;
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);
if(ob_phone != null){
int simState = Integer.parseInt(ob_phone.toString());
if(simState == TelephonyManager.SIM_STATE_READY){
isReady = true;
}
}
} catch (Exception e) {
e.printStackTrace();
throw new GeminiMethodNotFoundException(predictedMethodName);
}
return isReady;
}
private static class GeminiMethodNotFoundException extends Exception {
private static final long serialVersionUID = -996812356902545308L;
public GeminiMethodNotFoundException(String info) {
super(info);
}
}
}
Edit :
Getting access of methods like "getDeviceIdGemini" for other SIM slot's detail has prediction that method exist.
If that method's name doesn't match with one given by device manufacturer than it will not work. You have to find corresponding method name for those devices.
Finding method names for other manufacturers can be done using Java reflection as follows :
public static void printTelephonyManagerMethodNamesForThisDevice(Context context) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Class<?> telephonyClass;
try {
telephonyClass = Class.forName(telephony.getClass().getName());
Method[] methods = telephonyClass.getMethods();
for (int idx = 0; idx < methods.length; idx++) {
System.out.println("\n" + methods[idx] + " declared by " + methods[idx].getDeclaringClass());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
EDIT :
As Seetha pointed out in her comment :
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdDs", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdDs", 1);
It is working for her. She was successful in getting two IMEI numbers for both the SIM in Samsung Duos device.
Add <uses-permission android:name="android.permission.READ_PHONE_STATE" />
EDIT 2 :
The method used for retrieving data is for Lenovo A319 and other phones by that manufacture (Credit Maher Abuthraa):
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 1);
Try this easy code:
awk '{printf("%s,",$2)}' File1
Inside Spring Boot
, I always put the webpages inside a folder like public
or webapps
or views
and place it inside src/main/resources
directory as you can see in application.properties
also.
and this is my application.properties
:
server.port=15800
spring.mvc.view.prefix=/public/
spring.mvc.view.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3306/hibernatedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
as soon you put the url like servername:15800
and this request received by Spring Boot occupied Servlet dispatcher it will exactly search the index.html
and this name will in case sensitive as the spring.mvc.view.suffix
which would be html, jsp, htm etc.
Hope it would help manyone.
An elegant way in Swift 3 and better to understand:
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
let leftMargin:CGFloat = 40
let imgWidth:CGFloat = 24
let imgHeight:CGFloat = 24
return CGRect(x: leftMargin, y: (contentRect.size.height-imgHeight) * 0.5, width: imgWidth, height: imgHeight)
}
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
let leftMargin:CGFloat = 80
let rightMargin:CGFloat = 80
return CGRect(x: leftMargin, y: 0, width: contentRect.size.width-leftMargin-rightMargin, height: contentRect.size.height)
}
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
let leftMargin:CGFloat = 10
let rightMargin:CGFloat = 10
let topMargin:CGFloat = 10
let bottomMargin:CGFloat = 10
return CGRect(x: leftMargin, y: topMargin, width: bounds.size.width-leftMargin-rightMargin, height: bounds.size.height-topMargin-bottomMargin)
}
override func contentRect(forBounds bounds: CGRect) -> CGRect {
let leftMargin:CGFloat = 5
let rightMargin:CGFloat = 5
let topMargin:CGFloat = 5
let bottomMargin:CGFloat = 5
return CGRect(x: leftMargin, y: topMargin, width: bounds.size.width-leftMargin-rightMargin, height: bounds.size.height-topMargin-bottomMargin)
}
You can use pandas.DataFrame.mask
to add virtually as many conditions as you need:
data = {'a': [1,2,3,4,5], 'b': [6,8,9,10,11]}
d = pd.DataFrame.from_dict(data, orient='columns')
c = {'c1': (2, 'Value1'), 'c2': (3, 'Value2'), 'c3': (5, d['b'])}
d['new'] = np.nan
for value in c.values():
d['new'].mask(d['a'] == value[0], value[1], inplace=True)
d['new'] = d['new'].fillna('Else')
d
Output:
a b new
0 1 6 Else
1 2 8 Value1
2 3 9 Value2
3 4 10 Else
4 5 11 11
You can do a reverse DNS lookup with host
, too. Just give it the IP address as an argument:
$ host 192.168.0.10
server10 has address 192.168.0.10
Short and elegant
#include <vector>
#include <string>
using namespace std;
vector<string> split(string data, string token)
{
vector<string> output;
size_t pos = string::npos; // size_t to avoid improbable overflow
do
{
pos = data.find(token);
output.push_back(data.substr(0, pos));
if (string::npos != pos)
data = data.substr(pos + token.size());
} while (string::npos != pos);
return output;
}
can use any string as delimiter, also can be used with binary data (std::string supports binary data, including nulls)
using:
auto a = split("this!!is!!!example!string", "!!");
output:
this
is
!example!string
You can use the negation pseudo-class :not()
against the :last-child
pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:
:not(:last-child) { /* styles */ }
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
When I faced the same problem I resolved by creating a temporary text box above the password field and hide it
like this,
<form method="post" autocomplete="off" action="">
<ul class="field-set">
<li>
<label>Username:</label>
<input type="text" name="acct" id="username" maxlength="100" size="20">
</li>
<li>
<label>Password:</label>
<input type="text" style="display:none;">
<input type="password" name="pswd" id="password" maxlength="16" size="20" >
</li>
...
</ul> </form>
It will make the username
text field not to show any previously typed words in a drop down. Since there is no attribute like name
, id
for the input field <input type="text" style="display:none;">
it wouldn't send any extra parameters also.
I am Not sure this is a good practice, but it will resolve the issue.
Namespace is use to define the path to a specific file containing a class e.g.
namespace album/className;
class className{
//enter class properties and methods here
}
You can then include this specific class into another php file by using the keyword "use" like this:
use album/className;
class album extends classname {
//enter class properties and methods
}
NOTE: Do not use the path to the file containing the class to be implements, extends of use to instantiate an object but only use the namespace.
You can use git aliases, e.g.
git config --global alias.add-commit '!git add -A && git commit'
and use it with
git add-commit -m 'My commit message'
EDIT: Reverted back to ticks ('), as otherwise it will fail for shell expansion on Linux. On Windows, one should use double-quotes (") instead (pointed out in the comments, did not verify).
The error message is fairly self-explanatory
(a,b,c,d,e) = line.split()
expects line.split()
to yield 5 elements, but in your case, it is only yielding 1 element. This could be because the data is not in the format you expect, a rogue malformed line, or maybe an empty line - there's no way to know.
To see what line is causing the issue, you could add some debug statements like this:
if len(line.split()) != 11:
print line
As Martin suggests, you might also be splitting on the wrong delimiter.
Question is quite old, but I created some possible solution how to create abstract "class" and block creation of object that type.
//our Abstract class_x000D_
var Animal=function(){_x000D_
_x000D_
this.name="Animal";_x000D_
this.fullname=this.name;_x000D_
_x000D_
//check if we have abstract paramater in prototype_x000D_
if (Object.getPrototypeOf(this).hasOwnProperty("abstract")){_x000D_
_x000D_
throw new Error("Can't instantiate abstract class!");_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
};_x000D_
_x000D_
//very important - Animal prototype has property abstract_x000D_
Animal.prototype.abstract=true;_x000D_
_x000D_
Animal.prototype.hello=function(){_x000D_
_x000D_
console.log("Hello from "+this.name);_x000D_
};_x000D_
_x000D_
Animal.prototype.fullHello=function(){_x000D_
_x000D_
console.log("Hello from "+this.fullname);_x000D_
};_x000D_
_x000D_
//first inheritans_x000D_
var Cat=function(){_x000D_
_x000D_
Animal.call(this);//run constructor of animal_x000D_
_x000D_
this.name="Cat";_x000D_
_x000D_
this.fullname=this.fullname+" - "+this.name;_x000D_
_x000D_
};_x000D_
_x000D_
Cat.prototype=Object.create(Animal.prototype);_x000D_
_x000D_
//second inheritans_x000D_
var Tiger=function(){_x000D_
_x000D_
Cat.call(this);//run constructor of animal_x000D_
_x000D_
this.name="Tiger";_x000D_
_x000D_
this.fullname=this.fullname+" - "+this.name;_x000D_
_x000D_
};_x000D_
_x000D_
Tiger.prototype=Object.create(Cat.prototype);_x000D_
_x000D_
//cat can be used_x000D_
console.log("WE CREATE CAT:");_x000D_
var cat=new Cat();_x000D_
cat.hello();_x000D_
cat.fullHello();_x000D_
_x000D_
//tiger can be used_x000D_
_x000D_
console.log("WE CREATE TIGER:");_x000D_
var tiger=new Tiger();_x000D_
tiger.hello();_x000D_
tiger.fullHello();_x000D_
_x000D_
_x000D_
console.log("WE CREATE ANIMAL ( IT IS ABSTRACT ):");_x000D_
//animal is abstract, cannot be used - see error in console_x000D_
var animal=new Animal();_x000D_
animal=animal.fullHello();
_x000D_
As You can see last object give us error, it is because Animal in prototype has property abstract
. To be sure it is Animal not something which has Animal.prototype
in prototype chain I do:
Object.getPrototypeOf(this).hasOwnProperty("abstract")
So I check that my closest prototype object has abstract
property, only object created directly from Animal
prototype will have this condition on true. Function hasOwnProperty
checks only properties of current object not his prototypes, so this gives us 100% sure that property is declared here not in prototype chain.
Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain. More about it:
In my proposition we not have to change constructor
every time after Object.create
like it is in current best answer by @Jordão.
Solution also enables to create many abstract classes in hierarchy, we need only to create abstract
property in prototype.
Ensure that Enhanced session mode settings are enabled on the Hyper-V host.
Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".
Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.
Enable Hyper-V Guest Services for your virtual machine
Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.
Start a virtual machine and click Show Options in the pop-up windows.
Or click "Edit Session Settings..." in the Actions panel on the right
It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.
View local resources. Then, select the "More..." menu.
From there, you can choose which devices to share. Removable drives are especially useful for file sharing.
Choose to "Save my settings for future connections to this virtual machine".
Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.
Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine
Alternately, if you have a case where you don't particularly care about the values of the resolved promises when there is one failure but you still want them to have run, you could do something like this which will resolve with the promises as normal when they all succeed and reject with the failed promises when any of them fail:
function promiseNoReallyAll (promises) {
return new Promise(
async (resolve, reject) => {
const failedPromises = []
const successfulPromises = await Promise.all(
promises.map(
promise => promise.catch(error => {
failedPromises.push(error)
})
)
)
if (failedPromises.length) {
reject(failedPromises)
} else {
resolve(successfulPromises)
}
}
)
}
In the same style as Giampaolo Rodolà' answer but as one liner, case insensitive and without having to match the whole process name, in windows you would have to include the .exe
suffix.
[x.kill() for x in psutil.process_iter() if 'ichat' in x.name().lower()]
To disable a keyboard key after IE9, use : e.preventDefault();
To disable a regular keyboard key under IE7/8, use : e.returnValue = false;
or return false;
If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F
) you need to add those lines :
try {
e.keyCode = 0;
}catch (e) {}
Here is a full example for IE7/8 only :
document.attachEvent("onkeydown", function () {
var e = window.event;
//Ctrl+F or F3
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
//Prevent for Ctrl+...
try {
e.keyCode = 0;
}catch (e) {}
//prevent default (could also use e.returnValue = false;)
return false;
}
});
Reference : How to disable keyboard shortcuts in IE7 / IE8
Your class MyClass
creates a new MyClassToBeTested
, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.
This error can get thrown if your data frame has sf
geometry columns.
I don't believe it's possible to guarantee that using only standard POSIX calls. Like real life, once a child is spawned, it has a life of its own.
It is possible for the parent process to catch most possible termination events, and attempt to kill the child process at that point, but there's always some that can't be caught.
For example, no process can catch a SIGKILL
. When the kernel handles this signal it will kill the specified process with no notification to that process whatsoever.
To extend the analogy - the only other standard way of doing it is for the child to commit suicide when it finds that it no longer has a parent.
There is a Linux-only way of doing it with prctl(2)
- see other answers.
CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.
Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.
The usual recommendation is to use many processes rather than many threads.
I use:
if(jQuery.support.touch){
alert('Touch enabled');
}
in jQuery mobile 1.0.1
Steps that you should follow if you want the thread dump of your StandAlone Java Process
Step 1: Get the Process ID for the shell script calling the java program
linux$ ps -aef | grep "runABCD"
user1 **8535** 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17796 17372 0 08:15:41 pts/49 0:00 grep runABCD
Step 2: Get the Process ID for the Child which was Invoked by the runABCD. Use the above PID to get the childs.
linux$ ps -aef | grep **8535**
user1 **8536** 8535 0 Mar 25 ? 126:38 /apps/java/jdk/sun4/SunOS5/1.6.0_16/bin/java -cp /home/user1/XYZServer
user1 8535 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17977 17372 0 08:15:49 pts/49 0:00 grep 8535
Step 3: Get the JSTACK for the particular process. Get the Process id of your XYSServer process. i.e. 8536
linux$ jstack **8536** > threadDump.log
ryeguy, I am currently developing a similar application and my threads number is set to 15. Unfortunately if I increase it at 20, it crashes. So, yes, I think the best way to handle this is to measure whether or not your current configuration allows more or less than a number X of threads.
The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.
Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool())
by filter(ItemType::isCool)
. That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter
invocation using a lambda expression with &&
.
But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.
In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.
So there is no simple answer.
The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.
¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation
Solution for busybox, macOS bash, and non-bash shells
The accepted answer is certainly the best choice for bash. I'm working in a Busybox environment without access to bash, and it does not understand the exec > >(tee log.txt)
syntax. It also does not do exec >$PIPE
properly, trying to create an ordinary file with the same name as the named pipe, which fails and hangs.
Hopefully this would be useful to someone else who doesn't have bash.
Also, for anyone using a named pipe, it is safe to rm $PIPE
, because that unlinks the pipe from the VFS, but the processes that use it still maintain a reference count on it until they are finished.
Note the use of $* is not necessarily safe.
#!/bin/sh
if [ "$SELF_LOGGING" != "1" ]
then
# The parent process will enter this branch and set up logging
# Create a named piped for logging the child's output
PIPE=tmp.fifo
mkfifo $PIPE
# Launch the child process with stdout redirected to the named pipe
SELF_LOGGING=1 sh $0 $* >$PIPE &
# Save PID of child process
PID=$!
# Launch tee in a separate process
tee logfile <$PIPE &
# Unlink $PIPE because the parent process no longer needs it
rm $PIPE
# Wait for child process, which is running the rest of this script
wait $PID
# Return the error code from the child process
exit $?
fi
# The rest of the script goes here
Open javascript console. You'll see an error message there. In my case it was CORS.
You do not need to insert the current timestamp manually as MySQL
provides this facility to store it automatically. When the MySQL
table is created, simply do this:
TIMESTAMP
as your column type Default
value to CURRENT_TIMESTAMP
insert
any rows into the table without inserting any values for the time
columnYou'll see the current timestamp
is automatically inserted when you insert a row. Please see the attached picture.
Open your Google-services.json file and look for this section in the file:
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:857242555489:android:46d8562d82407b11",
"android_client_info": {
"package_name": "com.example.duke_davis.project"
}
}
check whether the package is the same as your package name. Mine was different, so I changed it and it worked.
You can use the below formula to find the distance between the 2 points:
distance*distance = ((x2 - x1)*(x2 - x1)) + ((y2 - y1)*(y2 - y1))
Combining the answers of kiamlaluno and Mark, along with formatOnSave to autointent code for Python:
{
"editor.formatOnSave": true,
"editor.autoIndent": "advanced",
"editor.detectIndentation": true,
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"editor.formatOnPaste": true,
"editor.multiCursorModifier": "ctrlCmd",
"editor.snippetSuggestions": "top",
"editor.rulers": [
{
"column": 79,
"color": "#424142"
},
100, // <- a ruler in the default color or as customized at column 0
{
"column": 120,
"color": "#ff0000"
},
],
}
A revelation: Some blank cells are not actually blank! As I will show cells can have spaces, newlines and true empty:
To find these cells quickly you can do a few things.
=CODE(A1)
formula will return a #VALUE! if the cell is truly empty, otherwise a number will return. This number is the ASCII number used in =CHAR(32)
.Removing these:
If you only have a space in the cells these can be removed easily using:
If you have newlines this is more difficult and requires VBA:
Then enter the following code. Remember the Chr(10)
is a newline only replace this as required, e.g. " " & Char(10)
is a space and a newline:
Sub find_newlines()
With Me.Cells
Set c = .Find(Chr(10), LookIn:=xlValues, LookAt:=xlWhole)
If Not c Is Nothing Then
firstAddress = c.Address
Do
c.Value = ""
Set c = .FindNext(c)
If c Is Nothing Then Exit Do
Loop While c.Address <> firstAddress
End If
End With
End Sub
Now run your code pressing F5.
After file supplied: Select the range of interest for improved performance, then run the following:
Sub find_newlines()
With Selection
Set c = .Find("", LookIn:=xlValues, LookAt:=xlWhole)
If Not c Is Nothing Then
firstAddress = c.Address
Do
c.Value = ""
Set c = .FindNext(c)
If c Is Nothing Then Exit Do
Loop While c.Address <> firstAddress
End If
End With
End Sub
Here is the code to a method I call whenever I want an information box to pop up, it hogs the screen until it is accepted:
import javax.swing.JOptionPane;
public class ClassNameHere
{
public static void infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
}
The first JOptionPane
parameter (null
in this example) is used to align the dialog. null
causes it to center itself on the screen, however any java.awt.Component
can be specified and the dialog will appear in the center of that Component
instead.
I tend to use the titleBar
String to describe where in the code the box is being called from, that way if it gets annoying I can easily track down and delete the code responsible for spamming my screen with infoBoxes.
To use this method call:
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");
For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.
As above I'll post a small example of how you could use JavaFX dialogs to achieve the same result
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;
public class ClassNameHere
{
public static void infoBox(String infoMessage, String titleBar)
{
/* By specifying a null headerMessage String, we cause the dialog to
not have a header */
infoBox(infoMessage, titleBar, null);
}
public static void infoBox(String infoMessage, String titleBar, String headerMessage)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(titleBar);
alert.setHeaderText(headerMessage);
alert.setContentText(infoMessage);
alert.showAndWait();
}
}
One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.
To use this method call:
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");
or
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");
If you are trying to add an image in a button dynamically based on the context of your project, you can use the ? take to reference the source based on an outcome. Here I am using mvvm design to let my Model.Phases[0] value determine whether I want my button to be populated with images of a lightbulb on or off based on the value of the light phase.
Not sure if this helps. I'm using JqueryUI, Blueprint, and CSS. The class definition should allow you to style the button based on whatever you'd like.
<button>
<img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
I use this functions
function strright($str, $separator) {
if (intval($separator)) {
return substr($str, -$separator);
} elseif ($separator === 0) {
return $str;
} else {
$strpos = strpos($str, $separator);
if ($strpos === false) {
return $str;
} else {
return substr($str, -$strpos + 1);
}
}
}
function strleft($str, $separator) {
if (intval($separator)) {
return substr($str, 0, $separator);
} elseif ($separator === 0) {
return $str;
} else {
$strpos = strpos($str, $separator);
if ($strpos === false) {
return $str;
} else {
return substr($str, 0, $strpos);
}
}
}
In the VSCode launch.json you can use "env" and configure all your environment variables there:
{
"version": "0.2.0",
"configurations": [
{
"env": {
"NODE_ENV": "development",
"port":"1337"
},
...
}
]
}
A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.
public class ListModel<T>
{
public List<T> Items { get; set; }
public ListModel(List<T> list) {
Items = list;
}
}
and when you return the View you just need to simply do:
List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));
then define the list in the model:
@model ListModel<customClass>
and ready to go:
@foreach(var element in Model.Items) {
//do as needed...
}
if you do ctrl-z
and then type exit
it will close background applications.
Ctrl+Q
is another good way to kill the application.
Instead of faking a Boolean and leaving a trap for future readers, why not just use a better value than true and false?
For example:
build_state=success
if something-horrible; then
build_state=failed
fi
if [[ "$build_state" == success ]]; then
echo go home; you are done
else
echo your head is on fire; run around in circles
fi
The solution
angular.element(document.getElementById('ID')).scope().get()
stopped working for me in angular 1.5.2. Sombody mention in a comment that this doesn't work in 1.4.9 also.
I fixed it by storing the scope in a global variable:
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope = function bar(){
console.log("foo");
};
scopeHolder = $scope;
})
call from custom code:
scopeHolder.bar()
if you wants to restrict the scope to only this method. To minimize the exposure of whole scope. use following technique.
var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
$scope.bar = function(){
console.log("foo");
};
scopeHolder = $scope.bar;
})
call from custom code:
scopeHolder()
I figured out that the plt.pause(0.001)
command is the only thing needed and nothing else.
plt.show() and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.
Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.
The documentation of the plt.pause(interval) command states:
If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.
and this is pretty much exactly what we want. Try this code:
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0, 51) # x coordinates
for z in range(10, 50):
y = np.power(x, z/10) # y coordinates of plot for animation
plt.cla() # delete previous plot
plt.axis([-50, 50, 0, 10000]) # set axis limits, to avoid rescaling
plt.plot(x, y) # generate new plot
plt.pause(0.1) # pause 0.1 sec, to force a plot redraw
This was considered for inclusion in C++/1x, but was dropped (this is a correction to what I said earlier).
It would be less useful in C++ anyway since we already have std::vector
to fill this role.
Give the command SHOW CREATE TABLE whatever
Then look at the table definition.
It probably has a line like this
logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
in it. DEFAULT CURRENT_TIMESTAMP
means that any INSERT
without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP
means that any update without an explicit timestamp results in an update to the current timestamp value.
You can control this default behavior when creating your table.
Or, if the timestamp column wasn't created correctly in the first place, you can change it.
ALTER TABLE whatevertable
CHANGE whatevercolumn
whatevercolumn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable
without changing the timestamp, that is,
To prevent the column from updating when other columns change
then you need to issue this kind of update.
UPDATE whatevertable
SET something = 'newvalue',
whatevercolumn = whatevercolumn
WHERE someindex = 'indexvalue'
This works with TIMESTAMP
and DATETIME
columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMP
s) When you use TIMESTAMP
s, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.
Recommended approach will be
1.Don't call super method(Remove super call from overridden method)
2.Google recommend to call SslErrorHandler.cancel() method if any error comes
3.Don't Prompt dialog to expose SSL errors
Whats the best solution?? Remove this override method
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,SslError error) {
}
Had the same problem on AWS Linux 2, phpinfo() shows SimpleXML installed but not working, below cmd solved my issue
sudo yum install php-xml
As of January 2018 the url is https://www.twitch.tv/username/dashboard/settings/streamkey
Consider using std::multimap
as suggested by @Ulrich Eckhardt. Just that the code could be made even simpler.
Given
std::vector<int> a = {5, 2, 1, 4, 3}; // a: 5 2 1 4 3
To sort in the mean time of insertion
std::multimap<int, std::size_t> mm;
for (std::size_t i = 0; i != a.size(); ++i)
mm.insert({a[i], i});
To retrieve values and original indices
std::vector<int> b;
std::vector<std::size_t> c;
for (const auto & kv : mm) {
b.push_back(kv.first); // b: 1 2 3 4 5
c.push_back(kv.second); // c: 2 1 4 3 0
}
The reason to prefer a std::multimap
to a std::map
is to allow equal values in original vectors. Also please note that, unlike for std::map
, operator[]
is not defined for std::multimap
.
I finally ended using the following :
bower install --save http://twitter.github.com/bootstrap/assets/bootstrap.zip
Seems cleaner to me since it doesn't clone the whole repo, it only unzip the required assests.
The downside of that is that it breaks the bower philosophy since a bower update
will not update bootstrap.
But I think it's still cleaner than using bower install bootstrap
and then building bootstrap in your workflow.
It's a matter of choice I guess.
Update : seems they now version a dist folder (see: https://github.com/twbs/bootstrap/pull/6342), so just use bower install bootstrap
and point to the assets in the dist
folder
SELECT *, CAST(SUBSTRING_INDEX(field, '-', -1) AS UNSIGNED) as num FROM tableName ORDER BY num;
I have provided jsfiddle link for you to format US phone numbers as (XXX) XXX-XXX
$('.class-name').on('keypress', function(e) {
var key = e.charCode || e.keyCode || 0;
var phone = $(this);
if (phone.val().length === 0) {
phone.val(phone.val() + '(');
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if (phone.val().length === 4) {
phone.val(phone.val() + ')');
}
if (phone.val().length === 5) {
phone.val(phone.val() + ' ');
}
if (phone.val().length === 9) {
phone.val(phone.val() + '-');
}
if (phone.val().length >= 14) {
phone.val(phone.val().slice(0, 13));
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.on('focus', function() {
phone = $(this);
if (phone.val().length === 0) {
phone.val('(');
} else {
var val = phone.val();
phone.val('').val(val); // Ensure cursor remains at the end
}
})
.on('blur', function() {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Live example: JSFiddle
A tip to all people that use flat-red, flat-green plugin, because of this plugin the answers above wont work!
In that case, use onchange="do_your_stuff();" on the label, for example: Your checkbox here
The reason why it doesn't work is that this Jquery creates a lot of objects around the real checkbox, so you can't see if it's changed or not.
But if someone click straight on checkbox, won't work :'(
Instead of giving the path following way:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\python.exe
Do this:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\
According to doc
Migrate a GCM client app to FCM
onTokenRefresh()
only Called if InstanceID token is updated
So it will call only at first time when you install an app to your device.
So I suggest please uninstall your app manually and try to run again
definitely you will get TOKEN
You can use a JsonPath query to extract the value. And with JsonSurfer which is backed by Gson, your problem can be solved by simply two line of code!
JsonSurfer jsonSurfer = JsonSurfer.gson();
String result = jsonSurfer.collectOne(jsonLine, String.class, "$.data.translations[0].translatedText");
<img src='thumb.gif' onclick='this.src="full_size.gif"' />
Of course you can change the onclick event to load the image wherever you want.
If you look at this url: http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/
this part of the schema may be what you are looking for.
ID INTEGER NOT NULL
PRIMARY KEY GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1),
Try:
adb shell ip addr show rmnet0 | grep 'inet ' | cut -d' ' -f6|cut -d/ -f1
It will return your IPV4 assigned by the operator
172.22.1.215
The answers from Tomik and Peterdk work when you want your custom view to occupy the entire action bar, even hiding the native title.
But if you want your custom view to live side-by-side with the title (and fill all remaining space after the title is displayed), then may I refer you to the excellent answer from user Android-Developer here:
https://stackoverflow.com/a/16517395/614880
His code at bottom worked perfectly for me.
This might work...
from p in db.products
select new
{
Owner = (p.price > 0 ?
from q in db.Users select q.Name :
from r in db.ExternalUsers select r.Name)
}
use desc tablename
from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.
$ hive -e 'desc dbname.tablename;' > ~/columnnames.txt
where dbname
is the name of the Hive database where your table is residing
You can find the file columnnames.txt in your root directory.
$cd ~
$ls
i tried using the same ng-click for two elements with same name showDetail2('abc')
it is working for me . can you check rest of the code which may be breaking you to move further.
You can try this:
.classname{_x000D_
width:250px;_x000D_
overflow:hidden;_x000D_
text-overflow:ellipsis;_x000D_
}
_x000D_
No. JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the GC decides to run and the object is eligible for collection.
Seeing as that will happen automatically as required, what would be the purpose of reclaiming the memory explicitly?
this is the solution you need, you can use the errorPlacement
method to override where to put the error message
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
errorPlacement: function(error, element) {
error.insertAfter('.form-group'); //So i putted it after the .form-group so it will not include to your append/prepend group.
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
it's works for me like magic. Cheers
This one-liner should work too:
(cd /path/to/your/app && npm start)
Note that the current directory will be changed to /path/to/your/app after executing this command. To preserve the working directory:
(cd /path/to/your/app && npm start && cd -)
I used this solution because a program configuration file I was editing back then didn't support specifying command line arguments.
This will let Git authenticate on HTTPS using .netrc
:
_netrc
and located in c:\Users\<username>
.HOME=%USERPROFILE%
(set system-wide environment variables using the System option in the control panel. Depending on the version of Windows, you may need to select "Advanced Options".)._netrc
file cannot contain spaces (quoting the password will not work).When installing make sure that under Tcl/Tk
you select Will be installed on hard drive
. If it is installing with a cross at the left then Tkinter will not be installed.
The same goes for Python 3:
Two way to add Scroll in page
1. Using SingleChildScrollView :
SingleChildScrollView(
child: Column(
children: [
Container(....),
SizedBox(...),
Container(...),
Text(....)
],
),
),
2. Using ListView : ListView is default provide Scroll no need to add extra widget for scrolling
ListView(
children: [
Container(..),
SizedBox(..),
Container(...),
Text(..)
],
),
Have you tried adding the absolute directory of go to your 'path'?
export PATH=$PATH:/directory/to/go/
According Oracle and Sun doc, a class can use all classes from its own package and all public classes from other packages. You can access the public classes in another package in two ways.
The first is simply to add the full package name in front of every class name. For example:
java.util.Date today = new java.util.Date();
The simpler, and more common, approach is to use the import statement. The point of the import statement is to give you a shorthand to refer to the classes in the package. Once you use import, you no longer have to give the classes their full names. You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.util package with the statement Then you can use without a package prefix.
import java.util.*;
// Use class in your code with this manner
Date today = new Date();
As you mentioned in your question that your classes are under the same package, you should not have any problem, it is better just to use class name.
So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.
// Download button
$("#download-image").on('click', function () {
let width = __CANVAS.width;
let height = __CANVAS.height;
//set the orientation
if(width > height){
pdf = new jsPDF('l', 'px', [width, height]);
}
else{
pdf = new jsPDF('p', 'px', [height, width]);
}
//then we get the dimensions from the 'pdf' file itself
width = pdf.internal.pageSize.getWidth();
height = pdf.internal.pageSize.getHeight();
pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
pdf.save("download.pdf");
});
Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476
it should be :
$_SERVER['REQUEST_URI'];
Take a look at : Get the full URL in PHP
A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work
$.each(object, function(index, value) {
console.log(value);
});
Another option would be to use vanilla Javascript using the Object.keys()
and the Array .map()
functions like this
Object.keys(object).map(function(objectKey, index) {
var value = object[objectKey];
console.log(value);
});
See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.
But usually, a for-loop doesn't work better than jQuery
or Object.keys().map()
. I'll go into two potential issues with using a plain for-loop below.
Right, so also pointed out in other answers, a plain Javascript alternative would be
for(var index in object) {
var attr = object[index];
}
There are two potential issues with this:
1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty
function like so
for(var index in object) {
if (object.hasOwnProperty(index)) {
var attr = object[index];
}
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.
The jQuery.each
and Object.keys
functions take care of this automatically.
2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log
like this:
<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>
var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) {
if (messagesByButtonId.hasOwnProperty(buttonId)) {
$('#'+buttonId).click(function() {
var message = messagesByButtonId[buttonId];
console.log(message);
});
}
}
If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId]
using the buttonId
variable at that moment. And since the loop has finished at that moment, the buttonId
variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId]
will be messagesByButtonId["button2"]
, i.e. "clicked last!".
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.
Again, jQuery.each
and Object.keys().map()
solve this problem automatically for us, because it provides us with a function(index, value)
(that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.
Here I get only three specific columns from mainDataTable and use the filter
DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");
If you are posting JSON to Django, I think you want request.body
(request.raw_post_data
on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.
Here is an example using JavaScript, jQuery, jquery-json and Django.
JavaScript:
var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
allDay: calEvent.allDay };
$.ajax({
url: '/event/save-json/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: $.toJSON(myEvent),
dataType: 'text',
success: function(result) {
alert(result.Result);
}
});
Django:
def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.body
return HttpResponse("OK")
Django < 1.4:
def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.raw_post_data
return HttpResponse("OK")
In Python you can use (.)\1{9,}
example:
txt = """1. aaaaaaaaaaaaaaa
2. bb
3. cccccccccccccccccccc
4. dd
5. eeeeeeeeeeee"""
rx = re.compile(r'(.)\1{9,}')
lines = txt.split('\n')
for line in lines:
rxx = rx.search(line)
if rxx:
print line
Output:
1. aaaaaaaaaaaaaaa
3. cccccccccccccccccccc
5. eeeeeeeeeeee
NULL
isn't a keyword; it's a macro substitution for 0, and comes in stddef.h
or cstddef
, I believe. You haven't #included
an appropriate header file, so g++ sees NULL
as a regular variable name, and you haven't declared it.
The official RFC which defines this specification could be found here:
http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)
2.1.2. Header Field: From
Description: Mailbox of message author [...] Related information: Specifies the author(s) of the message; that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. Defined as standard by RFC 822.
2.1.3. Header Field: Sender
Description: Mailbox of message sender [...] Related information: Specifies the mailbox of the agent responsible for the actual transmission of the message. Defined as standard by RFC 822.
2.1.22. Header Field: Return-Path
Description: Message return path [...] Related information: Return path for message response diagnostics. See also RFC 2821 [17]. Defined as standard by RFC 822.
This function will reorder your columns without losing data. Any omitted columns remain in the center of the data set:
def reorder_columns(columns, first_cols=[], last_cols=[], drop_cols=[]):
columns = list(set(columns) - set(first_cols))
columns = list(set(columns) - set(drop_cols))
columns = list(set(columns) - set(last_cols))
new_order = first_cols + columns + last_cols
return new_order
Example usage:
my_list = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
reorder_columns(my_list, first_cols=['fourth', 'third'], last_cols=['second'], drop_cols=['fifth'])
# Output:
['fourth', 'third', 'first', 'sixth', 'second']
To assign to your dataframe, use:
my_list = df.columns.tolist()
reordered_cols = reorder_columns(my_list, first_cols=['fourth', 'third'], last_cols=['second'], drop_cols=['fifth'])
df = df[reordered_cols]
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);
You print Float here
, that has no format at all.
To print formatted float, just use
String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);
I konow it's history question now. But for other googlers: you could write something like this. But this requires change in base class what makes it useless with external libraries.
class A
{
void protoX() { Console.WriteLine("x"); }
virtual void X() { protoX(); }
}
class B : A
{
override void X() { Console.WriteLine("y"); }
}
class Program
{
static void Main()
{
A b = new B();
// Call A.X somehow, not B.X...
b.protoX();
}
Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.
So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.
Arslan,
why do you want to force orientation pro grammatically, though there's already a way in manifest
<activity android:name=".youractivityName" android:screenOrientation="portrait" />
Try this:
<div class="row">
<div class="col-md-5">
Set room heater temperature
</div>
<div class="col-md-2"></div>
<div class="col-md-5">
Set room heater temperature
</div>
</div>
Suposse you have
Class1
public class Class1 {
//Your class code above
}
Class2
public class Class2 {
}
and then you can use Class2 in different ways.
Class Field
public class Class1{
private Class2 class2 = new Class2();
}
Method field
public class Class1 {
public void loginAs(String username, String password)
{
Class2 class2 = new Class2();
class2.invokeSomeMethod();
//your actual code
}
}
Static methods from Class2 Imagine this is your class2.
public class Class2 {
public static void doSomething(){
}
}
from class1 you can use doSomething from Class2 whenever you want
public class Class1 {
public void loginAs(String username, String password)
{
Class2.doSomething();
//your actual code
}
}
The simple GUI way, as provided by J Y in a previous answer:
This works well and reminds you of the significance of allocation unit size. But it does have a caveat: as seen in comments to previous answer, Windows will sometimes show "Size on disk" as 0 for a very small file. In my testing, NTFS filesystems with allocation unit size 4096 bytes required the file to be 800 bytes to consistently avoid this issue. On FAT32 file systems this issue seems nonexistent, even a single byte file will work - just not empty.
Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
Here is a code snip to do exactly that.
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
1f, 1f, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(1000);
v.startAnimation(anim);
}
The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...)
.
The other 4 args are for the Y-scaling we do care about.
startScale, endScale
- In your case, you'd use 0f, 0.6f
.
Animation.RELATIVE_TO_SELF, 1f
- This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f
because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f
.
Finally, and equally important, is the call to anim.setFillAfter(true)
. If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.
So in your case, you can do something like this:
View v = findViewById(R.id.viewContainer);
scaleView(v, 0f, .6f);
To offer a little bit more information to other's answers. You have two options regarding how to deliver the .png file to the user. The file structure should conform to the method you choose. The two options are:
Use the module system (import x from y
) provided with react-create-app and bundle it with your JS. Place the image inside the src
folder.
Serve it from the public
folder and let Node serve the file. create-react-app also apparently comes with an environment variable e.g. <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
. This means you can reference it in your React app but still have it served through Node, with your browser asking for it separately in a normal GET request.
Source: create-react-app
if (User.Identity.IsAuthenticated)
{
Page.Title = "Home page for " + User.Identity.Name;
}
else
{
Page.Title = "Home page for guest user.";
}
I would use tel:
(as recommended). But to have a better fallback/not display error pages I would use something like this (using jquery):
// enhance tel-links
$("a[href^='tel:']").each(function() {
var target = "call-" + this.href.replace(/[^a-z0-9]*/gi, "");
var link = this;
// load in iframe to supress potential errors when protocol is not available
$("body").append("<iframe name=\"" + target + "\" style=\"display: none\"></iframe>");
link.target = target;
// replace tel with callto on desktop browsers for skype fallback
if (!navigator.userAgent.match(/(mobile)/gi)) {
link.href = link.href.replace(/^tel:/, "callto:");
}
});
The assumption is, that mobile browsers that have a mobile stamp in the userAgent-string have support for the tel:
protocol. For the rest we replace the link with the callto:
protocol to have a fallback to Skype where available.
To suppress error-pages for the unsupported protocol(s), the link is targeted to a new hidden iframe.
Unfortunately it does not seem to be possible to check, if the url has been loaded successfully in the iframe. It's seems that no error events are fired.
Strings are hard work in C.
#include <stdio.h>
int main()
{
int i;
char buf[12];
for (i = 0; i < 100; i++) {
snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
printf("%s\n", buf); // outputs so you can see it
}
}
The 12
is enough bytes to store the text "pre_"
, the text "_suff"
, a string of up to two characters ("99"
) and the NULL terminator that goes on the end of C string buffers.
This will tell you how to use snprintf
, but I suggest a good C book!
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
Try underscore-cli:
cat myfile.json | underscore print --color
It's a pretty nifty tool that can elegantly do a lot of manipulation of structured data, execute js snippets, fill templates, etc. It's ridiculously well documented, polished, and ready for serious use. And I wrote it. :)
slightly off-topic (using the CLI instead of PHP), but still worth knowing: You can set the prompt to display the default database by using any of the following
mysql --prompt='\d> '
export MYSQL_PS1='\d> '
or once inside
prompt \d>\_
\R \d>\_
IF EXISTS()
is semantically incorrect. EXISTS
condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:
declare
l_exst number(1);
begin
select case
when exists(select ce.s_regno
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1
)
then 1
else 0
end into l_exst
from dual;
if l_exst = 1
then
DBMS_OUTPUT.put_line('YES YOU CAN');
else
DBMS_OUTPUT.put_line('YOU CANNOT');
end if;
end;
Or you can simply use count
function do determine the number of rows returned by the query, and rownum=1
predicate - you only need to know if a record exists:
declare
l_exst number;
begin
select count(*)
into l_exst
from courseoffering co
join co_enrolment ce
on ce.co_id = co.co_id
where ce.s_regno=403
and ce.coe_completionstatus = 'C'
and ce.c_id = 803
and rownum = 1;
if l_exst = 0
then
DBMS_OUTPUT.put_line('YOU CANNOT');
else
DBMS_OUTPUT.put_line('YES YOU CAN');
end if;
end;
An improvement to the most useful answer here:
1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network
There is no need to restart the MySQL server.
use FLUSH PRIVILEGES;
after the update mysql.user statement for password change.
The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.
The --skip-grant-options
enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to
use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.
from: reference: resetting-permissions-generic
As I am explaining later, I would always favor the TryParse
and TryParseExact
methods. Because they are a bit bulky to use, I have written an extension method which makes parsing much easier:
var dtStr = "2011-03-21 13:26";
DateTime? dt = dtStr.ToDate("yyyy-MM-dd HH:mm");
Or more simply, if you want to use the date patterns of your current culture implicitly, you can use it like:
DateTime? dt = dtStr.ToDate();
In that case no specific pattern need to be specified.
Unlike Parse
, ParseExact
etc. it does not throw an exception, and allows you to check via
if (dt.HasValue) { // continue processing } else { // do error handling }
whether the conversion was successful (in this case dt
has a value you can access via dt.Value
) or not (in this case, it is null
).
That even allows to use elegant shortcuts like the "Elvis"-operator ?.
, for example:
int? year = dtStr?.ToDate("yyyy-MM-dd HH:mm")?.Year;
Here you can also use year.HasValue
to check if the conversion succeeded, and if it did not succeed then year
will contain null
, otherwise the year portion of the date. There is no exception thrown if the conversion failed.
Solution: The .ToDate() extension method
public static class Extensions
{
/// <summary>
/// Extension method parsing a date string to a DateTime? <para/>
/// </summary>
/// <param name="dateTimeStr">The date string to parse</param>
/// <param name="dateFmt">dateFmt is optional and allows to pass
/// a parsing pattern array or one or more patterns passed
/// as string parameters</param>
/// <returns>Parsed DateTime or null</returns>
public static DateTime? ToDate(this string dateTimeStr, params string[] dateFmt)
{
// example: var dt = "2011-03-21 13:26".ToDate(new string[]{"yyyy-MM-dd HH:mm",
// "M/d/yyyy h:mm:ss tt"});
// or simpler:
// var dt = "2011-03-21 13:26".ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");
const DateTimeStyles style = DateTimeStyles.AllowWhiteSpaces;
if (dateFmt == null)
{
var dateInfo = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
dateFmt=dateInfo.GetAllDateTimePatterns();
}
var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
style, out var dt) ? dt : null as DateTime?;
return result;
}
}
Some information about the code
You might wonder, why I have used InvariantCulture
calling TryParseExact
: This is to force the function to treat format patterns always the same way (otherwise for example "." could be interpreted as decimal separator in English while it is a group separator or a date separator in German). Recall we have already queried the culture based format strings a few lines before so that is okay here.
Update: .ToDate()
(without parameters) now defaults to all common date/time patterns of the thread's current culture.
Note that we need the result
and dt
together, because TryParseExact
does not allow to use DateTime?
, which we intend to return.
In C# Version 7 you could simplify the ToDate
function a bit as follows:
// in C#7 only: "DateTime dt;" - no longer required, declare implicitly
if (DateTime.TryParseExact(dateTimeStr, dateFmt,
CultureInfo.InvariantCulture, style, out var dt)) result = dt;
or, if you like it even shorter:
// in C#7 only: Declaration of result as a "one-liner" ;-)
var result = DateTime.TryParseExact(dateTimeStr, dateFmt, CultureInfo.InvariantCulture,
style, out var dt) ? dt : null as DateTime?;
in which case you don't need the two declarations DateTime? result = null;
and DateTime dt;
at all - you can do it in one line of code.
(It would also be allowed to write out DateTime dt
instead of out var dt
if you prefer that).
The old style of C# would have required it the following way (I removed that from the code above):
// DateTime? result = null;
// DateTime dt;
// if (DateTime.TryParseExact(dateTimeStr, dateFmt,
// CultureInfo.InvariantCulture, style, out dt)) result = dt;
I have simplified the code further by using the params
keyword: Now you don't need the 2nd overloaded method any more.
Example of usage
var dtStr="2011-03-21 13:26";
var dt=dtStr.ToDate("yyyy-MM-dd HH:mm");
if (dt.HasValue)
{
Console.WriteLine("Successful!");
// ... dt.Value now contains the converted DateTime ...
}
else
{
Console.WriteLine("Invalid date format!");
}
As you can see, this example just queries dt.HasValue
to see if the conversion was successful or not. As an extra bonus, TryParseExact allows to specify strict DateTimeStyles
so you know exactly whether a proper date/time string has been passed or not.
More Examples of usage
The overloaded function allows you to pass an array of valid formats used for parsing/converting dates as shown here as well (TryParseExact
directly supports this), e.g.
string[] dateFmt = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
var dtStr="5/1/2009 6:32 PM";
var dt=dtStr.ToDate(dateFmt);
If you have only a few template patterns, you can also write:
var dateStr = "2011-03-21 13:26";
var dt = dateStr.ToDate("yyyy-MM-dd HH:mm", "M/d/yyyy h:mm:ss tt");
Advanced examples
You can use the ??
operator to default to a fail-safe format, e.g.
var dtStr = "2017-12-30 11:37:00";
var dt = (dtStr.ToDate()) ?? dtStr.ToDate("yyyy-MM-dd HH:mm:ss");
In this case, the .ToDate()
would use common local culture date formats, and if all these failed, it would try to use the ISO standard format "yyyy-MM-dd HH:mm:ss"
as a fallback. This way, the extension function allows to "chain" different fallback formats easily.
You can even use the extension in LINQ, try this out (it's in the .NetFiddle above):
var strDateArray = new[] { "15-01-2019", "15.01.2021" };
var patterns=new[] { "dd-MM-yyyy", "dd.MM.yyyy" };
var dtRange = strDateArray.Select(s => s.ToDate(patterns));
dtRange.Dump();
which will convert the dates in the array on the fly by using the patterns and dump them to the console.
Some background about TryParseExact
Finally, Here are some comments about the background (i.e. the reason why I have written it this way):
I am preferring TryParseExact in this extension method, because you avoid exception handling - you can read in Eric Lippert's article about exceptions why you should use TryParse rather than Parse, I quote him about that topic:2)
This unfortunate design decision1) [annotation: to let the Parse method throw an exception] was so vexing that of course the frameworks team implemented TryParse shortly thereafter which does the right thing.
It does, but TryParse
and TryParseExact
both are still a lot less than comfortable to use: They force you to use an uninitialized variable as an out
parameter which must not be nullable and while you're converting you need to evaluate the boolean return value - either you have to use an if
statement immediately or you have to store the return value in an additional boolean variable so you're able to do the check later. And you can't just use the target variable without knowing if the conversion was successful or not.
In most cases you just want to know whether the conversion was successful or not (and of course the value if it was successful), so a nullable target variable which keeps all the information would be desirable and much more elegant - because the entire information is just stored in one place: That is consistent and easy to use, and much less error-prone.
The extension method I have written does exactly that (it also shows you what kind of code you would have to write every time if you're not going to use it).
I believe the benefit of .ToDate(strDateFormat)
is that it looks simple and clean - as simple as the original DateTime.Parse
was supposed to be - but with the ability to check if the conversion was successful, and without throwing exceptions.
1) What is meant here is that exception handling (i.e. a try { ... } catch(Exception ex) { ...}
block) - which is necessary when you're using Parse because it will throw an exception if an invalid string is parsed - is not only unnecessary in this case but also annoying, and complicating your code. TryParse avoids all this as the code sample I've provided is showing.
2) Eric Lippert is a famous StackOverflow fellow and was working at Microsoft as principal developer on the C# compiler team for a couple of years.
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
JTable source = (JTable)evt.getSource();
int row = source.rowAtPoint( evt.getPoint() );
int column = source.columnAtPoint( evt.getPoint() );
String s=source.getModel().getValueAt(row, column)+"";
JOptionPane.showMessageDialog(null, s);
}
if you want click cell or row in jtable use this way
OPTIONS
method returns info about API (methods/content type)
HEAD
method returns info about resource (version/length/type)
Server response
OPTIONS
HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0
HEAD
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
OPTIONS
Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?HEAD
Checking whether a resource has changed. This is useful when maintaining a cached version of a resourceHEAD
Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrievalHEAD, OPTIONS
Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application
Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.
One of the first differences that I can recall from top of my head are multiple domains running in the same server, partial resource retrieval, this allows you to retrieve and speed up the download of a resource (it's what almost every download accelerator does).
If you want to develop an application like a website or similar, you don't need to worry too much about the differences but you should know the difference between GET
and POST
verbs at least.
Now if you want to develop a browser then yes, you will have to know the complete protocol as well as if you are trying to develop a HTTP server.
If you are only interested in knowing the HTTP protocol I would recommend you starting with HTTP/1.1 instead of 1.0.
If I know for sure in my application that the object is not used in search in any of the list or hash data structure and not used equals method elsewhere except the one used indirectly in hash data structure while adding. Is it advisable to update the existing object in set in equals method. Refer the below code. If I add the this bean to HashSet, I can do group aggregation on the matching object on key (id). By this way I am able to achieve aggregation functions such as sum, max, min, ... as well. If not advisable, please feel free to share me your thoughts.
public class MyBean {
String id,
name;
double amountSpent;
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj!=null && obj instanceof MyBean ) {
MyBean tmpObj = (MyBean) obj;
if(tmpObj.id!=null && tmpObj.id.equals(this.id)) {
tmpObj.amountSpent += this.amountSpent;
return true;
}
}
return false;
}
}
Technically, the char*
is not an array, but a pointer to a char
.
Similarly, char**
is a pointer to a char*
. Making it a pointer to a pointer to a char
.
C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of char
s, or an array of strings.
TreeSet sortedset = new TreeSet();
sortedset.addAll(originalset);
list.addAll(sortedset);
where originalset = unsorted set and list = the list to be returned
Setting the max-width of class tooltip-inner didn´t work for me, I´m using bootstrap 3.2
Some how setting max-width only work if you set the width of parent class (.tooltip).
But then all tooltips become the size you specify. So here´s my solution:
add a Width to the parent class:
.tooltip {
width:400px;
}
Then you add the max-width and change the display to inline-block, so it will not occupy the entire space
.tooltip-inner {
max-width: @tooltip-max-width;
display:inline-block;
}
- http://dev.mysql.com/doc/refman/5.0/en/char.html
Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.
- So ...
< MySQL 5.0.3 use TEXT
or
>= MySQL 5.0.3 use VARCHAR(2083)
If (theChar >= '0' && theChar <='9')
it's a digit. You get the idea.
If you are using .NET Core application, this solution might help!
Moreover this might not be an Angular or other request error in your front end application
First, you have to add the Microsoft CORS Nuget package:
Install-Package Microsoft.AspNetCore.Cors
You then need to add the CORS services in your startup.cs. In your ConfigureServices method you should have something similar to the following:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
Next, add the CORS middleware to your app. In your startup.cs you should have a Configure method. You need to have it similar to this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseCors( options =>
options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseMvc();
}
The options lambda is a fluent API so you can add/remove any extra options you need. You can actually use the option “AllowAnyOrigin” to accept any domain, but I highly recommend you do not do this as it opens up cross origin calls from anyone. You can also limit cross origin calls to their HTTP Method (GET/PUT/POST etc), so you can only expose GET calls cross domain etc.
A shorter alternative to the first solution given by Russ Cam would be:
$('#mySelect').val('');
This assumes you want to retain the list, but make it so that no option is selected.
If you wish to select a particular default value, just pass that value instead of an empty string.
$('#mySelect').val('someDefaultValue');
or to do it by the index of the option, you could do:
$('#mySelect option:eq(0)').attr('selected','selected'); // Select first option
"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True
:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
return some_set == set()
public class SwitCase {
public static void main (String[] args){
String hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello.charAt(0); //get the first char.
switch(hi){
case 'a': System.out.println("a");
}
}
}
When I do this, I get a very small square screen instead of a maxed screen. Yet, when I only use the FormWindowState.Maximized, it does give me a full screen. Why is that?
public partial class Testscherm : Form
{
public Testscherm()
{
this.WindowState = FormWindowState.Maximized;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = this.Size;
this.MaximumSize = this.Size;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
InitializeComponent();
}
foreach (var item in listOfItems) {
if (condition_is_met)
// Any processing you may need to complete here...
break; // return true; also works if you're looking to
// completely exit this function.
}
Should do the trick. The break statement will just end the execution of the loop, while the return statement will obviously terminate the entire function. Judging from your question you may want to use the return true; statement.
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
This is not an answer, really and I would have entered it as a comment had the question not been locked. This answers the question:
Why would you want it?
Assume you have a table with the sequence as the primary key and the sequence is generated by an insert trigger. If you wanted to have the sequence available for subsequent updates to the record, you need to have a way to extract that value.
In order to make sure you get the right one, you might want to wrap the INSERT and RonK's query in a transaction.
RonK's Query:
select MY_SEQ_NAME.currval from DUAL;
In the above scenario, RonK's caveat does not apply since the insert and update would happen in the same session.
If you know the white space is only due to spaces, you can use:
$string = str_replace(' ','',$string);
But if it could be due to space, tab...you can use:
$string = preg_replace('/\s+/','',$string);
This will work:
>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
... title, sequence = match.groups()
... title = title.strip()
... sequence = rx_blanks.sub("",sequence)
... print "Title:",title
... print "Sequence:",sequence
... print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK
Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW
Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)
^
) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).(.+?)\n\n
means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.[A-Z]+\n
means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.((?:
textline)+)
means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.\n
in the regular expression if you want to enforce a double newline at the end.\n
or \r
or \r\n
) then just fix the regular expression by replacing every occurrence of \n
by (?:\n|\r\n?)
.I know this is a really old question, but in case someone is looking for the newer way to do this, use the spring util namespace:
<util:constant static-field="my.pkg.types.MyEnumType.TYPE1" />
As described in the spring documentation.
This works in ksh:
$ alias -x mkcd="mkdir \$dirname; cd \$dirname;"
$ alias mkcd
mkcd='mkdir $dirname; cd $dirname;'
$ dirname=aaa
$ pwd
/tmp
$ mkcd
$ pwd
/tmp/aaa
The "-x" option make the alias "exported" - alias is visible in subshells.
And be aware of fact that aliases defined in a script are not visible in that script (because aliases are expanded when a script is loaded, not when a line is interpreted). This can be solved with executing another script file in same shell (using dot).
So easy way :
XML:
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Java code:
private ViewPager viewPager;
private String[] PAGE_TITLES = new String[]{
"text1",
"text1",
"text3"
};
private final Fragment[] PAGES = new Fragment[]{
new fragment1(),
new fragment2(),
new fragment3()
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_a_requests);
/**TODO ***************tebLayout*************************/
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
tabLayout.setSelectedTabIndicatorHeight((int) (4 *
getResources().getDisplayMetrics().density));
tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"),
Color.parseColor("#0d0e10"));
tabLayout.setupWithViewPager(viewPager);
/***************************************************************************/
}
$('.submit').filter(':checked').each(function() {
//This is same as 'continue'
if(something){
return true;
}
//This is same as 'break'
if(something){
return false;
}
});
Wrap it in an unused function:
.f = function() {
## unwanted code here:
}
I agree with sorting using ORDER BY when populating with a database query, if all you want is to sort the displayed results alphabetically. Let the database engine do the work of sorting.
However, sometimes you want some other sort order besides alphabetical. For example, you might want a logical sequence like: New, Open, In Progress, Completed, Approved, Closed. In that case, you could add a column to the database table to explicitly set the sort order. Name it something like SortOrder or DisplaySortOrder. Then, in your SQL, you'd ORDER BY the sort order field (without retrieving that field).
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
Xcode 10 Swift 4.2
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
let state : UIApplicationState = application.applicationState
if (state == .Inactive || state == .Background) {
// coming from background
} else {
// App is running in foreground
}
}
There is a way of displaying 3 Y axis see here.
Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.
Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.
In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).
Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
SubToBeCalled
End If
End Sub
This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.
Cheers!
I agree that one shouldn't suppress warnings in classes or methods as one could overlook other, accidentally suppressed warnings. But IMHO it's absolutely reasonable to suppress a warning that affects only a single line of code.
@SuppressWarnings("unchecked")
Foo<Bar> mockFoo = mock(Foo.class);
Another alternative:
:call cursor('.',strwidth(getline('.')))
This is may be useful if you're writing a function. Another situation would be when I need to open a specific template and jump to end of first line, I can do:
vi +"call cursor('.',strwidth(getline(1)))" notetaking_template.txt
The above could also be done with
vi +"execute ':normal! $'" notetaking_template.txt
See also:
This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:
The client have two network cards,a wireless one and a normal one.
The ping to server can be succeed.However telnet serverAddress 3306
would fail.
And would complain
Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)
when try to connect to server.So I forbidden the normal network adapters.
And tried telnet serverAddress 3306
it works.And then it work when connect to MySQL server.
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });
Forked @http://jsfiddle.net/QVJXD/
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
}
}
then see this link link
The order of a dictionary doesn't have any relationship to the order it was defined in. This is true of all dictionaries, not just those turned into JSON.
>>> {"b": 1, "a": 2}
{'a': 2, 'b': 1}
Indeed, the dictionary was turned "upside down" before it even reached json.dumps
:
>>> {"id":1,"name":"David","timezone":3}
{'timezone': 3, 'id': 1, 'name': 'David'}
It can be done without the use of View State or Session. Current order can be determined based on value in first and last row in the column we sort by:
protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)
{
GridView grid = sender as GridView; // get reference to grid
SortDirection currentSortDirection = SortDirection.Ascending; // default order
// get column index by SortExpression
int columnIndex = grid.Columns.IndexOf(grid.Columns.OfType<DataControlField>()
.First(x => x.SortExpression == e.SortExpression));
// sort only if grid has more than 1 row
if (grid.Rows.Count > 1)
{
// get cells
TableCell firstCell = grid.Rows[0].Cells[columnIndex];
TableCell lastCell = grid.Rows[grid.Rows.Count - 1].Cells[columnIndex];
// if field type of the cell is 'TemplateField' Text property is always empty.
// Below assumes that value is binded to Label control in 'TemplateField'.
string firstCellValue = firstCell.Controls.Count == 0 ? firstCell.Text : ((Label)firstCell.Controls[1]).Text;
string lastCellValue = lastCell.Controls.Count == 0 ? lastCell.Text : ((Label)lastCell.Controls[1]).Text;
DateTime tmpDate;
decimal tmpDecimal;
// try to determinate cell type to ensure correct ordering
// by date or number
if (DateTime.TryParse(firstCellValue, out tmpDate)) // sort as DateTime
{
currentSortDirection =
DateTime.Compare(Convert.ToDateTime(firstCellValue),
Convert.ToDateTime(lastCellValue)) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
else if (Decimal.TryParse(firstCellValue, out tmpDecimal)) // sort as any numeric type
{
currentSortDirection = Decimal.Compare(Convert.ToDecimal(firstCellValue),
Convert.ToDecimal(lastCellValue)) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
else // sort as string
{
currentSortDirection = string.CompareOrdinal(firstCellValue, lastCellValue) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
}
// then bind GridView using correct sorting direction (in this example I use Linq)
if (currentSortDirection == SortDirection.Descending)
{
grid.DataSource = myItems.OrderBy(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
}
else
{
grid.DataSource = myItems.OrderByDescending(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
}
grid.DataBind();
}
change x to 1 and output is integer, else its not an integer add to count example whole numbers, decimal numbers etc.
double x = 1.1;
int count = 0;
if (x == (int)x)
{
System.out.println("X is an integer: " + x);
count++;
System.out.println("This has been added to the count " + count);
}else
{
System.out.println("X is not an integer: " + x);
System.out.println("This has not been added to the count " + count);
}
var string = 123 (is string),
parseInt(parameter is string);
var string = '123';
var int= parseInt(string );
console.log(int); //Output will be 123.
Firstly a quick recap on RSA key generation.
The public key consists of the modulus and the public exponent.
A minimal private key would consist of the modulus and the private exponent. There is no computationally feasible surefire way to go from a known modulus and private exponent to the corresponding public exponent.
However:
So in most practical RSA implementations you can get the public key from the private key. It would be possible to build a RSA based cryptosystem where this was not possible, but it is not the done thing.
I guess Simple solution to this will be:
//X.h
#pragma once
class X
{
public:
X(void);
~X(void);
private:
static bool IsInit;
static bool Init();
};
//X.cpp
#include "X.h"
#include <iostream>
X::X(void)
{
}
X::~X(void)
{
}
bool X::IsInit(Init());
bool X::Init()
{
std::cout<< "ddddd";
return true;
}
// main.cpp
#include "X.h"
int main ()
{
return 0;
}
For those of you who are popping up a new window to print from, and then automatically closing it after the user clicks "Print" or "Cancel" on the Chrome print preview, I used the following (thanks to the help from PaulVB's answer):
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var showPopup = false;
window.onbeforeunload = function () {
if (showPopup) {
return 'You must use the Cancel button to close the Print Preview window.\n';
} else {
showPopup = true;
}
}
window.print();
window.close();
} else {
window.print();
window.close();
}
I am debating if it would be a good idea to also filter by the version of Chrome...
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.
They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.
import sys
try:
# your code here
except Exception as err:
print("Error: " + str(err))
sys.exit(50) # whatever non zero exit code
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
The accepted answer gave me node 0.10.36 and npm 1.3.6 which are very out of date. I grabbed the latest linux-x64 tarball from the nodejs downloads page and it wasn't too difficult to install: https://nodejs.org/dist/latest/.
# start in a directory where you like to install things for the current user
(For noobs : it downloads node package as node.tgz file in your directlry)
curl (paste the link to the one you want from the downloads page) >node.tgz
Now upzip the tar you just downloaded -
tar xzf node.tgz
Run this command and then also add it to your .bashrc
:
export PATH="$PATH:(your install dir)/(node dir)/bin"
(example : export PATH ="$PATH:/home/ec2-user/mydirectory/node/node4.5.0-linux-x64/bin")
And update npm
(only once, don't add to .bashrc
):
npm install -g npm
Note that the -g
there which means global, really means global to that npm instance which is the instance we just installed and is limited to the current user. This will apply to all packages that npm installs 'globally'.
Only <
and &
are required to be escaped if they are to be treated character data and not markup:
It is better to add new Maven repository (preferably using your own artifactory) to your project instead of installing it to your local repository.
Maven syntax:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
...
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
Grails example:
mavenRepo "https://code.lds.org/nexus/content/groups/main-repo"
build 'com.oracle:ojdbc6:11.2.0.3'
I faced the same issue. Tried adding the US_export_policy.jar
and local_policy.jar
in the java security folder first but the issue persisted. Then added the below in java_opts
inside tomcat setenv.sh
file and it worked.
-Djdk.tls.ephemeralDHKeySize=2048
Please check this link for further info
I had the same problem and this is my solution. I had the following code:
se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);
And I changed it to:
se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");
And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.
I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/"
, for example, I kept getting "This localhost page can't be found"
in the browser.
I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/"
as changing it to appBase="C:/Java Project/ROOT"
will cause "This localhost page can't be found"
to be displayed again.
Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.