In cell D2 and copied down:
=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))
MySQL has a short description of their more or less strict rules:
https://dev.mysql.com/doc/internals/en/coding-style.html
Most common codingstyle for MySQL by Simon Holywell:
See also this question: Are there any published coding style guidelines for SQL?
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
For me, this worked:
rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");
Tip: use regex tester for quick testing without compiling in your environment
flexbox can help you. info here
<div class="d-flex flex-row justify-content-center align-items-center" style="height: 100px;">
<div class="p-2">
1
</div>
<div class="p-2">
2
</div>
</div>
All notifications (even other app notifications) can be removed via listening to 'NotificationListenerService' as mentioned in NotificationListenerService Implementation
In the service you have to call cancelAllNotifications()
.
The service has to be enabled for your application via:
‘Apps & notifications’ -> ‘Special app access’ -> ‘Notifications access’.
Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:
resources :articles do
resources :comments
end
You get paths like:
/articles/42
/articles/42/comments/99
routed to controllers at
app/controllers/articles_controller.rb
app/controllers/comments_controller.rb
just as it says at http://guides.rubyonrails.org/routing.html#nested-resources, with no special namespaces.
But partials and forms become tricky. Note the square brackets:
<%= form_for [@article, @comment] do |f| %>
Most important, if you want a URI, you may need something like this:
article_comment_path(@article, @comment)
Alternatively:
[@article, @comment]
as described at http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects
For example, inside a collections partial with comment_item
supplied for iteration,
<%= link_to "delete", article_comment_path(@article, comment_item),
:method => :delete, :confirm => "Really?" %>
What jamuraa says may work in the context of Article, but it did not work for me in various other ways.
There is a lot of discussion related to nested resources, e.g. http://weblog.jamisbuck.org/2007/2/5/nesting-resources
Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:
# POST /comments
post :create, :comment => {:article_id=>42, ...}
In order to test the route that they may prefer, they need to do it this way:
# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}
I learned this because my unit-tests started failing when I switched from this:
resources :comments
resources :articles do
resources :comments
end
to this:
resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:
resources :comments
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
Sorry for the long answer. Not many people are aware of the subtleties, I think.
Here's the map solution:
#include <iostream>
#include <map>
typedef std::map<char, char> BasePairMap;
int main()
{
BasePairMap m;
m['A'] = 'T';
m['T'] = 'A';
m['C'] = 'G';
m['G'] = 'C';
std::cout << "A:" << m['A'] << std::endl;
std::cout << "T:" << m['T'] << std::endl;
std::cout << "C:" << m['C'] << std::endl;
std::cout << "G:" << m['G'] << std::endl;
return 0;
}
Just for the sake of completeness, since I noticed no one suggested this simple approach:
>>> print("%.0f%%" % (100 * 1.0/3))
33%
Details:
%.0f
stands for "print a float with 0 decimal places", so %.2f
would print 33.33
%%
prints a literal %
. A bit cleaner than your original +'%'
1.0
instead of 1
takes care of coercing the division to float, so no more 0.0
You could use:
^(mailto|ftp|joe)
But to be honest, StartsWith
is perfectly fine to here. You could rewrite it as follows:
string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));
You could also look at the System.Uri
class if you are parsing URIs.
Just try to re-create connection. In my situation one of jdbc connection stopped working for no reason. From console sqlplus was working ok. It took me 2 hours to realize that If i create the same connection - it works.
Use SpannableStringBuilder
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);
SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);
There is an option in WinSCP that does exactly what you are looking for:
You would need to use position:relative
or position:absolute
on both the parent and child to use z-index
.
This is a very broad question, so I am going to give a broad answer.
That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.
Just some testing about it:
public class PrimitiveTypesV2 {
public static void main (String[] args) {
Class typesList[] = {
Boolean.class , Byte.class, Character.class, Short.class, Integer.class,
Long.class, Float.class, Double.class, Boolean.TYPE, Byte.TYPE, Character.TYPE,
Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE
};
try {
for ( Class type : typesList ) {
if (type.isPrimitive()) {
System.out.println("Primitive type:\t" + type);
}
else {
boolean hasSize = false;
java.lang.reflect.Field fields[] = type.getFields();
for (int count=0; count<fields.length; count++) {
if (fields[count].getName().contains("SIZE")) hasSize = true;
}
if (hasSize) {
System.out.println("Bits size of type " + type + " :\t\t\t" + type.getField("SIZE").getInt(type) );
double value = type.getField("MIN_VALUE").getDouble(type);
long longVal = Math.round(value);
if ( (value - longVal) == 0) {
System.out.println("Min value for type " + type + " :\t\t" + longVal );
longVal = Math.round(type.getField("MAX_VALUE").getDouble(type));
System.out.println("Max value for type " + type + " :\t\t" + longVal );
}
else {
System.out.println("Min value for type " + type + " :\t\t" + value );
value = type.getField("MAX_VALUE").getDouble(type);
System.out.println("Max value for type " + type + " :\t\t" + value );
}
}
else {
System.out.println(type + "\t\t\t type without SIZE field.");
}
} // if not primitive
} // for typesList
} catch (Exception e) {e.printStackTrace();}
} // main
} // class PrimitiveTypes
To clarify for future reference, a2enmod, as is suggested in several answers above, is for Debian/Ubuntu. Red Hat does not use this to enable Apache modules - instead it uses LoadModule statements in httpd.conf.
The resolution/correct answer is in the comments on the OP:
I think you need mod_ssl and SSLProxyEngine with ProxyPass – Deadooshka May 29 '14 at 11:35
@Deadooshka Yes, this is working. If you post this as an answer, I can accept it – das_j May 29 '14 at 12:04
i wanted to ask if Android Devices uses the network time protocol (ntp) to synchronize the time.
For general time synchronization, devices with telephony capability, where the wireless provider provides NITZ information, will use NITZ. My understanding is that NTP is used in other circumstances: NITZ-free wireless providers, WiFi-only, etc.
Your cited blog post suggests another circumstance: on-demand time synchronization in support of GPS. That is certainly conceivable, though I do not know whether it is used or not.
Syntax
Here
function printBye(message1, message2){_x000D_
console.log(message1 + " " + this.name + " "+ message2);_x000D_
}_x000D_
_x000D_
var par01 = { name:"John" };_x000D_
var msgArray = ["Bye", "Never come again..."];_x000D_
_x000D_
printBye.call(par01, "Bye", "Never come again...");_x000D_
//Bye John Never come again..._x000D_
_x000D_
printBye.call(par01, msgArray);_x000D_
//Bye,Never come again... John undefined_x000D_
_x000D_
//so call() doesn't work with array and better with comma seperated parameters _x000D_
_x000D_
//printBye.apply(par01, "Bye", "Never come again...");//Error_x000D_
_x000D_
printBye.apply(par01, msgArray);_x000D_
//Bye John Never come again..._x000D_
_x000D_
var func1 = printBye.bind(par01, "Bye", "Never come again...");_x000D_
func1();//Bye John Never come again..._x000D_
_x000D_
var func2 = printBye.bind(par01, msgArray);_x000D_
func2();//Bye,Never come again... John undefined_x000D_
//so bind() doesn't work with array and better with comma seperated parameters
_x000D_
This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.
I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.
On your exampe I would like to do this setup:
$ch = curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);
This request will return data in 0.10 second max
Here is my approach, clunky as it is and available in github:
Put in the very first notebook cell, the import cell:
from IPythonTOC import IPythonTOC
toc = IPythonTOC()
Somewhere after the import cell, put in the genTOCEntry cell but don't run it yet:
''' if you called toc.genTOCMarkdownCell before running this cell,
the title has been set in the class '''
print toc.genTOCEntry()
Below the genTOCEntry cell`, make a TOC cell as a markdown cell:
<a id='TOC'></a>
#TOC
As the notebook is developed, put this genTOCMarkdownCell before starting a new section:
with open('TOCMarkdownCell.txt', 'w') as outfile:
outfile.write(toc.genTOCMarkdownCell('Introduction'))
!cat TOCMarkdownCell.txt
!rm TOCMarkdownCell.txt
Move the genTOCMarkdownCell down to the point in your notebook where you want to start a new section and make the argument to genTOCMarkdownCell the string title for your new section then run it. Add a markdown cell right after it and copy the output from genTOCMarkdownCell into the markdown cell that starts your new section. Then go to the genTOCEntry cell near the top of your notebook and run it. For example, if you make the argument to genTOCMarkdownCell as shown above and run it, you get this output to paste into the first markdown cell of your newly indexed section:
<a id='Introduction'></a>
###Introduction
Then when you go to the top of your notebook and run genTocEntry, you get the output:
[Introduction](#Introduction)
Copy this link string and paste it into the TOC markdown cell as follows:
<a id='TOC'></a>
#TOC
[Introduction](#Introduction)
After you edit the TOC cell to insert the link string and then you press shift-enter, the link to your new section will appear in your notebook Table of Contents as a web link and clicking it will position the browser to your new section.
One thing I often forget is that clicking a line in the TOC makes the browser jump to that cell but doesn't select it. Whatever cell was active when we clicked on the TOC link is still active, so a down or up arrow or shift-enter refers to still active cell, not the cell we got by clicking on the TOC link.
I like your question, regardless of whether it's off topic or not :P
An interesting aside; I've just completed a subject in my degree where we covered robotics and computer vision. Our project for the semester was incredibly similar to the one you describe.
We had to develop a robot that used an Xbox Kinect to detect coke bottles and cans on any orientation in a variety of lighting and environmental conditions. Our solution involved using a band pass filter on the Hue channel in combination with the hough circle transform. We were able to constrain the environment a bit (we could chose where and how to position the robot and Kinect sensor), otherwise we were going to use the SIFT or SURF transforms.
You can read about our approach on my blog post on the topic :)
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
A more complicated way :) that emulates SQL's 'IN':
public static class Ext {
public static bool In<T>(this T t,params T[] values){
foreach (T value in values) {
if (t.Equals(value)) {
return true;
}
}
return false;
}
}
if (value.In(1,2)) {
// ...
}
But go for the standard way, it's more readable.
EDIT: a better solution, according to @Kobi's suggestion:
public static class Ext {
public static bool In<T>(this T t,params T[] values){
return values.Contains(t);
}
}
"put" has been deprecated, refrain from using it, use .of instead
ImmutableMap<String, String> myMap = ImmutableMap.of(
"city1", "Seattle",
"city2", "Delhi"
);
Try this way:
<td><a href="..." style="display:block;"> </a></td>
This answer has 20 upvotes now, but it is not intended as an endorsement of std::valarray
.
In my experience, time is better spent installing and learning to use a full-fledged math library such as Eigen. Valarray has fewer features than the competition, but it isn't more efficient or particularly easier to use.
If you only need a little bit of linear algebra, and you are dead-set against adding anything to your toolchain, then maybe valarray
would fit. But, being stuck unable to express the mathematically correct solution to your problem is a very bad position to be in. Math is relentless and unforgiving. Use the right tool for the job.
The standard library provides std::valarray<double>
. std::vector<>
, suggested by a few others here, is intended as a general-purpose container for objects. valarray
, lesser known because it is more specialized (not using "specialized" as the C++ term), has several advantages:
vector
rounds up to the nearest power of two when allocating, so you can resize it without reallocating every time. (You can still resize a valarray
; it's just still as expensive as realloc()
.)Of course, the advantage over using C is that you don't need to manage memory. The dimensions can reside on the stack, or in a slice object.
std::valarray<double> matrix( row * col ); // no more, no less, than a matrix
matrix[ std::slice( 2, col, row ) ] = pi; // set third column to pi
matrix[ std::slice( 3*row, row, 1 ) ] = e; // set fourth row to e
If you already require JQuery, this solution might do the work (this is the exact same code I actually needed in my case, although using a Promise is just to force the code to wait until file selection has been resolved):
await new Promise(resolve => {
const input = $("<input type='file'/>");
input.on('change', function() {
resolve($(this).val());
});
$('body').one('focus', '*', e => {
resolve(null);
e.stopPropagation();
});
input.click();
});
Take a closer look at the ?axis
documentation. If you look at the description of the labels
argument, you'll see that it is:
"a logical value specifying whether (numerical) annotations are
to be made at the tickmarks,"
So, just change it to true, and you'll get your tick labels.
x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)
Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.
It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis
into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.
"copysign" is defined by IEEE 754, and part of the C99 specification. That's why it's in Python. The function cannot be implemented in full by abs(x) * sign(y) because of how it's supposed to handle NaN values.
>>> import math
>>> math.copysign(1, float("nan"))
1.0
>>> math.copysign(1, float("-nan"))
-1.0
>>> math.copysign(float("nan"), 1)
nan
>>> math.copysign(float("nan"), -1)
nan
>>> float("nan") * -1
nan
>>> float("nan") * 1
nan
>>>
That makes copysign() a more useful function than sign().
As to specific reasons why IEEE's signbit(x) is not available in standard Python, I don't know. I can make assumptions, but it would be guessing.
The math module itself uses copysign(1, x) as a way to check if x is negative or non-negative. For most cases dealing with mathematical functions that seems more useful than having a sign(x) which returns 1, 0, or -1 because there's one less case to consider. For example, the following is from Python's math module:
static double
m_atan2(double y, double x)
{
if (Py_IS_NAN(x) || Py_IS_NAN(y))
return Py_NAN;
if (Py_IS_INFINITY(y)) {
if (Py_IS_INFINITY(x)) {
if (copysign(1., x) == 1.)
/* atan2(+-inf, +inf) == +-pi/4 */
return copysign(0.25*Py_MATH_PI, y);
else
/* atan2(+-inf, -inf) == +-pi*3/4 */
return copysign(0.75*Py_MATH_PI, y);
}
/* atan2(+-inf, x) == +-pi/2 for finite x */
return copysign(0.5*Py_MATH_PI, y);
There you can clearly see that copysign() is a more effective function than a three-valued sign() function.
You wrote:
If I were a python designer, I would been the other way around: no cmp() builtin, but a sign()
That means you don't know that cmp() is used for things besides numbers. cmp("This", "That") cannot be implemented with a sign() function.
Edit to collate my additional answers elsewhere:
You base your justifications on how abs() and sign() are often seen together. As the C standard library does not contain a 'sign(x)' function of any sort, I don't know how you justify your views. There's an abs(int) and fabs(double) and fabsf(float) and fabsl(long) but no mention of sign. There is "copysign()" and "signbit()" but those only apply to IEEE 754 numbers.
With complex numbers, what would sign(-3+4j) return in Python, were it to be implemented? abs(-3+4j) return 5.0. That's a clear example of how abs() can be used in places where sign() makes no sense.
Suppose sign(x) were added to Python, as a complement to abs(x). If 'x' is an instance of a user-defined class which implements the __abs__(self) method then abs(x) will call x.__abs__(). In order to work correctly, to handle abs(x) in the same way then Python will have to gain a sign(x) slot.
This is excessive for a relatively unneeded function. Besides, why should sign(x) exist and nonnegative(x) and nonpositive(x) not exist? My snippet from Python's math module implementation shows how copybit(x, y) can be used to implement nonnegative(), which a simple sign(x) cannot do.
Python should support have better support for IEEE 754/C99 math function. That would add a signbit(x) function, which would do what you want in the case of floats. It would not work for integers or complex numbers, much less strings, and it wouldn't have the name you are looking for.
You ask "why", and the answer is "sign(x) isn't useful." You assert that it is useful. Yet your comments show that you do not know enough to be able to make that assertion, which means you would have to show convincing evidence of its need. Saying that NumPy implements it is not convincing enough. You would need to show cases of how existing code would be improved with a sign function.
And that it outside the scope of StackOverflow. Take it instead to one of the Python lists.
Download the appropriate APR based tomcat native library for your operating system so that Apache tomcat server can take some advantage of the feature of your OS which is not included by default in tomcat. For windows it will be a .dll
file.
I too got the warning while starting the server and you don't have to worry about this if you are testing or developing. This is meant to be on production purposes. After putting the tcnative-1.dll file inside the bin folder of Apache Tomcat 7 following are the output in the stderr file,
Apr 07, 2015 1:14:12 PM org.apache.catalina.core.AprLifecycleListener init
INFO: Loaded APR based Apache Tomcat Native library 1.1.33 using APR version 1.5.1.
Apr 07, 2015 1:14:12 PM org.apache.catalina.core.AprLifecycleListener init
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
Apr 07, 2015 1:14:14 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized (OpenSSL 1.0.1m 19 Mar 2015)
Apr 07, 2015 1:14:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-apr-127.0.0.1"]
just use php composer.phar require
For example :
php composer.phar require doctrine/mongodb-odm-bundle 3.0
Also available with install.
https://getcomposer.org/doc/03-cli.md#require https://getcomposer.org/doc/03-cli.md#install
Never faced this problem before (not worked much on email, I avoid it like the plague) but you could try declaring the bullet with the unicode code point (different notation for CSS than for HTML): content: '\2022'
. (you need to use the hex number, not the 8226 decimal one)
Then, in case you use something that picks up those characters and HTML-encodes them into entities (which won't work for CSS strings), I guess it will ignore that.
Sometimes Excel will hiccup and needs a kick-start to reapply an equation. This happens in some cases when you are using custom formulas.
Make sure that you have the following script
ActiveSheet.EnableCalculation = True
Reapply the equation of choice.
Cells(RowA,ColB).Formula = Cells(RowA,ColB).Formula
This can then be looped as needed.
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
I think everyone missed the "suddenly" part of this question. Most likely, your .jshintrc has a syntax error, so it's not including the 'browser' line. Run it through a json validator to see where the error is.
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
Docker might have lost the authentication data. So you'll have to reauthenticate with your registry provider. With AWS for example:
aws ecr get-login --region us-west-2 --no-include-email
And then copy and paste that resulting "docker login..." to authenticated docker.
Source: Amazon ECR Registeries
So, let me give you sample code:
<div class="news">
Blah, blah, blah. I'm hidden.
</div>
<a class="trigger">Hide/Show News</a>
The link will be the trigger to show the div when clicked. So your Javascript will be:
$('.trigger').click(function() {
$('.news').toggle();
});
You're almost always better off letting jQuery handle the styling for hiding and showing elements.
Edit: I see people above are recommending using .show
and .hide
for this. .toggle
allows you to do both with just one effect. So that's cool.
If you only care about strings, objects, and arrays:
function objectToString (obj) {
var str = '';
var i=0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(typeof obj[key] == 'object')
{
if(obj[key] instanceof Array)
{
str+= key + ' : [ ';
for(var j=0;j<obj[key].length;j++)
{
if(typeof obj[key][j]=='object') {
str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
}
else
{
str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
}
}
str+= ']' + (i > 0 ? ',' : '')
}
else
{
str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
}
}
else {
str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
}
i++;
}
}
return str;
}
I guess you could use curl
and wget
, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.
Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx
, a text based browser.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
The JUnit assertEquals(obj1, obj2)
does indeed call obj1.equals(obj2)
.
There's also assertSame(obj1, obj2)
which does obj1 == obj2
(i.e., verifies that obj1
and obj2
are referencing the same instance), which is what you're trying to avoid.
So you're fine.
Your style should look like this:
<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
<item name="android:indeterminateDrawable">@anim/mp3</item>
</style>
If you don't want to use float, the easiest and cleanest way to do it is by using an auto width column:
<div class="row">
<div class="col">
<h3 class="one">Text</h3>
</div>
<div class="col-auto">
<button class="btn btn-secondary pull-right">Button</button>
</div>
</div>
I like to use np.vectorize
for such tasks. Consider the following:
>>> # function which returns True when constraints are satisfied.
>>> func = lambda d: d >= r and d<= (r+dr)
>>>
>>> # Apply constraints element-wise to the dists array.
>>> result = np.vectorize(func)(dists)
>>>
>>> result = np.where(result) # Get output.
You can also use np.argwhere
instead of np.where
for clear output. But that is your call :)
Hope it helps.
The code you've shown will read 8 bytes. You could use
with open(filename, 'rb') as f:
while 1:
byte_s = f.read(1)
if not byte_s:
break
byte = byte_s[0]
...
When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.
From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :
int myInt = new Integer(11);
Integer myInt2 = myInt;
The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long
,Double
,Short
too)
You may use int
all the time, but Integer
contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String)
)
string result = Path.GetTempPath();
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.
In JavaScript functions are objects.
document.getElementById('foo').onclick = function(){
prompt('Hello world');
}
Try using TabulaPDF (https://github.com/tabulapdf/tabula) . This is very good library to extract table content from the PDF file. It is very as expected.
Good luck. :)
Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();
foreach(string key in keys) {
if(!dictionary.ContainsKey(key)) {
//add
dictionary.Add(key, new List<string>());
}
dictionary[key].Add("theString");
}
If the key doesn't exist, a new List
is added (inside if). Else the key exists, so just add a new value to the List
under that key.
Using Alt + Shift + o It works for me!
Step-by-Step way to do this:
you can also try lsblk ... is in util-linux ... but i have a question too
fdisk -l /dev/sdl
no result
grep sdl /proc/partitions
8 176 15632384 sdl
8 177 15628288 sdl1
lsblk | grep sdl
sdl 8:176 1 14.9G 0 disk
`-sdl1 8:177 1 14.9G 0 part
fdisk is good but not that good ... seems like it cannot "see" everything
in my particular example i have a stick that have also a card reader build in it and i can see only the stick using fdisk:
fdisk -l /dev/sdk
Disk /dev/sdk: 15.9 GB, 15931539456 bytes
255 heads, 63 sectors/track, 1936 cylinders, total 31116288 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xbe24be24
Device Boot Start End Blocks Id System
/dev/sdk1 * 8192 31116287 15554048 c W95 FAT32 (LBA)
but not the card (card being /dev/sdl)
also, file -s is inefficient ...
file -s /dev/sdl1
/dev/sdl1: sticky x86 boot sector, code offset 0x52, OEM-ID "NTFS ", sectors/cluster 8, reserved sectors 0, Media descriptor 0xf8, heads 255, hidden sectors 8192, dos < 4.0 BootSector (0x0)
that's nice ... BUT
fdisk -l /dev/sdb
/dev/sdb1 2048 156301487 78149720 fd Linux raid autodetect
/dev/sdb2 156301488 160086527 1892520 82 Linux swap / Solaris
file -s /dev/sdb1
/dev/sdb1: sticky \0
to see information about a disk that cannot be accesed by fdisk, you can use parted:
parted /dev/sdl print
Model: Mass Storage Device (scsi)
Disk /dev/sdl: 16.0GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 4194kB 16.0GB 16.0GB primary ntfs
arted /dev/sdb print
Model: ATA Maxtor 6Y080P0 (scsi)
Disk /dev/sdb: 82.0GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 1049kB 80.0GB 80.0GB primary raid
2 80.0GB 82.0GB 1938MB primary linux-swap(v1)
There are a few MongoDB GUIs out there, some of them have built-in support for data exporting. You'll find a comprehensive list of MongoDB GUIs at http://mongodb-tools.com
You've asked about exporting the results of your query, and not about exporting entire collections. Give 3T MongoChef MongoDB GUI a try, this tool has support for your specific use case.
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
String extends Object, which means an Object. Object o = a;
If you really want to get as Object, you may do like below.
String s = "Hi";
Object a =s;
To use this function/method,you need an instance of the class Date .
This method is always used in conjunction with a Date object.
See the code below :
var d = new Date();
d.getTime();
SQL Developer provides this functionality too :
Double click the results grid cell, and click edit :
Then on top-right part of the pop up , "View As Text" (You can even see images..)
And that's it!
Yes, it is very Simple. Just Put your Code Inside this:
<androidx.core.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
//YOUR CODE
</androidx.core.widget.NestedScrollView>
A little clearer... A software program that has kernel mode access has total access to all of the computer's data and its hardware.
Since Windows Vista Microsoft has stopped any and all I/O processes from accessing the kernel (ring 0) directly ever again. The closest we get is a folder created as a virtual kernel access partition, but technically no access to kernel itself; the kernel meets halfway.
This is because the software itself dictates which token to use, so if it asks for an administrator access token, instead of just allowing communications with the kernel like on Windows XP you are prompted to allow access to the kernel, each and every time. Changing UAC could reduce prompts, but never the kernel prompts.
Even when you login as an Administrator, you are running processes as a standard user until prompted to elevate the rights you have. I believe logged in as the administrator saves you from entering the credentials. But it also writes to the administrator users folder structure.
Kernel access is similar to root access in Linux. When you elevate your permissions you are isolating yourself from the root of C:\ and whatever lovely environment variables are contained within.
If you remember BSODs this was the OS shutting down when it believed a bad I/O reached the kernel.
You can reset settings for eclipse by deleting .metadata folder from your current workspace.
This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.
You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".
There is also Math.DivRem
quotient = Math.DivRem(dividend, divisor, out remainder);
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).
There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".
I wrote this test that keeps on adding 'a'
to parameter until the browser fails
C# part:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ParamTest(string x)
{
ViewBag.TestLength = 0;
if (!string.IsNullOrEmpty(x))
{
System.IO.File.WriteAllLines("c:/result.txt",
new[] {Request.UserAgent, x.Length.ToString()});
ViewBag.TestLength = x.Length + 1;
}
return View();
}
View:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var text = "a";
for (var i = 0; i < parseInt(@ViewBag.TestLength)-1; i++) {
text += "a";
}
document.location.href = "http://localhost:50766/Home/ParamTest?x=" + text;
});
</script>
PART 1
On Chrome I got:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
2046
It then blew up with:
HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.
Same on Internet Explorer 8 and Firefox
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
2046
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
2046
PART 2
I went easy mode and added additional limits to IISExpress applicationhost.config
and web.config
setting maxQueryStringLength="32768"
.
Chrome failed with message 'Bad Request - Request Too Long
HTTP Error 400. The size of the request headers is too long.
after 7744 characters.
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
7744
PART 3
<headerLimits>
<add header="Content-type" sizeLimit="32768" />
</headerLimits>
which didn't help at all. I finally decided to use fiddler to remove the referrer from header.
static function OnBeforeRequest(oSession: Session) {
if (oSession.url.Contains("localhost:50766")) {
oSession.RequestHeaders.Remove("Referer");
}
Which did nicely.
Chrome: got to 15613 characters. (I guess it's a 16K limit for IIS)
And it failed again with:
<BODY><h2>Bad Request - Request Too Long</h2>
<hr><p>HTTP Error 400. The size of the request headers is too long.</p>
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
15613
Firefox:
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
15708
Internet Explorer 8 failed with iexplore.exe crashing.
After 2505
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
2505
Android Emulator
Mozilla/5.0 (Linux; Android 5.1; Android SDK built for x86 Build/LKY45) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36
7377
Internet Explorer 11
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
4043
Internet Explorer 10
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
4043
Internet Explorer 9
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
4043
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View
{
Paint paint = null;
public MyView(Context context)
{
super(context);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
}
}
Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using
canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);
These two link also help
http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o
http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html
To stop Jenkins Please avoid shutting down the Java process or the Windows service. These are not usual commands. Use those only if your Jenkins is causing problems.
Use Jenkins' way to stop that protects from data loss.
http://[jenkins-server]/[command]
where [command] can be any one of the following
Example: if my local PC is running Jenkins at port 8080, it will be
http://localhost:8080/exit
Check out jasypt, which is a library offering basic encryption capabilities with minimum effort.
One path to take is to
Use the resource loader to locate the file:
URL url = Test.class.getClassLoader().getResource("myfile.txt");
System.out.println(url.getPath());
...
List<string> values =new list<string>();
foreach(ListItem Item in ChkList.Item)
{
if(Item.Selected)
values.Add(item.Value);
}
When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware
and InitializingBean
. If they are found, the methods are invoked. E.g. (very simplified)
Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(ctx);
}
Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:
@Inject // or @Autowired
private ApplicationContext ctx;
Just:
myfile = open(filename)
onecaracter = myfile.read(1)
Follow these steps to connect with SQL Server 2008 r2 (windows authentication)
Step 1: Goto Control Panel --> Administrator Tools --> Services select SQL SERVER (MSSQLSERVER) and double click on it
Step 2: Click on start Service
Step 3: Now login to SQL server with Windows authentication and use user name : (local)
Enjoy ...
I accidentally ran our (largeish) application on a 64bit VM rather than a 32bit VM and didn't notice until some external libraries (called by JNI) started failing.
Data serialized on a 32bit platform was read in on the 64bit platform with no issues at all.
What sort of issues are you getting? Do some things work and not others? Have you tried attaching JConsole etc and have a peak around?
If you have a very big VM you may find that GC issues in 64 bit can affect you.
CodeIgniter file upload optionally ...works perfectly..... :)
---------- controller ---------
function file()
{
$this->load->view('includes/template', $data);
}
function valid_file()
{
$this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');
if ($this->form_validation->run()==FALSE)
{
$this->file();
}
else
{
$config['upload_path'] = './documents/';
$config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile',FALSE))
{
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if($_FILES['userfile']['error'] != 4)
{
return false;
}
}
else
{
return true;
}
}
i just use this lines which makes it optionally,
if($_FILES['userfile']['error'] != 4)
{
return false;
}
$_FILES['userfile']['error'] != 4 is for file required to upload.
you can make it unnecessary by using $_FILES['userfile']['error'] != 4
, then it will pass this error for file required and works great with other types of errors if any by using return false ,
hope it works for u ....
Assign after the EXEC
token:
DECLARE @returnValue INT
EXEC @returnValue = SP_One
I know that this is a bit of an old post, but all of the regular expressions here are missing one very important component: the support for IDN domain names.
IDN domain names start with xn--. They enable extended UTF-8 characters in domain names. For example, did you know "?.com" is a valid domain name? Yeah, "love heart dot com"! To validate the domain name, you need to let http://xn--c6h.com/ pass the validation.
Note, to use this regex, you will need to convert the domain to lower case, and also use an IDN library to ensure you encode domain names to ACE (also known as "ASCII Compatible Encoding"). One good library is GNU-Libidn.
idn(1) is the command line interface to the internationalized domain name library. The following example converts the host name in UTF-8 into ACE encoding. The resulting URL https://nic.xn--flw351e/ can then be used as ACE-encoded equivalent of https://nic.??/.
$ idn --quiet -a nic.??
nic.xn--flw351e
This magic regular expression should cover most domains (although, I am sure there are many valid edge cases that I have missed):
^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$
When choosing a domain validation regex, you should see if the domain matches the following:
If these three domains do not pass, your regular expression may be not allowing legitimate domains!
Check out The Internationalized Domain Names Support page from Oracle's International Language Environment Guide for more information.
Feel free to try out the regex here: http://www.regexr.com/3abjr
ICANN keeps a list of tlds that have been delegated which can be used to see some examples of IDN domains.
Edit:
^(((?!-))(xn--|_{1,1})?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9][a-z0-9\-]{0,60}|[a-z0-9-]{1,30}\.[a-z]{2,})$
This regular expression will stop domains that have '-' at the end of a hostname as being marked as being valid. Additionally, it allows unlimited subdomains.
you can achive it with group join
var result = (from c in Customers
join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
Select new { customer = c, orderItems = g});
c is Customer and g is the customers order items.
If you want to start search from root "/" , you will probably see output somethings like:
find: /./proc/1731/fdinfo: Permission denied
find: /./proc/2032/task/2032/fd: Permission denied
It's because of permission. To solve this:
You can use sudo command:
sudo find /. -name 'toBeSearched.file'
It asks super user's password, when enter the password you will see result what you really want. If you don't have permission to use sudo command which means you don't have super user's password, first ask system admin to add you to the sudoers file.
You can use redirect the Standard Error Output from (Generally Display/Screen) to some file and avoid seeing the error messages on the screen! redirect to a special file /dev/null :
find /. -name 'toBeSearched.file' 2>/dev/null
You can use redirect the Standard Error Output from (Generally Display/Screen) to Standard output (Generally Display/Screen), then pipe with grep command with -v "invert" parameter to not to see the output lines which has 'Permission denied' word pairs:
find /. -name 'toBeSearched.file' 2>&1 | grep -v 'Permission denied'
mp3 music to wav
ffmpeg -i music.mp3 music.wav
truncate to fit video
ffmpeg -i music.wav -ss 0 -t 37 musicshort.wav
mix music and video
ffmpeg -i musicshort.wav -i movie.avi final_video.avi
boolean isBeforeToday(Date d) {
Date today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
return d.before(today);
}
gcc -I/path -L/path
-I /path
path to include, gcc will find .h files in this path
-L /path
contains library files, .a
, .s
o
I wrote another one: http://argparse4j.sourceforge.net/
Argparse4j is a command line argument parser library for Java, based on Python's argparse.
In your user settings add:
"C_Cpp.default.includePath":["path1","path2"]
If the InputStream
you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:
input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
//stream not empty
} else {
//stream empty
}
If you don't control what kind of InputStream
you're using, you can use the markSupported()
method to check whether mark/reset will work on the stream, and fall back to the available()
method or the java.io.PushbackInputStream
method otherwise.
You should create a background thread to to create and populate the form. This will allow your foreground thread to show the loading message.
yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.
My go to solution on Windows for a bit of 'packaging' is something like this:
@echo off
setlocal
@rem _________________________
@rem
@set JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@rem
@set JAVA_EXE=%JAVA_HOME%\bin\java
@set VER=test
@set WRK=%~d0%~p0%VER%
@rem
@pushd %WRK%
cd
@echo.
@echo %JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
%JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
@rem
@rem _________________________
popd
endlocal
@exit /b
I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.
I use the following macro:
#define ENUM_FLAG_OPERATORS(T) \
inline T operator~ (T a) { return static_cast<T>( ~static_cast<std::underlying_type<T>::type>(a) ); } \
inline T operator| (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) | static_cast<std::underlying_type<T>::type>(b) ); } \
inline T operator& (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) & static_cast<std::underlying_type<T>::type>(b) ); } \
inline T operator^ (T a, T b) { return static_cast<T>( static_cast<std::underlying_type<T>::type>(a) ^ static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator|= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) |= static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator&= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) &= static_cast<std::underlying_type<T>::type>(b) ); } \
inline T& operator^= (T& a, T b) { return reinterpret_cast<T&>( reinterpret_cast<std::underlying_type<T>::type&>(a) ^= static_cast<std::underlying_type<T>::type>(b) ); }
It is similar to the ones mentioned above but has several improvements:
int
)It does need to include type_traits:
#include <type_traits>
Use below method,
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
If you want to use regular expression you can use as below,
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
@JoinColumn
could be used on both sides of the relationship. The question was about using @JoinColumn
on the @OneToMany
side (rare case). And the point here is in physical information duplication (column name) along with not optimized SQL query that will produce some additional UPDATE
statements.
According to documentation:
Since many to one are (almost) always the owner side of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)
@Entity
public class Troop {
@OneToMany(mappedBy="troop")
public Set<Soldier> getSoldiers() {
...
}
@Entity
public class Soldier {
@ManyToOne
@JoinColumn(name="troop_fk")
public Troop getTroop() {
...
}
Troop
has a bidirectional one to many relationship with Soldier
through the troop property. You don't have to (must not) define any physical mapping in the mappedBy
side.
To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy
element and set the many to one @JoinColumn
as insertable
and updatable
to false. This solution is not optimized and will produce some additional UPDATE
statements.
@Entity
public class Troop {
@OneToMany
@JoinColumn(name="troop_fk") //we need to duplicate the physical information
public Set<Soldier> getSoldiers() {
...
}
@Entity
public class Soldier {
@ManyToOne
@JoinColumn(name="troop_fk", insertable=false, updatable=false)
public Troop getTroop() {
...
}
You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.
public interface MyInterface {
public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}
The best option would be to put any element you want to be centered in a div
like this:
<div class="center"> <img src="images/logo.png" /> </div>
and css or inline style:
.center { text-align:center }
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
The ThreadPoolExecutor
class is the base implementation for the executors that are returned from many of the Executors
factory methods. So let's approach Fixed and Cached thread pools from ThreadPoolExecutor
's perspective.
The main constructor of this class looks like this:
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
)
The corePoolSize
determines the minimum size of the target thread pool. The implementation would maintain a pool of that size even if there are no tasks to execute.
The maximumPoolSize
is the maximum number of threads that can be active at once.
After the thread pool grows and becomes bigger than the corePoolSize
threshold, the executor can terminate idle threads and reach to the corePoolSize
again.
If allowCoreThreadTimeOut
is true, then the executor can even terminate core pool threads if they were idle more than keepAliveTime
threshold.
So the bottom line is if threads remain idle more than keepAliveTime
threshold, they may get terminated since there is no demand for them.
What happens when a new task comes in and all core threads are occupied? The new tasks will be queued inside that BlockingQueue<Runnable>
instance. When a thread becomes free, one of those queued tasks can be processed.
There are different implementations of the BlockingQueue
interface in Java, so we can implement different queuing approaches like:
Bounded Queue: New tasks would be queued inside a bounded task queue.
Unbounded Queue: New tasks would be queued inside an unbounded task queue. So this queue can grow as much as the heap size allows.
Synchronous Handoff: We can also use the SynchronousQueue
to queue the new tasks. In that case, when queuing a new task, another thread must already be waiting for that task.
Here's how the ThreadPoolExecutor
executes a new task:
corePoolSize
threads are running, tries to start a
new thread with the given task as its first job.BlockingQueue#offer
method. The offer
method won't block if the queue is full and immediately returns false
.offer
returns false
), then it tries to add a new thread to the thread pool with this task as its first job.RejectedExecutionHandler
.The main difference between the fixed and cached thread pools boils down to these three factors:
+-----------+-----------+-------------------+---------------------------------+ | Pool Type | Core Size | Maximum Size | Queuing Strategy | +-----------+-----------+-------------------+---------------------------------+ | Fixed | n (fixed) | n (fixed) | Unbounded `LinkedBlockingQueue` | +-----------+-----------+-------------------+---------------------------------+ | Cached | 0 | Integer.MAX_VALUE | `SynchronousQueue` | +-----------+-----------+-------------------+---------------------------------+
Excutors.newFixedThreadPool(n)
works:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
As you can see:
OutOfMemoryError
.When should I use one or the other? Which strategy is better in terms of resource utilization?
A fixed-size thread pool seems to be a good candidate when we're going to limit the number of concurrent tasks for resource management purposes.
For example, if we're going to use an executor to handle web server requests, a fixed executor can handle the request bursts more reasonably.
For even better resource management, it's highly recommended to create a custom ThreadPoolExecutor
with a bounded BlockingQueue<T>
implementation coupled with reasonable RejectedExecutionHandler
.
Here's how the Executors.newCachedThreadPool()
works:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
As you can see:
Integer.MAX_VALUE
. Practically, the thread pool is unbounded.SynchronousQueue
always fails when there is no one on the other end to accept it! When should I use one or the other? Which strategy is better in terms of resource utilization?
Use it when you have a lot of predictable short-running tasks.
Comparison of three ONELINERS which handle minus numbers case (input in a
array):
var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity: O(n)
var maxB = a.sort((a,b)=>b.y-a.y)[0].y; // 27 chars time complexity: O(nlogn)
var maxC = Math.max(...a.map(o=>o.y)); // 26 chars time complexity: >O(2n)
editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a
is changed because sort
is in-place).
var a = [
{"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},
{"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]
var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;
document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
_x000D_
For bigger arrays the Math.max...
will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 });
// Exception: Maximum call stack size exceeded
try {
let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }
try {
let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
_x000D_
First things first:
Arrays.copyOf()
methods.ArrayList
instead of an array.That being said, there might be situations where you have no other choice than to change the size of an array that is created somewhere outside of your code.1 The only way to do that is to manipulate the generated bytecode of the code that creates the array.
Below is a small proof-of-concept project that uses Java instrumentation to dynamically change the size of an array2. The sample project is a maven project with the following structure:
.
+- pom.xml
+- src
+- main
+- java
+- com
+- stackoverflow
+- agent
+- Agent.java
+- test
+- Main.java
Main.java
This file contains the target class of which we're going to manipulate the bytecode:
package com.stackoverflow.agent.test;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] array = {"Zero"};
fun(array);
System.out.println(Arrays.toString(array));
}
public static void fun(String[] array) {
array[1] = "One";
array[2] = "Two";
array[3] = "Three";
array[4] = "Four";
}
}
In the main
method, we create a String
array of size 1. In the fun
method, 4 additional values are assigned outside of the array's bounds. Running this code as-is will obviously result in an error.
Agent.java
This file contains the class that will perform the bytecode manipulation:
package com.stackoverflow.agent;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
public class Agent {
public static void premain(String args, Instrumentation instrumentation) {
instrumentation.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader l, String name, Class<?> c,
ProtectionDomain d, byte[] b) {
if (name.equals("com/stackoverflow/agent/test/Main")) {
byte iconst1 = (byte) 0x04;
byte iconst5 = (byte) 0x08;
byte anewarray = (byte) 0xbd;
for (int i = 0; i <= b.length - 1; i++) {
if (b[i] == iconst1 && b[i + 1] == anewarray) {
b[i] = iconst5;
}
}
return b;
}
return null;
}
});
}
}
On the bytecode level, the creation of the String
array in the Main
class consists of two commands:
iconst_1
, which pushes an int
constant with value 1 onto the stack (0x04
).anewarray
, which pops the value of the stack and creates a reference array3 of the same size (0xbd
).
The above code looks for that combination of commands in the Main
class, and if found, replaces the const_1
command with a const_5
command (0x08
), effectively changing the dimensions of the array to 5.4 pom.xml
The maven POM file is used to build the application JAR and configure the main class and the Java agent class.5
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stackoverflow</groupId>
<artifactId>agent</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<archive>
<manifestEntries>
<Main-Class>com.stackoverflow.agent.test.Main</Main-Class>
<Premain-Class>com.stackoverflow.agent.Agent</Premain-Class>
<Agent-Class>com.stackoverflow.agent.Agent</Agent-Class>
<Can-Retransform-Classes>true</Can-Retransform-Classes>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
The sample project can be built using the standard mvn clean package
command.
Executing without referencing the agent code will yield the expected error:
$> java -jar target/agent.jar
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at com.stackoverflow.agent.test.Main.fun(Main.java:15)
at com.stackoverflow.agent.test.Main.main(Main.java:9)
While executing with the agent code will yield:
$> java -javaagent:target/agent.jar -jar target/agent.jar
[Zero, One, Two, Three, Four]
This demonstrates that the size of the array was successfully changed using bytecode manipulation.
1 Such situations came up in questions here and here, the latter of which prompted me to write this answer.
2 Technically, the sample project doesn't resize the array. It just creates it with a different size than the size specified in code. Actually resizing an existing array while maintaining its reference and copying its elements would be a fair bit more complicated.
3 For a primitive array, the corresponding bytecode operation would be newarray
(0xbc
) instead.
4 As noted, this is just a proof of concept (and a very hacky one at that). Instead of randomly replacing bytes, a more robust implementation could use a bytecode manipulation library like ASM to insert a pop
command followed by an sipush
command before any newarray
or anewarray
command. Some more hints towards that solution can be found in the comments to this answer.
5 In a real-world scenario, the agent code would obviously be in a separate project.
Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.
{
"insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}
findViewById(R.id.android_text) does not need typecasting.
You can try this:
int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = cleft * 40;
txt.Size = new Size(200, 16);
txt.Left = 150;
cleft = cleft + 1;
Label lbl = new Label();
this.Controls.Add(lbl);
lbl.Top = aleft * 40;
lbl.Size = new Size(100, 16);
lbl.ForeColor = Color.Blue;
lbl.Text = "BoxNo/CardNo";
lbl.Left = 70;
aleft = aleft + 1;
return;
}
private void btd_Click(object sender, EventArgs e)
{
//Here you Delete Text Box One By One(int ix for Text Box)
for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
//Here you Delete Lable One By One(int ix for Lable)
for (int x = this.Controls.Count - 2; x >= 0; x--)
{
if (this.Controls[ix] is TextBox)
this.Controls[ix].Dispose();
if (this.Controls[x] is Label)
this.Controls[x].Dispose();
return;
}
}
That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,_x000D_
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),_x000D_
msg = document.getElementById('msg'),_x000D_
onChange = function(ev){_x000D_
ev.preventDefault();_x000D_
let _this = this,_x000D_
arrVal = Array.prototype.slice.call(_x000D_
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))_x000D_
.map(function(cur){return cur.value});_x000D_
_x000D_
if(arrVal.length){_x000D_
msg.innerHTML = JSON.stringify(arrVal);_x000D_
} else {_x000D_
_this.checked=true;_x000D_
msg.innerHTML = "At least one value must be checked!";_x000D_
}_x000D_
};_x000D_
_x000D_
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
_x000D_
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>_x000D_
<div id="msg"></div>
_x000D_
By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.
I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since.
We use:
/**
* Get the customer's IP address.
*
* @return string
*/
public function getIpAddress() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($ips[count($ips) - 1]);
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
The explode on HTTP_X_FORWARDED_FOR is because of weird issues we had detecting IP addresses when Squid was used.
It might be worth looking at a tutorial: MDN Canvas Tutorial
You can get the width and height of a canvas element simply by accessing those properties of the element. For example:
var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;
If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:
const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;
Or using the shorter object destructuring syntax:
const { width, height } = canvas.getBoundingClientRect();
The context
is an object you get from the canvas to allow you to draw into it. You can think of the context
as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.
The function below will return the x86 Program Files
directory in all of these three Windows configurations:
static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
I noticed that Internet Explorer 11 gets incredibly slow when slicing the data like Jeremy suggested. This is true for Chrome, but Internet Explorer seems to have a problem when passing the sliced data to the Blob-Constructor. On my machine, passing 5 MB of data makes Internet Explorer crash and memory consumption is going through the roof. Chrome creates the blob in no time.
Run this code for a comparison:
var byteArrays = [],
megaBytes = 2,
byteArray = new Uint8Array(megaBytes*1024*1024),
block,
blobSlowOnIE, blobFastOnIE,
i;
for (i = 0; i < (megaBytes*1024); i++) {
block = new Uint8Array(1024);
byteArrays.push(block);
}
//debugger;
console.profile("No Slices");
blobSlowOnIE = new Blob(byteArrays, { type: 'text/plain'});
console.profileEnd();
console.profile("Slices");
blobFastOnIE = new Blob([byteArray], { type: 'text/plain'});
console.profileEnd();
So I decided to include both methods described by Jeremy in one function. Credits go to him for this.
function base64toBlob(base64Data, contentType, sliceSize) {
var byteCharacters,
byteArray,
byteNumbers,
blobData,
blob;
contentType = contentType || '';
byteCharacters = atob(base64Data);
// Get BLOB data sliced or not
blobData = sliceSize ? getBlobDataSliced() : getBlobDataAtOnce();
blob = new Blob(blobData, { type: contentType });
return blob;
/*
* Get BLOB data in one slice.
* => Fast in Internet Explorer on new Blob(...)
*/
function getBlobDataAtOnce() {
byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
return [byteArray];
}
/*
* Get BLOB data in multiple slices.
* => Slow in Internet Explorer on new Blob(...)
*/
function getBlobDataSliced() {
var slice,
byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
slice = byteCharacters.slice(offset, offset + sliceSize);
byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
// Add slice
byteArrays.push(byteArray);
}
return byteArrays;
}
}
just use:
setTimeout("window.location.href='yoururl';",4000);
..where the '4000' is m.second
img
in the center of its parent.img
is an inline element, text-center
aligns inline elements in the center of its container should the container be a block
element. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col text-center">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
mx-auto
centers block
elements. In order to so, change display
of the img from inline
to block
with d-block
class. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
d-flex
and justify-content-center
on its parent. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col d-flex justify-content-center">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
You can use CSS to accomplish this:
.disabled {
pointer-events: none;
cursor: default;
}
_x000D_
<a href="somelink.html" class="disabled">Some link</a>
_x000D_
Or you can use JavaScript to prevent the default action like this:
$('.disabled').click(function(e){
e.preventDefault();
})
Move your form tag just outside the paragraph and set margins / padding to zero:
<form style="margin: 0; padding: 0;">
<p>
Read this sentence
<input style="display: inline;" type="submit" value="or push this button" />
</p>
</form>
It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:
char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);
Without the fflush()
, if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar()
peeks the "a", but the "\n" remains in the buffer, so the next fgets()
will find it and return an empty string without even waiting for user input.
However, note that this use of fflush()
is unportable. I've tested right now on a Linux machine, and it does not work, for example.
You could try appending it to a real DOM node...
function isDom(obj)
{
var elm = document.createElement('div');
try
{
elm.appendChild(obj);
}
catch (e)
{
return false;
}
return true;
}
I find this works easier. readonly the input field, then style it so the end user knows it's read only. inputs placed here (from AJAX for example) can still submit, without extra code.
<input readonly style="color: Grey; opacity: 1; ">
I would argue that creating a simple extension of Text and turning text
into a property is the cleanest way to go. You can then stick that extension in some file that you always import, and use it instead of the original Text
widget. This way, instead of having to remember, write, repeat, etc all the hoops tkinter makes you jump through to do the simplest things, you have a butt-simple interface that can be reused in any project. You can do this for Entry
, as well, but the syntax is slightly different.
import tkinter as tk
root = tk.Tk()
class Text(tk.Text):
@property
def text(self) -> str:
return self.get('1.0', 'end-1c')
@text.setter
def text(self, value) -> None:
self.replace('1.0', 'end-1c', value)
def __init__(self, master, **kwargs):
tk.Text.__init__(self, master, **kwargs)
#Entry version of the same concept as above
class Entry(tk.Entry):
@property
def text(self) -> str:
return self.get()
@text.setter
def text(self, value) -> None:
self.delete(0, 'end')
self.insert(0, value)
def __init__(self, master, **kwargs):
tk.Entry.__init__(self, master, **kwargs)
textbox = Text(root)
textbox.grid()
textbox.text = "this is text" #set
print(textbox.text) #get
entry = Entry(root)
entry.grid()
entry.text = 'this is text' #set
print(entry.text) #get
root.mainloop()
what about javascript without jQuery ?
for any input that you can get with or without jQuery, just :
input.readOnly
note : mind camelCase
You could use an input mask on the text box, too. If you set the mask to ##/##/####
it will always be formatted as you type and you don't need to do any coding other than checking to see if what was entered was a true date.
Which just a few easy lines
txtUserName.SetFocus
If IsDate(txtUserName.text) Then
Debug.Print Format(CDate(txtUserName.text), "MM/DD/YYYY")
Else
Debug.Print "Not a real date"
End If
Spire.Doc for Java, it is a professional Java API that enables Java applications to create, convert, manipulate and print Word documents without using Microsoft Office.You can easily convert Word to PDF with several lines of codes as follows.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.ToPdfParameterList;
public class WordToPDF {
public static void main(String[] args) {
//Create Document object
Document doc = new Document();
//Load the file from disk.
doc.loadFromFile("Sample.docx");
//create an instance of ToPdfParameterList.
ToPdfParameterList ppl=new ToPdfParameterList();
//embeds full fonts by default when IsEmbeddedAllFonts is set to true.
ppl.isEmbeddedAllFonts(true);
//set setDisableLink to true to remove the hyperlink effect for the result PDF page.
//set setDisableLink to false to preserve the hyperlink effect for the result PDF page.
ppl.setDisableLink(true);
//Set the output image quality as 40% of the original image. 80% is the default setting.
doc.setJPEGQuality(40);
//Save to file.
doc.saveToFile("output/ToPDF.pdf",FileFormat.PDF);
}
}
After running the code snippets above, all formats of the original Word document can be copied into PDF perfectly.
it works:
type HtmlEvent = React.ChangeEvent<HTMLSelectElement>
const onChange: React.EventHandler<HtmlEvent> =
(event: HtmlEvent) => {
console.log(event.target.value)
}
I believe you can get the border width using .css('border-left-width')
. You can also fetch top, right, and bottom and compare them to find the max value. The key here is that you have to specify a specific side.
See jQuery calculate padding-top as integer in px
Use the same logic as border or padding.
Alternatively, you could use outerWidth. The pseudo-code should bemargin = (outerWidth(true) - outerWidth(false)) / 2
. Note that this only works for finding the margin horizontally. To find the margin vertically, you would need to use outerHeight.
There's a nice workaround for this in the sitepoint forums:
<div onclick="this.nextElementSibling.style.display='block'; this.style.display='none'">
<img src="my_thumbnail.png" style="cursor:pointer" />
</div>
<div style="display:none">
<!-- Embed code here -->
</div>
Note: To prevent having to click twice to make the video play, use autoplay=1
in the video embed code. It will start playing when the second div is displayed.
You can also debug tomcat using the community edition (Unlike what is said above).
Start tomcat in debug mode, for example like this: .\catalina.bat jpda run
In intellij: Run > Edit Configurations > +
Select "Remote" Name the connection: "somename" Set "Port:" 8000 (default 5005)
Select Run > Debug "somename"
System.out.println(result/count)
you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:
double avg = (double)result / (double)args.length
If you are interested in the mouse entering or leaving one of your components you can use the @HostListener
decorator:
import { Component, HostListener, OnInit } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {
@HostListener('mouseenter')
onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave')
onMouseLeave() {
this.highlight(null);
}
...
}
As explained in the link in @Brandon comment to OP (https://angular.io/docs/ts/latest/guide/attribute-directives.html)
Looks it's one of the early asked question about Golang . And same time answers to never update . During these three to four years , too many new libraries and blog post has been out . Below are the few links what I felt useful .
Calling C++ Code From Go With SWIG
For OpenShift, you only get one PORT and IP pair to bind to (per application). It sounds like you should be able to serve both services from a single nodejs instance by adding internal routes for each service endpoint.
I have some info on how OpenShift uses your project's package.json to start your application here: https://www.openshift.com/blogs/run-your-nodejs-projects-on-openshift-in-two-simple-steps#package_json
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine
If you have compatibility with Object.keys
, and node does have compatibility, you should use that for sure.
However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:
JSON.stringify(obj) === '{}'
Consider this solution a 'last resort' use only if must.
See in the comments "there are many ways in which this solution is not ideal".
I had a last resort scenario, and it worked perfectly.
It appears you're missing an important point here: JavaScript is a single-threaded execution environment. Let's look again at your code, note I've added alert("Here")
:
var isPaused = false;
function firstFunction(){
isPaused = true;
for(i=0;i<x;i++){
// do something
}
isPaused = false;
};
function secondFunction(){
firstFunction()
alert("Here");
function waitForIt(){
if (isPaused) {
setTimeout(function(){waitForIt()},100);
} else {
// go do that thing
};
}
};
You don't have to wait for isPaused
. When you see the "Here" alert, isPaused
will be false
already, and firstFunction
will have returned. That's because you cannot "yield" from inside the for
loop (// do something
), the loop may not be interrupted and will have to fully complete first (more details: Javascript thread-handling and race-conditions).
That said, you still can make the code flow inside firstFunction
to be asynchronous and use either callback or promise to notify the caller. You'd have to give up upon for
loop and simulate it with if
instead (JSFiddle):
function firstFunction()
{
var deferred = $.Deferred();
var i = 0;
var nextStep = function() {
if (i<10) {
// Do something
printOutput("Step: " + i);
i++;
setTimeout(nextStep, 500);
}
else {
deferred.resolve(i);
}
}
nextStep();
return deferred.promise();
}
function secondFunction()
{
var promise = firstFunction();
promise.then(function(result) {
printOutput("Result: " + result);
});
}
On a side note, JavaScript 1.7 has introduced yield
keyword as a part of generators. That will allow to "punch" asynchronous holes in otherwise synchronous JavaScript code flow (more details and an example). However, the browser support for generators is currently limited to Firefox and Chrome, AFAIK.
I had an issue when setting react state multiple times (it always used default state). Following this react/github issue worked for me
const [state, setState] = useState({
foo: "abc",
bar: 123
});
// Do this!
setState(prevState => {
return {
...prevState,
foo: "def"
};
});
setState(prevState => {
return {
...prevState,
bar: 456
};
});
try to use use include_once
or require_once
instead of include
or require
Based on Vasily Sochinsky's answer a bit tweaked & with a small fix:
public static void unzip(File zipFile, File targetDirectory) throws IOException {
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = zis.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " +
dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
/* if time should be restored as well
long time = ze.getTime();
if (time > 0)
file.setLastModified(time);
*/
}
} finally {
zis.close();
}
}
Notable differences
public static
- this is a static utility method that can be anywhere.File
parameters because String
are :/ for files and one could not specify where the zip file is to be extracted before. Also path + filename
concatenation > https://stackoverflow.com/a/412495/995891throws
- because catch late - add a try catch if really not interested in them.mkdirs()
is important.finally
to prevent resource leaks.So
unzip(new File("/sdcard/pictures.zip"), new File("/sdcard"));
should do the equivalent of the original
unpackZip("/sdcard/", "pictures.zip")
Look for an email containing something to this effect:
Missing Info.plist key - This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSAppleMusicUsageDescription key with a string value explaining to the user how the app uses this data.
Where the missing key could be any of a range of permissions, and may be something you're not even using. This comes up often for react-native applications especially.
If you get such an email, follow the advice regarding the Info.plist
key and then resubmit the app.
If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"
Another understated reason for not using a singleton DbContext, even in a single threaded single user application, is because of the identity map pattern it uses. It means that every time you retrieve data using query or by id, it will keep the retrieved entity instances in cache. The next time you retrieve the same entity, it will give you the cached instance of the entity, if available, with any modifications you have done in the same session. This is necessary so the SaveChanges method does not end up with multiple different entity instances of the same database record(s); otherwise, the context would have to somehow merge the data from all those entity instances.
The reason that is a problem is a singleton DbContext can become a time bomb that could eventually cache the whole database + the overhead of .NET objects in memory.
There are ways around this behavior by only using Linq queries with the .NoTracking()
extension method. Also these days PCs have a lot of RAM. But usually that is not the desired behavior.
We can combine list-style-image
with svg
s, which we can inline in css! This method offers incredible control over the "bullets", which can become anything.
To get a red circle, just use the following css:
ul {
list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="2"/></svg>');
}
But this is just the beginning. This allows us to do any crazy thing we want with those bullets. circles or rectangles are easy, but anything you can draw with svg
you can stick in there! Check out the bullseye example below:
ul {_x000D_
list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="5"/></svg>');_x000D_
}_x000D_
ul ul {_x000D_
list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><rect fill="red" x="0" y="0" height="10" width="10"/></svg>');_x000D_
}_x000D_
ul ul ul {_x000D_
list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="3"/></svg>');_x000D_
}_x000D_
ul ul ul ul {_x000D_
list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><rect fill="red" x="2" y="2" height="4" width="4"/></svg>');_x000D_
}_x000D_
ul.bulls-eye {_x000D_
list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="10" height="10"><circle fill="red" cx="5" cy="5" r="5"/><circle fill="white" cx="5" cy="5" r="4"/><circle fill="red" cx="5" cy="5" r="2"/></svg>');_x000D_
}_x000D_
ul.multi-color {_x000D_
list-style-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12" width="15" height="15"><circle fill="blue" cx="6" cy="6" r="6"/><circle fill="pink" cx="6" cy="6" r="4"/><circle fill="green" cx="6" cy="6" r="2"/></svg>');_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Big circles!_x000D_
_x000D_
<ul>_x000D_
<li>Big rectangles!</li>_x000D_
<li>b_x000D_
<ul>_x000D_
<li>Small circles!</li>_x000D_
<li>c_x000D_
<ul>_x000D_
<li>Small rectangles!</li>_x000D_
<li>b</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>b</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="bulls-eye">_x000D_
<li>Bulls</li>_x000D_
<li>eyes.</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="multi-color">_x000D_
<li>Multi</li>_x000D_
<li>color</li>_x000D_
</ul>
_x000D_
Some browsers require width
and height
attributes to be set on the <svg>
, or they display nothing. At time of writing, recent versions of Firefox exhibit this problem. I've set both attributes in the examples.
A recent comment reminded me of encodings for the data-uri. This was a pain-point for me recently, and I can share a bit of information I've researched.
The data-uri spec, which references the URI spec, says that the svg should be encoded according to the URI spec. That means all sorts of characters should be encoded, eg <
becomes %3C
.
Some sources suggest base64 encoding, which should fix encoding issues, however it will unnecessarily increase the size of the SVG, whereas URI encoding will not. I recommend URI encoding.
Do what the compiler tells you to do, i.e. recompile with -fPIC
. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.
In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.
Finally, you can read about it on Wikipedia too.
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
Try using the type
attribute selector to find buttons (maybe this'll fix it too):
input[type=button]
{
background-color: #E3E1B8;
}
input[type=button]:hover
{
background-color: #46000D
}
I know I'm late to the game, but you can just do ?id=14&like=like
by using http build query as follows:
http_build_query(array_merge($_GET, array("like"=>"like")))
Whatever GET parameters you had will still be there and if like
was a parameter before it will be overwritten, otherwise it will be included at the end.
Get latest version of MsBuild. Best way, for all types of msbuild installation, for different processor architecture (Power Shell):
function Get-MsBuild-Path
{
$msbuildPathes = $null
$ptrSize = [System.IntPtr]::Size
switch ($ptrSize) {
4 {
$msbuildPathes =
@(Resolve-Path "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\*\*\MSBuild\*\Bin\msbuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:ProgramFiles(x86)}\MSBuild\*\Bin\MSBuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:windir}\Microsoft.NET\Framework\*\MSBuild.exe" -ErrorAction SilentlyContinue)
}
8 {
$msbuildPathes =
@(Resolve-Path "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\*\*\MSBuild\*\Bin\amd64\msbuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:ProgramFiles(x86)}\MSBuild\*\Bin\amd64\MSBuild.exe" -ErrorAction SilentlyContinue) +
@(Resolve-Path "${Env:windir}\Microsoft.NET\Framework64\*\MSBuild.exe" -ErrorAction SilentlyContinue)
}
default {
throw ($msgs.error_unknown_pointersize -f $ptrSize)
}
}
$latestMSBuildPath = $null
$latestVersion = $null
foreach ($msbuildFile in $msbuildPathes)
{
$msbuildPath = $msbuildFile.Path
$versionOutput = & $msbuildPath -version
$fileVersion = (New-Object System.Version($versionOutput[$versionOutput.Length - 1]))
if (!$latestVersion -or $latestVersion -lt $fileVersion)
{
$latestVersion = $fileVersion
$latestMSBuildPath = $msbuildPath
}
}
Write-Host "MSBuild version detected: $latestVersion" -Foreground Yellow
Write-Host "MSBuild path: $latestMSBuildPath" -Foreground Yellow
return $latestMSBuildPath;
}
I solved the problem as follows:
run MySQLInstanceConfig.exe
C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin\MySQLInstanceConfig.exe
Follow to the end without changing anything.
For Java, consider using Apache Commons FileUtils:
/**
* Convert a file to base64 string representation
*/
public String fileToBase64(File file) throws IOException {
final byte[] bytes = FileUtils.readFileToByteArray(file);
return Base64.getEncoder().encodeToString(bytes);
}
/**
* Convert base64 string representation to a file
*/
public void base64ToFile(String base64String, String filePath) throws IOException {
byte[] bytes = Base64.getDecoder().decode(base64String);
FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}
Very simply, use this
as the context: http://api.jquery.com/jQuery/#selector-context
var a_href = $('div.cpt', this).find('h2 a').attr('href');
Which says, find 'div.cpt'
only inside this
Just wrap floated elements in a <div>
and give it this CSS:
.wrapper {
display: table;
margin: auto;
}
Spent a few hours facing this issue this morning. I am likely to be the least technical person on these forums. Like the requester, I endured every reminder to set %JAVA_HOME%, biting my tongue each time I saw this non luminary advice. Finally I pondered whether my laptop's JRE was versions ahead of my JDK (as JREs are regularly updated automatically) and I installed the latest JDK. The difference was minor, emanating from a matter of weeks of different versions. I started with this error on jdk v 1.0865. The JRE was 1.0866. After installation, I had jdk v1.0874 and the equivalent JRE. At that point, I directed the Eclipse JRE to focus on my JDK and all was well. My println of java.home even reflected the correct JRE.
So much feedback repeated the wrong responses. I would strongly request that people read the feedback from others to avoid useless redundancy. Take care all, SG
I think the main problem is that you are casting using wrapper class, seems that they are incompatible types.
But another issue is that "i" is an int so you are casting the final result and you should cast i as well. Also try using the keyword "double" to cast and not "Double" wrapper class.
You can check here:
Hope this helps. I found the thread useful but I think this helps further clarify it.
Other than John's answer, you could also make one of the variable float, and the result will yield float.
>>> 144 / 314.0
0.4585987261146497
jqxhr is a json object:
complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").
see: jQuery ajax
so you would do:
jqxhr.status
to get the status
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
You can customize the JsonSerializerSettings
by using the Formatters.JsonFormatter.SerializerSettings
property in the HttpConfiguration
object.
For example, you could do that in the Application_Start() method:
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
}
Try using ReadAsStringAsync() instead.
var foo = resp.Content.ReadAsStringAsync().Result;
The reason why it ReadAsAsync<string>()
doesn't work is because ReadAsAsync<>
will try to use one of the default MediaTypeFormatter
(i.e. JsonMediaTypeFormatter
, XmlMediaTypeFormatter
, ...) to read the content with content-type
of text/plain
. However, none of the default formatter can read the text/plain
(they can only read application/json
, application/xml
, etc).
By using ReadAsStringAsync()
, the content will be read as string regardless of the content-type.
Fix of above function for play and pause
public void playBeep ( String word )
{
try
{
if ( ( m == null ) )
{
m = new MediaPlayer ();
}
else if( m != null&&lastPlayed.equalsIgnoreCase (word)){
m.stop();
m.release ();
m=null;
lastPlayed="";
return;
}else if(m != null){
m.release ();
m = new MediaPlayer ();
}
lastPlayed=word;
AssetFileDescriptor descriptor = context.getAssets ().openFd ( "rings/" + word + ".mp3" );
long start = descriptor.getStartOffset ();
long end = descriptor.getLength ();
// get title
// songTitle=songsList.get(songIndex).get("songTitle");
// set the data source
try
{
m.setDataSource ( descriptor.getFileDescriptor (), start, end );
}
catch ( Exception e )
{
Log.e ( "MUSIC SERVICE", "Error setting data source", e );
}
m.prepare ();
m.setVolume ( 1f, 1f );
// m.setLooping(true);
m.start ();
}
catch ( Exception e )
{
e.printStackTrace ();
}
}
A pure Python equivalent for string comparisons would be:
def less(string1, string2):
# Compare character by character
for idx in range(min(len(string1), len(string2))):
# Get the "value" of the character
ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
# If the "value" is identical check the next characters
if ordinal1 == ordinal2:
continue
# It's not equal so we're finished at this index and can evaluate which is smaller.
else:
return ordinal1 < ordinal2
# We're out of characters and all were equal, so the result depends on the length
# of the strings.
return len(string1) < len(string2)
This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for <
comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.
A more general variant would be:
from operator import lt, gt
def compare(string1, string2, less=True):
op = lt if less else gt
for char1, char2 in zip(string1, string2):
ordinal1, ordinal2 = ord(char1), ord(char1)
if ordinal1 == ordinal2:
continue
else:
return op(ordinal1, ordinal2)
return op(len(string1), len(string2))
I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:
AND (isdelete is NULL or isdelete = 0)
Simple bar graph:
set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes
data.dat:
0 label 100
1 label2 450
2 "bar label" 75
If you want to style your bars differently, you can do something like:
set style line 1 lc rgb "red"
set style line 2 lc rgb "blue"
set style fill solid
set boxwidth 0.5
plot "data.dat" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \
"data.dat" every ::1::2 using 1:3:xtic(2) with boxes ls 2
If you want to do multiple bars for each entry:
data.dat:
0 5
0.5 6
1.5 3
2 7
3 8
3.5 1
gnuplot:
set xtics ("label" 0.25, "label2" 1.75, "bar label" 3.25,)
set boxwidth 0.5
set style fill solid
plot 'data.dat' every 2 using 1:2 with boxes ls 1,\
'data.dat' every 2::1 using 1:2 with boxes ls 2
If you want to be tricky and use some neat gnuplot tricks:
Gnuplot has psuedo-columns that can be used as the index to color:
plot 'data.dat' using 1:2:0 with boxes lc variable
Further you can use a function to pick the colors you want:
mycolor(x) = ((x*11244898) + 2851770)
plot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable
Note: you will have to add a couple other basic commands to get the same effect as the sample images.
Just to update on the current state of ASP.NET WebAPI. The interface is now called IActionResult
and implementation hasn't changed much:
[JsonObject(IsReference = true)]
public class DuplicateEntityException : IActionResult
{
public DuplicateEntityException(object duplicateEntity, object entityId)
{
this.EntityType = duplicateEntity.GetType().Name;
this.EntityId = entityId;
}
/// <summary>
/// Id of the duplicate (new) entity
/// </summary>
public object EntityId { get; set; }
/// <summary>
/// Type of the duplicate (new) entity
/// </summary>
public string EntityType { get; set; }
public Task ExecuteResultAsync(ActionContext context)
{
var message = new StringContent($"{this.EntityType ?? "Entity"} with id {this.EntityId ?? "(no id)"} already exist in the database");
var response = new HttpResponseMessage(HttpStatusCode.Ambiguous) { Content = message };
return Task.FromResult(response);
}
#endregion
}
You could use Java reflection to do this. The method would be represented as an instance of java.lang.reflect.Method.
import java.lang.reflect.Method;
public class Demo {
public static void main(String[] args) throws Exception{
Class[] parameterTypes = new Class[1];
parameterTypes[0] = String.class;
Method method1 = Demo.class.getMethod("method1", parameterTypes);
Demo demo = new Demo();
demo.method2(demo, method1, "Hello World");
}
public void method1(String message) {
System.out.println(message);
}
public void method2(Object object, Method method, String message) throws Exception {
Object[] parameters = new Object[1];
parameters[0] = message;
method.invoke(object, parameters);
}
}
This should strip away the date part:
select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()
and return a datetime with a default date of 1900-01-01.
First of all, 2 thing that we need to understand
it make request to specific server
bindService(new
Intent("com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);`
here mServiceConn
is instance of ServiceConnection
class(inbuilt) it is actually interface that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.
server send response with IBind Object.so IBind object is our handler which access all the method of service by using (.) operator.
MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.d("ServiceConnection","connected");
myService = binder;
}
//binder comes from server to communicate with method's of
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
}
myservice.serviceMethod();
here myService
is object and serviceMethode
is method in service.
And by this way communication is established between client and server.
You can do this:
/* Clearfix for the menu */
.ui-menu:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
and also set:
.ui-menu .ui-menu-item {
display: inline-block;
float: left;
margin: 0;
padding: 0;
width: auto;
}
I want to do a for loop, yet with askewchan's method it does not work well, so I have modified it.
x = np.empty((0,3))
y = np.array([1,2,3])
for i in ...
x = np.vstack((x,y))
You can use the "Join" function to create a single string out of the array of labels, like this:
=Join(Parameters!Product.Label, ",")
i prefer to physically print my tables instead:
CONNECT_SERVER="https://196.168.1.1/"
CONNECT_API_KEY<-"hpphotosmartP9000:8273827"
data.frame = data.frame(1:1000, 1000:2)
connectServer <- Sys.getenv("CONNECT_SERVER")
apiKey <- Sys.getenv("CONNECT_API_KEY")
install.packages('print2print')
print2print::send2printer(connectServer, apiKey, data.frame)
You can use the password_verify function with the PHP. It verifies that a password matches with the hash
password_verify ( string $password , string $hash ) : bool
more details: https://www.php.net/manual/en/function.password-verify.php
Here's the stock "settings.xml" with comments (complete/unchopped file at the bottom)
License:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
Main docs and top:
<!--
| This is the configuration file for Maven. It can be specified at two levels:
|
| 1. User Level. This settings.xml file provides configuration for a single
| user, and is normally provided in
| ${user.home}/.m2/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -s /path/to/user/settings.xml
|
| 2. Global Level. This settings.xml file provides configuration for all
| Maven users on a machine (assuming they're all using the
| same Maven installation). It's normally provided in
| ${maven.home}/conf/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -gs /path/to/global/settings.xml
|
| The sections in this sample file are intended to give you a running start
| at getting the most out of your Maven installation. Where appropriate, the
| default values (values used when the setting is not specified) are provided.
|
|-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
Local repository, interactive mode, plugin groups:
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set
| to false, maven will use a sensible default value, perhaps based on some
| other setting, for the parameter in question.
|
| Default: true
<interactiveMode>true</interactiveMode>
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when
| executing a build. This will have an effect on artifact downloads,
| artifact deployment, and others.
|
| Default: false
<offline>false</offline>
-->
<!-- pluginGroups
| This is a list of additional group identifiers that will be searched when
| resolving plugins by their prefix, i.e. when invoking a command line like
| "mvn prefix:goal". Maven will automatically add the group identifiers
| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
| already contained in the list.
|-->
<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
<pluginGroup>com.your.plugins</pluginGroup>
-->
</pluginGroups>
Proxies:
<!-- proxies
| This is a list of proxies which can be used on this machine to connect to
| the network. Unless otherwise specified (by system property or command-
| line switch), the first proxy specification in this list marked as active
| will be used.
|-->
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
Servers:
<!-- servers
| This is a list of authentication profiles, keyed by the server-id used
| within the system. Authentication profiles can be used whenever maven must
| make a connection to a remote server.
|-->
<servers>
<!-- server
| Specifies the authentication information to use when connecting to a
| particular server, identified by a unique name within the system
| (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR
| privateKey/passphrase, since these pairings are used together.
|
<server>
<id>deploymentRepo</id>
<username>repouser</username>
<password>repopwd</password>
</server>
-->
<!-- Another sample, using keys to authenticate.
<server>
<id>siteServer</id>
<privateKey>/path/to/private/key</privateKey>
<passphrase>optional; leave empty if not used.</passphrase>
</server>
-->
</servers>
Mirrors:
<!-- mirrors
| This is a list of mirrors to be used in downloading artifacts from remote
| repositories.
|
| It works like this: a POM may declare a repository to use in resolving
| certain artifacts. However, this repository may have problems with heavy
| traffic at times, so people have mirrored it to several places.
|
| That repository definition will have a unique id, so we can create a
| mirror reference for that repository, to be used as an alternate download
| site. The mirror site will be the preferred server for that repository.
|-->
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository.
| The repository that this mirror serves has an ID that matches the
| mirrorOf element of this mirror. IDs are used for inheritance and direct
| lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
</mirrors>
Profiles (1/3):
<!-- profiles
| This is a list of profiles which can be activated in a variety of ways,
| and which can modify the build process. Profiles provided in the
| settings.xml are intended to provide local machine-specific paths and
| repository locations which allow the build to work in the local
| environment.
|
| For example, if you have an integration testing plugin - like cactus -
| that needs to know where your Tomcat instance is installed, you can
| provide a variable here such that the variable is dereferenced during the
| build process to configure the cactus plugin.
|
| As noted above, profiles can be activated in a variety of ways. One
| way - the activeProfiles section of this document (settings.xml) - will be
| discussed later. Another way essentially relies on the detection of a
| system property, either matching a particular value for the property, or
| merely testing its existence. Profiles can also be activated by JDK
| version prefix, where a value of '1.4' might activate a profile when the
| build is executed on a JDK version of '1.4.2_07'. Finally, the list of
| active profiles can be specified directly from the command line.
|
| NOTE: For profiles defined in the settings.xml, you are restricted to
| specifying only artifact repositories, plugin repositories, and
| free-form properties to be used as configuration variables for
| plugins in the POM.
|
|-->
Profiles (2/3):
<profiles>
<!-- profile
| Specifies a set of introductions to the build process, to be activated
| using one or more of the mechanisms described above. For inheritance
| purposes, and to activate profiles via <activatedProfiles/> or the
| command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a
| consistent naming convention for profiles, such as 'env-dev',
| 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
| will make it more intuitive to understand what the set of introduced
| profiles is attempting to accomplish, particularly when you only have a
| list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and
| provides a JDK-specific repo.
<profile>
<id>jdk-1.4</id>
<activation>
<jdk>1.4</jdk>
</activation>
<repositories>
<repository>
<id>jdk14</id>
<name>Repository for JDK 1.4 builds</name>
<url>http://www.myhost.com/maven/jdk14</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
-->
Profiles (3/3):
<!--
| Here is another profile, activated by the system property 'target-env'
| with a value of 'dev', which provides a specific path to the Tomcat
| instance. To use this, your plugin configuration might hypothetically
| look like:
|
| ...
| <plugin>
| <groupId>org.myco.myplugins</groupId>
| <artifactId>myplugin</artifactId>
|
| <configuration>
| <tomcatLocation>${tomcatPath}</tomcatLocation>
| </configuration>
| </plugin>
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone
| set 'target-env' to anything, you could just leave off the
| <value/> inside the activation-property.
|
<profile>
<id>env-dev</id>
<activation>
<property>
<name>target-env</name>
<value>dev</value>
</property>
</activation>
<properties>
<tomcatPath>/path/to/tomcat/instance</tomcatPath>
</properties>
</profile>
-->
</profiles>
Bottom:
<!-- activeProfiles
| List of profiles that are active for all builds.
|
<activeProfiles>
<activeProfile>alwaysActiveProfile</activeProfile>
<activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>
-->
</settings>
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
| This is the configuration file for Maven. It can be specified at two levels:
|
| 1. User Level. This settings.xml file provides configuration for a single
| user, and is normally provided in
| ${user.home}/.m2/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -s /path/to/user/settings.xml
|
| 2. Global Level. This settings.xml file provides configuration for all
| Maven users on a machine (assuming they're all using the
| same Maven installation). It's normally provided in
| ${maven.home}/conf/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -gs /path/to/global/settings.xml
|
| The sections in this sample file are intended to give you a running start
| at getting the most out of your Maven installation. Where appropriate, the
| default values (values used when the setting is not specified) are provided.
|
|-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set
| to false, maven will use a sensible default value, perhaps based on some
| other setting, for the parameter in question.
|
| Default: true
<interactiveMode>true</interactiveMode>
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when
| executing a build. This will have an effect on artifact downloads,
| artifact deployment, and others.
|
| Default: false
<offline>false</offline>
-->
<!-- pluginGroups
| This is a list of additional group identifiers that will be searched when
| resolving plugins by their prefix, i.e. when invoking a command line like
| "mvn prefix:goal". Maven will automatically add the group identifiers
| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
| already contained in the list.
|-->
<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
<pluginGroup>com.your.plugins</pluginGroup>
-->
</pluginGroups>
<!-- proxies
| This is a list of proxies which can be used on this machine to connect to
| the network. Unless otherwise specified (by system property or command-
| line switch), the first proxy specification in this list marked as active
| will be used.
|-->
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
<!-- servers
| This is a list of authentication profiles, keyed by the server-id used
| within the system. Authentication profiles can be used whenever maven must
| make a connection to a remote server.
|-->
<servers>
<!-- server
| Specifies the authentication information to use when connecting to a
| particular server, identified by a unique name within the system
| (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR
| privateKey/passphrase, since these pairings are used together.
|
<server>
<id>deploymentRepo</id>
<username>repouser</username>
<password>repopwd</password>
</server>
-->
<!-- Another sample, using keys to authenticate.
<server>
<id>siteServer</id>
<privateKey>/path/to/private/key</privateKey>
<passphrase>optional; leave empty if not used.</passphrase>
</server>
-->
</servers>
<!-- mirrors
| This is a list of mirrors to be used in downloading artifacts from remote
| repositories.
|
| It works like this: a POM may declare a repository to use in resolving
| certain artifacts. However, this repository may have problems with heavy
| traffic at times, so people have mirrored it to several places.
|
| That repository definition will have a unique id, so we can create a
| mirror reference for that repository, to be used as an alternate download
| site. The mirror site will be the preferred server for that repository.
|-->
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository.
| The repository that this mirror serves has an ID that matches the
| mirrorOf element of this mirror. IDs are used for inheritance and direct
| lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
</mirrors>
<!-- profiles
| This is a list of profiles which can be activated in a variety of ways,
| and which can modify the build process. Profiles provided in the
| settings.xml are intended to provide local machine-specific paths and
| repository locations which allow the build to work in the local
| environment.
|
| For example, if you have an integration testing plugin - like cactus -
| that needs to know where your Tomcat instance is installed, you can
| provide a variable here such that the variable is dereferenced during the
| build process to configure the cactus plugin.
|
| As noted above, profiles can be activated in a variety of ways. One
| way - the activeProfiles section of this document (settings.xml) - will be
| discussed later. Another way essentially relies on the detection of a
| system property, either matching a particular value for the property, or
| merely testing its existence. Profiles can also be activated by JDK
| version prefix, where a value of '1.4' might activate a profile when the
| build is executed on a JDK version of '1.4.2_07'. Finally, the list of
| active profiles can be specified directly from the command line.
|
| NOTE: For profiles defined in the settings.xml, you are restricted to
| specifying only artifact repositories, plugin repositories, and
| free-form properties to be used as configuration variables for
| plugins in the POM.
|
|-->
<profiles>
<!-- profile
| Specifies a set of introductions to the build process, to be activated
| using one or more of the mechanisms described above. For inheritance
| purposes, and to activate profiles via <activatedProfiles/> or the
| command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a
| consistent naming convention for profiles, such as 'env-dev',
| 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
| will make it more intuitive to understand what the set of introduced
| profiles is attempting to accomplish, particularly when you only have a
| list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and
| provides a JDK-specific repo.
<profile>
<id>jdk-1.4</id>
<activation>
<jdk>1.4</jdk>
</activation>
<repositories>
<repository>
<id>jdk14</id>
<name>Repository for JDK 1.4 builds</name>
<url>http://www.myhost.com/maven/jdk14</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
-->
<!--
| Here is another profile, activated by the system property 'target-env'
| with a value of 'dev', which provides a specific path to the Tomcat
| instance. To use this, your plugin configuration might hypothetically
| look like:
|
| ...
| <plugin>
| <groupId>org.myco.myplugins</groupId>
| <artifactId>myplugin</artifactId>
|
| <configuration>
| <tomcatLocation>${tomcatPath}</tomcatLocation>
| </configuration>
| </plugin>
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone
| set 'target-env' to anything, you could just leave off the
| <value/> inside the activation-property.
|
<profile>
<id>env-dev</id>
<activation>
<property>
<name>target-env</name>
<value>dev</value>
</property>
</activation>
<properties>
<tomcatPath>/path/to/tomcat/instance</tomcatPath>
</properties>
</profile>
-->
</profiles>
<!-- activeProfiles
| List of profiles that are active for all builds.
|
<activeProfiles>
<activeProfile>alwaysActiveProfile</activeProfile>
<activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>
-->
</settings>
Check the Jon Skeet answer to this other question: UTF-16 to UTF-8 conversion (for scripting in Windows)
It contains the source code that you need.
Hope it helps.
Are you using the interactive interpreter? You can use
sys.argv[0]
You should read: How do I get the path of the current executed file in Python?
Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
});
In Style.xml pre-define the style:
<style name="largeText">
<item name="android:textAppearance">@android:style/TextAppearance.Large.Inverse</item>
<item name="android:textStyle">bold</item>
</style>
in code:
text.setTextAppearance(context, R.style.largeText);
You can use pd.Series.isin
.
For "IN" use: something.isin(somewhere)
Or for "NOT IN": ~something.isin(somewhere)
As a worked example:
import pandas as pd
>>> df
country
0 US
1 UK
2 Germany
3 China
>>> countries_to_keep
['UK', 'China']
>>> df.country.isin(countries_to_keep)
0 False
1 True
2 False
3 True
Name: country, dtype: bool
>>> df[df.country.isin(countries_to_keep)]
country
1 UK
3 China
>>> df[~df.country.isin(countries_to_keep)]
country
0 US
2 Germany
new Date("2016-3-17").valueOf()
will return a long epoch
no, but it runs fine on win64, and can create win64 .EXEs
In general, questions regarding "magic" variables in Perl can be answered by looking in the Perl predefined variables documentation a la:
perldoc perlvar
However, when you search this documentation for $1, etc., you'll find references in a number of places except the section on these "digit" variables. You have to search for
$<digits>
I would have added this to Brian's answer either by commenting or editing, but I don't have enough rep. If someone adds this I'll remove this answer.
When workspace is damaged and Eclipse cannot start, even using the -clean
option, removing single file workspace/.metadata/.plugins/org.eclipse.core.resources/.snap
may help (source: comments to article https://web.archive.org/web/20200517003712/https://letsgetdugg.com/2009/04/19/recovering-a-corrupt-eclipse-workspace/).
Update: when Eclipse 4.X cannot start after crash, try to start with -clearPersistedState
option; if it didn't help then remove file workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi
(sources: https://www.eclipse.org/forums/index.php/m/1269045/ https://www.eclipse.org/forums/index.php/t/522428/ https://bugs.eclipse.org/bugs/show_bug.cgi?id=404873). Note: you'll lose configuration of your perspective/views/tabs.
Update: Subversive plugin may be responsible for inability to start Eclipse with corrupted metadata. If you have Subversive plugin installed, update it to latest build (at least 0.7.9.I20120210-1700) from update-site. Related bugs 372621 and 370374 were fixed by Subversive developers.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
See here: https://superuser.com/questions/42537/is-there-any-sudo-command-for-windows
According to that the command looks like this for admin:
runas /noprofile /user:Administrator cmd
Here is the complete programme give Below`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace oops3
{
public class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Enter the size of the array");
int x = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[x];
Console.WriteLine("Enter the elements of the array");
for(int i=0;i<x;i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
int smallest = arr[0];
int Largest = arr[0];
for(int i=0;i<x;i++)
{
if(smallest>arr[i])
{
smallest = arr[i];
}
}
for (int i = 0; i < x; i++)
{
if (Largest< arr[i])
{
Largest = arr[i];
}
}
Console.WriteLine("The greater No in the array:" + Largest);
Console.WriteLine("The smallest No in the array:" + smallest);
Console.ReadLine();
}
}
}
Adding MongoDb
bin path in Environment path with \
worked for me
This is what my system path
C:\ProgramData\Oracle\Java\javapath;
...
...
Other path variables
...
;C:\Users\hitesh.sahu\AppData\Local\Android\sdk\platform-tools
;C:\Program Files\MongoDB\Server\3.2\bin\
Make sure:-
;
I get this code works on my browser:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
Note for this code: HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries
The latest CRAN version of rJava will find the jvm.dll
automatically, without manually setting the PATH
or JAVA_HOME
. However note that:
C:\Program files\Java\
and the latter in C:\Program Files (x86)\Java\
so they do not conflict.As of Java version 9, support for x86 (win32) has been discontinued. Hence the latest working multi-arch setup is to install both jdk-8u172-windows-i586.exe and jdk-8u172-windows-x64.exe and then the binary package from CRAN:
install.packages("rJava")
The binary package from CRAN should pick up on the jvm by itself. Experts only: to build rJava from source, you need the --merge-multiarch
flag:
install.packages('rJava', type = 'source', INSTALL_opts='--merge-multiarch')
(Note: many of folks in other answers/comments have said to remove JAVA_HOME, so consider that. I have not revisited this issue recently to know if all the steps below are still necessary.)
Here is some quick advice on how to get up and running with R + rJava on Windows 7 64bit. There are several possibilities, but most have fatal flaws. Here is what worked for me:
Add jvm.dll to your PATH
rJava, the R<->Java bridge, will need jvm.dll, but R will have trouble finding that DLL. It resides in a folder like
C:\Program Files\Java\jdk1.6.0_25\jre\bin\server
or
C:\Program Files\Java\jre6\jre\bin\client
Wherever yours is, add that directory to your windows PATH variable. (Windows -> "Path" -> "Edit environment variables to for your account" -> PATH -> edit the value.)
You may already have Java on your PATH. If so you should find the client/server directory in the same Java "home" dir as the one already on your PATH.
To be safe, make sure your architectures match.If you have Java in Program Files
, it is 64-bit, so you ought to run R64. If you have Java in Program Files (x86)
, that's 32-bit, so you use plain 32-bit R.
Re-launch R from the Windows Menu
If R is running, quit.
From the Start Menu , Start R / RGUI, RStudio. This is very important, to make R pick up your PATH changes.
Install rJava 0.9.2.
Earlier versions do not work! Mirrors are not up-to-date, so go to the source at www.rforge.net: http://www.rforge.net/rJava/files/. Note the advice there
“Please use
`install.packages('rJava',,'http://www.rforge.net/')`
to install.”
That is almost correct. This actually works:
install.packages('rJava', .libPaths()[1], 'http://www.rforge.net/')
Watch the punctuation! The mysterious “.libPaths()[1],” just tells R to install the package in the primary library directory. For some reason, leaving the value blank doesn’t work, even though it should default.
If your databaseName
value is correct, then use this: DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")
You need to use Range
and Valu
e functions.
Range
would be the cell where you want the text you want
Value
would be the text that you want in that Cell
Range("A1").Value="whatever text"
I added a directory to svn, then I accidentally deleted the .svn folder within.
I used
svn delete --keep-local folderName
to fix my problem.
Microsoft Message Analyzer is the successor of the Microsoft Network Monitor 3.4
If your http incoming traffic is going to your web server at 58000 port, start the Analyzer in Administrator mode and click new session:
use filter: tcp.Port = 58000 and HTTP
trace scenario: "Local Network Interfaces (Win 8 and earlier)" or "Local Network Interfaces (Win 8.1 and later)" depends on your OS
Parsing Level: Full
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
For Java SE 5: According to Garbage Collector Ergonomics [Oracle]:
initial heap size:
Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.
maximum heap size:
Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.
UPDATE:
As pointed out by Tom Anderson in his comment, the above is for server-class machines. From Ergonomics in the 5.0 JavaTM Virtual Machine:
In the J2SE platform version 5.0 a class of machine referred to as a server-class machine has been defined as a machine with
- 2 or more physical processors
- 2 or more Gbytes of physical memory
with the exception of 32 bit platforms running a version of the Windows operating system. On all other platforms the default values are the same as the default values for version 1.4.2.
In the J2SE platform version 1.4.2 by default the following selections were made
- initial heap size of 4 Mbyte
- maximum heap size of 64 Mbyte
Expanding on Nathans post. The following will do the job lot in one batch file.
@echo off
if %1.==Sub. goto %2
for %%f in (*.in) do call %0 Sub action %%~nf
goto end
:action
echo The file is %3
copy %3.in %3.out
ren %3.out monkeys_are_cool.txt
:end
You can use the statement :-
Class c = s.getClass();
To get the class instance.
They're very handy to use for when you want different functions at different times, or different phases of development. For instance, I'm developing an application on a host computer that has a console, but the final release of the software will be put on an Avnet ZedBoard (which has ports for displays and consoles, but they are not needed/wanted for the final release). So during development, I will use printf
to view status and error messages, but when I'm done, I don't want anything printed. Here's what I've done:
// First, undefine all macros associated with version.h
#undef DEBUG_VERSION
#undef RELEASE_VERSION
#undef INVALID_VERSION
// Define which version we want to use
#define DEBUG_VERSION // The current version
// #define RELEASE_VERSION // To be uncommented when finished debugging
#ifndef __VERSION_H_ /* prevent circular inclusions */
#define __VERSION_H_ /* by using protection macros */
void board_init();
void noprintf(const char *c, ...); // mimic the printf prototype
#endif
// Mimics the printf function prototype. This is what I'll actually
// use to print stuff to the screen
void (* zprintf)(const char*, ...);
// If debug version, use printf
#ifdef DEBUG_VERSION
#include <stdio.h>
#endif
// If both debug and release version, error
#ifdef DEBUG_VERSION
#ifdef RELEASE_VERSION
#define INVALID_VERSION
#endif
#endif
// If neither debug or release version, error
#ifndef DEBUG_VERSION
#ifndef RELEASE_VERSION
#define INVALID_VERSION
#endif
#endif
#ifdef INVALID_VERSION
// Won't allow compilation without a valid version define
#error "Invalid version definition"
#endif
In version.c
I will define the 2 function prototypes present in version.h
#include "version.h"
/*****************************************************************************/
/**
* @name board_init
*
* Sets up the application based on the version type defined in version.h.
* Includes allowing or prohibiting printing to STDOUT.
*
* MUST BE CALLED FIRST THING IN MAIN
*
* @return None
*
*****************************************************************************/
void board_init()
{
// Assign the print function to the correct function pointer
#ifdef DEBUG_VERSION
zprintf = &printf;
#else
// Defined below this function
zprintf = &noprintf;
#endif
}
/*****************************************************************************/
/**
* @name noprintf
*
* simply returns with no actions performed
*
* @return None
*
*****************************************************************************/
void noprintf(const char* c, ...)
{
return;
}
Notice how the function pointer is prototyped in version.h
as
void (* zprintf)(const char *, ...);
When it is referenced in the application, it will start executing wherever it is pointing, which has yet to be defined.
In version.c
, notice in the board_init()
function where zprintf
is assigned a unique function (whose function signature matches) depending on the version that is defined in version.h
zprintf = &printf;
zprintf calls printf for debugging purposes
or
zprintf = &noprint;
zprintf just returns and will not run unnecessary code
Running the code will look like this:
#include "version.h"
#include <stdlib.h>
int main()
{
// Must run board_init(), which assigns the function
// pointer to an actual function
board_init();
void *ptr = malloc(100); // Allocate 100 bytes of memory
// malloc returns NULL if unable to allocate the memory.
if (ptr == NULL)
{
zprintf("Unable to allocate memory\n");
return 1;
}
// Other things to do...
return 0;
}
The above code will use printf
if in debug mode, or do nothing if in release mode. This is much easier than going through the entire project and commenting out or deleting code. All that I need to do is change the version in version.h
and the code will do the rest!
That's called a hash-bang. If you run the script from the shell, it will inspect the first line to figure out what program should be started to interpret the script.
A non Unix based OS will use its own rules for figuring out how to run the script. Windows for example will use the filename extension and the #
will cause the first line to be treated as a comment.
If the path to the Python executable is wrong, then naturally the script will fail. It is easy to create links to the actual executable from whatever location is specified by standard convention.