Set up a virtualenv:
% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py
% sudo python /tmp/get-pip.py
These commands install pip into the global site-packages directory.
% sudo pip install virtualenv
and ditto for virtualenv:
% mkdir -p ~/.virtualenvs
I like my virtualenvs under one tree in my home directory called .virtualenvs
% virtualenv ~/.virtualenvs/lxmltest
Creates a virtualenv.
% . ~/.virtualenvs/lxmltest/bin/activate
Removes the need to specify the full path to pip/python in this virtualenv.
% pip install lxml
Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml
if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest
and start again from a new virtualenv.
I also saw similar problems reported in ReSharper which did not lead to compile/runtime errors.
These were mostly seen when using "{x:Type ...}"
or "{x:Static ...}"
markup, causing ReSharper to report "Cannot resolve symbol 'Type'"
or "Cannot resolve symbol 'Static'"
errors.
Additionally there were many errors like "Invalid markup extension type: expected type is '<type>', actual type is '...Extension'"
.
The problem resolved itself when I added a reference to the System.Xaml
assembly.
What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.
Also, in your card.cpp, the function should be Card::Card()
instead of void Card
. The Card::
is scoping; it means that your Card()
function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,
void Card(Card::Rank rank, Card::Suit suit)
should be
Card::Card(Card::Rank rank, Card::Suit suit)
Also, in deck.cpp, you are saying #include "Deck.h"
even though you referred to it as deck.h. The includes are case sensitive.
I've heard about tools which were using very simple, but quite effective algorithm. The algorithm calculated relative amount of pixels with color value near to some predefined "skin" colours. If that amount is higher than some predefined value then image is considered to be of erotic/pornographic content. Of course that algorithm will give false positive results for close-up face photos and many other things.
Since you are writing about social networking there will be lots of "normal" photos with high amount of skin colour on it, so you shouldn't use this algorithm to deny all pictures with positive result. But you can use it provide some help for moderators, for example flag these pictures with higher priority, so if moderator want to check some new pictures for pornographic content he can start from these pictures.
Let me propose an improved method when the values of the dictionnary are lists with the same lenght :
import numpy
def dctToNdarray (dd, szFormat = 'f8'):
'''
Convert a 'rectangular' dictionnary to numpy NdArray
entry
dd : dictionnary (same len of list
retrun
data : numpy NdArray
'''
names = dd.keys()
firstKey = dd.keys()[0]
formats = [szFormat]*len(names)
dtype = dict(names = names, formats=formats)
values = [tuple(dd[k][0] for k in dd.keys())]
data = numpy.array(values, dtype=dtype)
for i in range(1,len(dd[firstKey])) :
values = [tuple(dd[k][i] for k in dd.keys())]
data_tmp = numpy.array(values, dtype=dtype)
data = numpy.concatenate((data,data_tmp))
return data
dd = {'a':[1,2.05,25.48],'b':[2,1.07,9],'c':[3,3.01,6.14]}
data = dctToNdarray(dd)
print data.dtype.names
print data
To remove undefined, null, and empty string from object
_.omitBy(object, (v) => _.isUndefined(v) || _.isNull(v) || v === '');
The following command will delete images older than 48 hours.
$ docker image prune --all --filter until=48h
If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:
# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));
# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
In this case curl will send your defined cookie along with the cookies from the file.
If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).
The utma utmc, utmz
are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.
Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt
) instead of relative one.
Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.
curl_setopt($ch, CURLOPT_VERBOSE, true);
You can use DecimalFormat
. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.##
format.
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.
I find it easier to pass a value as a temporal data type (e.g. DATETIME
) then use temporal functionality, specifically DATEADD
and DATEPART
, to find the start and end dates for the period, in this case the month e.g. this finds the start date and end date pair for the current month, just substitute CURRENT_TIMESTAMP
for you parameter of of type DATETIME
(note the 1990-01-01 value is entirely arbitrary):
SELECT DATEADD(M,
DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP),
'1990-01-01T00:00:00.000'),
DATEADD(M,
DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP),
'1990-01-31T23:59:59.997')
You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.
print $ids
should be a fairly hard statement to mess up, but it is possible. Possible reasons:
$ids
is undefined. Gives the warning undefined value in print
$ids
is out of scope. With use
strict
, gives fatal warning Global
variable $ids needs explicit package
name
, and otherwise the undefined
warning from above.print $ids $nIds
,
in which case perl thinks that $ids
is supposed to be a filehandle, and
you get an error such as print to
unopened filehandle
.Explanations
1: Should not happen. It might happen if you do something like this (assuming you are not using strict
):
my $var;
while (<>) {
$Var .= $_;
}
print $var;
Gives the warning for undefined value, because $Var
and $var
are two different variables.
2: Might happen, if you do something like this:
if ($something) {
my $var = "something happened!";
}
print $var;
my
declares the variable inside the current block. Outside the block, it is out of scope.
3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings
.
4: Also a common mistake. There are a number of ways to correctly print two variables in the same print
statement:
print "$var1 $var2"; # concatenation inside a double quoted string
print $var1 . $var2; # concatenation
print $var1, $var2; # supplying print with a list of args
Lastly, some perl magic tips for you:
use strict;
use warnings;
# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;
# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;
my $ids = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";
Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.
Variations:
print "@file"
is equivalent to
$ids = join(' ',@file); print $ids;
$#file
will return the last index
in @file
. Since arrays usually start at 0,
$#file + 1
is equivalent to scalar @file
. You can also do:
my $ids;
do {
local $/;
$ids = <$fh>;
}
By temporarily "turning off" $/
, the input record separator, i.e. newline, you will make <$fh>
return the entire file. What <$fh>
really does is read until it finds $/
, then return that string. Note that this will preserve the newlines in $ids
.
Line-by-line solution:
open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
chomp;
$ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.
Just for a sake of completeness, if you need to find all positions of a character in a string, you can do the following:
s = 'shak#spea#e'
c = '#'
print([pos for pos, char in enumerate(s) if char == c])
which will print: [4, 9]
I think that Proguard is the best. It is also possible to integrate it with your IDE (for example NetBeans). However, consider that if you obfuscate your code it could be difficult to track problems in your logs..
from collections import OrderedDict
OrderedDict((word, True) for word in words)
contains
OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)])
If the values are True
(or any other immutable object), you can also use:
OrderedDict.fromkeys(words, True)
The only solution you have right now is to parse the HTML, build up some nodes with given point/font/etc attributes, then combine them together into an NSAttributedString. It's a lot of work, but if done correctly, can be reusable in the future.
You would get an error for using sns.figure.savefig("output.png")
in seaborn 0.8.1.
Instead use:
import seaborn as sns
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")
I have searched for this a few minutes and i couldn't find any working code.
But now i finaly did it ! Take a look:
<div class="input-group" id="unified-inputs">
<input type="text" class="form-control" placeholder="MinVal" />
<input type="text" class="form-control" placeholder="MaxVal" />
</div>
And css
#unified-inputs.input-group { width: 100%; }
#unified-inputs.input-group input { width: 50% !important; }
#unified-inputs.input-group input:last-of-type { border-left: 0; }
This is a further optimisation.
\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)
\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*(\d{1,2})$
(i) allows for valid international prefixes
(ii) followed by 9 or 10 digits, with any type or placing of delimeters (except between the last two digits)
This will match:
+1-234-567-8901
+61-234-567-89-01
+46-234 5678901
+1 (234) 56 89 901
+1 (234) 56-89 901
+46.234.567.8901
+1/234/567/8901
None of the existing answers worked in my case (Android studio 3.5.0). I had to
If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:
from collections import OrderedDict
order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)
You could use an fstream
and open it with the std::ios::app
flag. Have a look at the code below and it should clear your head.
...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...
You can find more information about the open modes here and about fstreams here.
Just from reading that i would have never understood that "$@"
expands into a list of separate parameters. Whereas, "$*"
is one parameter consisting of all the parameters added together.
If it still makes no sense do this.
http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/
This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
The query()
function returns an object, you'll want fetch a record from what's returned from that function. Look at the examples on this page to learn how to print data from mysql
It doesn't set the default value because your model isn't bound to the id or name properties, it's bound to each version
object. Try setting the versionID
to one of the objects and it should work, ie $scope.item.versionID = $scope.versions[2];
If you want to set by the id property then you need to add the select as
syntax:
ng-options="version.id as version.name for version in versions"
Use start /w programname to wait for the end of programname
START /W notepad
ECHO Back from notepad
START /W wordpad
ECHO Back from wordpad
START /W notepad
Maybe you have a file/directory named test
in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.
To force rebuild on these kind of not-file-related targets, you should make them phony as follows:
.PHONY: all test clean
Note that you can declare all of your phony targets there.
A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.
I know this is kind of old and has been marked as answers with 147 up votes, but there is something else to consider.
You can have all the model errors, the property named and string.Empty keys alike, be shown in the ValidationSummary if you need to. There is an overload in the ValidationSummary that will do this.
// excludePropertyErrors:
// true to have the summary display model-level errors only, or false to have
// the summary display all errors.
public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors);
Finally I have found a solution to get random and unique values.
My solution is:
substr(md5(time()), 0, 12)
time
always return a timestamp, and it is always unique. You can use it with MD5 to make it better.
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
HTML
? ✕
? ✓
? ✖
? ✔
? ✗
? ✘
× ×
×
CSS
If you want to use the above characters from CSS (like i.e: in an :before
or :after
pseudo) simply use the escaped \
Unicode HEX value, like for example:
[class^="ico-"], [class*=" ico-"]{
font: normal 1em/1 Arial, sans-serif;
display: inline-block;
}
.ico-times:before{ content: "\2716"; }
.ico-check:before{ content: "\2714"; }
_x000D_
<i class="ico-times" role="img" aria-label="Cancel"></i>
<i class="ico-check" role="img" aria-label="Accept"></i>
_x000D_
✕
HTML'\2715'
CSS like i.e: .clear:before { content: '\2715'; }
'\u2715'
JavaScript stringCheckout AcrossTabs - Easy communication between cross-origin browser tabs. It uses a combination of postMessage and sessionStorage API to make communication much easier and reliable.
There are different approaches and each one has its own advantages and disadvantages. Lets discuss each:
Pros:
Cons:
Pros:
Cons:
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
Typically, the following are allowed:
Pros:
localStorage
.Cons:
localStorage
, tt works on same-origin policy. So, data stored will only be able available on the same origin.Pros:
Cons:
targetOrigin
and a sanity check for the data being passed on to the messages listener.A combination of PostMessage + SessionStorage
Using postMessage to communicate between multiple tabs and at the same time using sessionStorage in all the newly opened tabs/windows to persist data being passed. Data will be persisted as long as the tabs/windows remain opened. So, even if the opener tab/window gets closed, the opened tabs/windows will have the entire data even after getting refreshed.
I have written a JavaScript library for this, named AcrossTabs which uses postMessage API to communicate between cross-origin tabs/windows and sessionStorage to persist the opened tabs/windows identity as long as they live.
There are multiple ways of doing that you can use either place
or grid
or even the pack
method.
Sample code:
from tkinter import *
root = Tk()
l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.
To place a widget to on basis of columns and rows , use the grid method:
but = Button(root, text="hello" )
but.grid(row=0, column=1)
You should always catch exceptions as concrete as possible, so you should use
try
{
//code
}
catch (Web2PDFException ex)
{
//Handle the exception here
}
You chould of course use something like this if you insist:
try
{
}
catch (Exception err)
{
if (err is Web2PDFException)
{
//Code
}
}
Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.
I would like to add an extending answer referring to different C# versions and because of two reasons:
The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.
No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).
Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.
Since .NET 3.5 there also exists a generic method Array<T>.Exists()
:
public void PrinterSetup(string[] printer)
{
if (Array.Exists(printer, x => x == "jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
}
}
You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same/similar ".Contains" as for strings for all arrays without including Linq:
// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
if (printer.ArrayContains("jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
}
}
public static bool ArrayContains<T>(this T[] thisArray, T searchElement)
{
// If you want this to find "null" values, you could change the code here
return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}
In this case this ArrayContains()
method is used and not the Contains method of Linq.
The elsewhere mentioned .Contains methods refer to List<T>.Contains
(since C# 2.0) or ArrayList.Contains
(since C# 1.1), but not to arrays itself directly.
for cordova developers having this issue
try to set
<preference name="deployment-target" value="8.0" />
in confix.xml
The copyright notice on a work establishes a claim to copyright. The date on the notice establishes how far back the claim is made. This means if you update the date, you are no longer claiming the copyright for the original date and that means if somebody has copied the work in the meantime and they claim its theirs on the ground that their publishing the copy was before your claim, then it will be difficult to establish who is the originator of the work.
Therefore, if the claim is based on common law copyright (not formally registered), then the date should be the date of first publication. If the claim is a registered copyright, then the date should be the date claimed in the registration. In cases where the work was substantially revised you may establish a new copyright claim to the revised work by adding another copyright notice with a newer date or by adding an additional date to the existing notice as in "© 2000, 2010". Again, the added date establishes how far back the claim is made on the revision.
You can use ASP.NET to generate your HTML outside the context of web pages. Here's an article that shows how it can be done.
To get Token Device you can do by some steps:
1) Enable APNS (Apple Push Notification Service) for both Developer Certification and Distribute Certification, then redownload those two file.
2) Redownload both Developer Provisioning and Distribute Provisioning file.
3) In Xcode interface: setting provisioning for PROJECT and TARGETS with two file provisioning have download.
4) Finally, you need to add the code below in AppDelegate file to get Token Device (note: run app in real device).
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
NSLog(@"Registering for push notifications...");
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
NSLog(@"%@", str);
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSString *str = [NSString stringWithFormat: @"Error: %@", err];
NSLog(@"%@",str);
}
<form method="post" name="myForm" id="myForm">
replace with above form tag remove action from form tag. and set url : "check.php" in ajax in your case first it goes to jQuery ajax then submit again the form. that's why it's creating issue.
i know i'm too late for this reply but i think it would help.
Why not use the built in events?
$('#checkbox').click(function(e){
if(e.target.checked) {
// code to run if checked
console.log('Checked');
} else {
//code to run if unchecked
console.log('Unchecked');
}
});
My cause was different I referenced a web service then I got this message.
Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.
hope this helps!
I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:
// make_string
class make_string {
public:
template <typename T>
make_string& operator<<( T const & val ) {
buffer_ << val;
return *this;
}
operator std::string() const {
return buffer_.str();
}
private:
std::ostringstream buffer_;
};
And then you use it as;
string str = make_string() << 6 << 8 << "hello";
Quite nifty!
Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)
// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
std::stringstream buf;
buf << str;
RETURN_TYPE val;
buf >> val;
return val;
}
Use as:
int x = parse_string<int>("78");
You might also want versions for wstrings.
If your local nameserver is down,
ping 4.2.2.1
is an easy-to-remember always-up IP (it's actually a nameserver, even).
You can do something like this to read 10 bytes:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
remember read() doesn't add '\0'
to terminate to make it string (just gives raw buffer).
To read 1 byte at a time:
char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
//do stuff
}
and don't forget to #include <unistd.h>
, STDIN_FILENO
defined as macro in this file.
There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:
Integer value Name
0 Standard input (stdin)
1 Standard output (stdout)
2 Standard error (stderr)
So instead STDIN_FILENO
you can use 0.
Edit:
In Linux System you can find this using following command:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
Notice the comment /* Standard input. */
How about using overloaded ArrayList constructor.
private ArrayList<String> symbolsPresent = new ArrayList<String>(Arrays.asList(new String[] {"One","Two","Three","Four"}));
You are not initializing connection.That's why this kind of error is coming to you.
Your code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
Corrected code:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);
Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument()
method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.
In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.
Here is a function I use (it's part of the Browser compatibility library I'm currently building):
function LoadXMLString(xmlString)
{
// ObjectExists checks if the passed parameter is not null.
// isString (as the name suggests) checks if the type is a valid string.
if (ObjectExists(xmlString) && isString(xmlString))
{
var xDoc;
// The GetBrowserType function returns a 2-letter code representing
// ...the type of browser.
var bType = GetBrowserType();
switch(bType)
{
case "ie":
// This actually calls into a function that returns a DOMDocument
// on the basis of the MSXML version installed.
// Simplified here for illustration.
xDoc = new ActiveXObject("MSXML2.DOMDocument")
xDoc.async = false;
xDoc.loadXML(xmlString);
break;
default:
var dp = new DOMParser();
xDoc = dp.parseFromString(xmlString, "text/xml");
break;
}
return xDoc;
}
else
return null;
}
Try this simple LINQ:
//For a file list/array
var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
//simply use Where ! x.Contains
var notContain = files.Where(x => ! x.Contains(@"\$RECYCLE.BIN\")).ToList();
//Or use Except()
var containing = files.Where(x => x.Contains(@"\$RECYCLE.BIN\")).ToList();
notContain = files.Except(containing).ToList();
Use a HashSet<T>
. For example:
var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
Console.WriteLine(s);
prints
A B D C
Just use CASCADE
TRUNCATE "products" RESTART IDENTITY CASCADE;
But be ready for cascade deletes )
I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line
; On windows: extension_dir = "ext"
I changed it to:
; On windows: extension_dir = "C:\php\ext"
And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.
$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p));
for dynamic merging of cells
This worked for me. TypeScript Version: 2.8.3
for (const [key, value] of Object.entries(myMap)) {
console.log(key, value);
}
Another modelling tool for Java is (my) website GitUML. Generate UML diagrams from Java or Python code stored in GitHub repositories.
One key idea with GitUML is to address one of the problems with "documentation": that diagrams are always out of date. With GitUML, diagrams automatically update when you push code using git.
Browse through community UML diagrams, there are some Java design patterns there. Surf through popular GitHub repositories and visualise the architectures and patterns in them.
Create diagrams using point and click. There is no drag drop editor, just click on the classes in the repository tree that you want to visualise:
The underlying technology is PlantUML based, which means you can refine your diagrams with additional PlantUML markup.
Here is some code telling about priority of all log4net levels:
TraceLevel(Level.All); //-2147483648
TraceLevel(Level.Verbose); // 10 000
TraceLevel(Level.Finest); // 10 000
TraceLevel(Level.Trace); // 20 000
TraceLevel(Level.Finer); // 20 000
TraceLevel(Level.Debug); // 30 000
TraceLevel(Level.Fine); // 30 000
TraceLevel(Level.Info); // 40 000
TraceLevel(Level.Notice); // 50 000
TraceLevel(Level.Warn); // 60 000
TraceLevel(Level.Error); // 70 000
TraceLevel(Level.Severe); // 80 000
TraceLevel(Level.Critical); // 90 000
TraceLevel(Level.Alert); // 100 000
TraceLevel(Level.Fatal); // 110 000
TraceLevel(Level.Emergency); // 120 000
TraceLevel(Level.Off); //2147483647
private static void TraceLevel(log4net.Core.Level level)
{
Debug.WriteLine("{0} = {1}", level, level.Value);
}
I solved the problem by enabling the TCP/IP using the SQL Server Configuration Manager under Protocols for SQLEXPRESS2008, i restarted the service and now the "Server is listening on" shows up in the ERRORLOG file
A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.
A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.
def foo():
"This is a doc string."
# A single line comment
"""
This
is a multiline
comment/String
"""
"""
print "This is a sample foo function"
print "This function has no arguments"
"""
return True
Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a #
in front of every line under the selection. Ctrl + Shift + K is for block uncomment.
you can convert like below code snippet
Collection<A> obj=new Collection<return ListRetunAPI()>
All three define the meaning of zero in different context.
These three are always different when you look at the memory:
NULL - 0x00000000 or 0x00000000'00000000 (32 vs 64 bit)
NUL - 0x00 or 0x0000 (ascii vs 2byte unicode)
'0' - 0x20
I hope this clarifies it.
Open base_facebook.php
Add Access_token at function getLoginUrl()
array_merge(array(
'access_token' => $this->getAccessToken(),
'client_id' => $this->getAppId(),
'redirect_uri' => $currentUrl, // possibly overwritten
'state' => $this->state),
$params);
and Use scope for Email Permission
if ($user) {
echo $logoutUrl = $facebook->getLogoutUrl();
} else {
echo $loginUrl = $facebook->getLoginUrl(array('scope' => 'email,read_stream'));
}
If you are using HUE this is fairly simple as well. Simply go to the Hive editor in HUE, execute your hive query, then save the result file locally as XLS or CSV, or you can save the result file to HDFS.
It depends upon lower_case_table_names
system variable:
show variables where Variable_name='lower_case_table_names'
There are three possible values for this:
0
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement. Name comparisons are case sensitive. 1
- Table names are stored in lowercase on disk and name comparisons are not case sensitive. 2
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement, but MySQL converts them to lowercase on lookup.
Name comparisons are not case sensitive.In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal()
, the compiler needs to see the declaration:
double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc
or *.cpp
) file. This neatly solves the problem of needing all the functions to be declared.
Activation by system properties can be done as follows
<activation>
<property>
<name>foo</name>
<value>bar</value>
</property>
</activation>
And run the mvn build with -D to set system property
mvn clean install -Dfoo=bar
This method also helps select profiles in transitive dependency of project artifacts.
These are all a matter of convenience.
Basically, if the question were 'Do we need to use body-parser
?' The answer is 'No'. We can come up with the same information from the client-post-request using a more circuitous route that will generally be less flexible and will increase the amount of code we have to write to get the same information.
This is kind of the same as asking 'Do we need to use express
to begin with?' Again, the answer there is no, and again, really it all comes down to saving us the hassle of writing more code to do the basic things that express comes with 'built-in'.
On the surface - body-parser
makes it easier to get at the information contained in client requests in a variety of formats instead of making you capture the raw data streams and figuring out what format the information is in, much less manually parsing that information into useable data.
Try this,to retrieve all files inside folder and sub-folder
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
To retrieve files/folder only
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
System.out.println(f.getName());
if(f.isFile()){
System.out.println(f.getName());
}
}
}
While creating a project from a full folder may or may not work within the workspace, there's a condition outside of the workspace that prevents starting a new project with a full folder.
This is relevant if you use numerous folder locations for sources, for example an htdocs or www folder for web projects, and a different location for desktop Java applications.
The condition mentioned occurs when Eclipse is told to create a new project, and given a full folder outside the workspace. Eclipse will say the folder isn't empty, and prevent creating a new project within the given folder. I haven't found a way around this, and any solution requires extra steps.
My favorite solution is as follows
Eclipse should make a new project, and update that project with the new folder contents as it scans for changes. The existing sources are now part of the new project.
Although you had to perform three extra steps, you now have a backup with the original sources available, and are also able to use a copy of them in an existing project. If storage space is a concern, simply move/cut the source rather than fully copy the original folder contents.
Simply use this
onclick="location.href='pageurl.html';"
Also, consider to use a repository manager such as Nexus and configure all your repositories there.
.class {
background-color:none;
}
This is not a valid property. W3C validator will display following error:
Value Error : background-color none is not a background-color value : none
transparent
may have been selected as better term instead of 0
or none
values during the development of specification of CSS.
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
There is some flickering problem in {{ }} like when you refresh the page then for a short spam of time expression is seen.So we should use ng-bind instead of expression for data depiction.
There is no difference. A primary key is a candidate key. By convention one candidate key in a relation is usually chosen to be the "primary" one but the choice is essentially arbitrary and a matter of convenience for database users/designers/developers. It doesn't make a "primary" key fundamentally any different to any other candidate key.
Use INDIRECT()
=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))
Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.
yes | execute_command
This will use yes as the answer to all yes/no prompts.
Platform independent solution in one line is
Python 2:
python -c "import sys; print sys.executable"
Python 3:
python -c "import sys; print(sys.executable)"
Based on zapl's answer, adding try()
around Closeable
's closes the streams automatically after use.
public static void unzip(File zipFile, File targetDirectory) {
try (FileInputStream fis = new FileInputStream(zipFile)) {
try (BufferedInputStream bis = new BufferedInputStream(fis)) {
try (ZipInputStream zis = new ZipInputStream(bis)) {
ZipEntry ze;
int count;
byte[] buffer = new byte[Constant.DefaultBufferSize];
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;
try (FileOutputStream fout = new FileOutputStream(file)) {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
}
}
}
}
} catch (Exception ex) {
//handle exception
}
}
Using Constant.DefaultBufferSize
(65536
) gotten from C# .NET 4
Stream.CopyTo from Jon Skeet's answer here:
https://stackoverflow.com/a/411605/1876355
I always just see posts using byte[1024]
or byte[4096]
buffer, never knew it can be much larger which improves performance and is still working perfectly normal.
Here is the Stream
Source code:
https://referencesource.microsoft.com/#mscorlib/system/io/stream.cs
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int _DefaultCopyBufferSize = 81920;
However, I dialed it back to 65536
which is also a multiple of 4096
just to be safe.
The problem with Threading.Thread.SLeep(2000)
is that it executes first in my VB.Net program. This
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
worked flawlessly.
Set the height of the parent element, and give that the width. Then use a background image with the rule "background-size: cover"
.parent {
background-image: url(../img/team/bgteam.jpg);
background-repeat: no-repeat;
background-position: center center;
-webkit-background-size: cover;
background-size: cover;
}
Add { } while importing and exporting:
export { ... };
|
import { ... } from './Template';
export → import { ... } from './Template'
export default → import ... from './Template'
Here is a working example:
// ExportExample.js
import React from "react";
function DefaultExport() {
return "This is the default export";
}
function Export1() {
return "Export without default 1";
}
function Export2() {
return "Export without default 2";
}
export default DefaultExport;
export { Export1, Export2 };
// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";
export default function App() {
return (
<>
<strong>
<DefaultExport />
</strong>
<br />
<Export1 />
<br />
<Export2 />
</>
);
}
??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark
Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.
As pointed out, you can use getElementById
instead, but you can also still achieve the same with a querySelector
:
document.querySelector("[id='22']")
In Ruby 2.5 you can now use Dir.children
. It gets filenames as an array except for "." and ".."
Example:
Dir.children("testdir") #=> ["config.h", "main.rb"]
If you don't care about the type of the numbers you can simply use:
qs[0].values()
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
:::::HTML:::::
<input type="text" onkeypress="return lettersValidate(event)" />
Only letters no spaces
::::JS::::::::
// ===================== Allow - Only Letters ===============================================================
function lettersValidate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))
{
return true;
}
else
{
return false;
}
}
I encountered a similar problem when I was using the below to obtain connection factory
ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");
Its resolved when I changed it to the below
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");
The below then showed that my Q size was increasing..
http://:8161/admin/queues.jsp
This callable function works perfectly, returns true for valid date. Be sure to call using a date on ISO format (yyyy-mm-dd or yyyy/mm/dd):
function validateDate(isoDate) {
if (isNaN(Date.parse(isoDate))) {
return false;
} else {
if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
return false;
}
}
return true;
}
Underscore-java library contains methods push(values), pop(), shift() and unshift(values).
Code example:
import com.github.underscore.U:
List<String> strings = Arrays.asList("one", "two", " three");
List<String> newStrings = U.push(strings, "four", "five");
// ["one", " two", "three", " four", "five"]
String newPopString = U.pop(strings).fst();
// " three"
String newShiftString = U.shift(strings).fst();
// "one"
List<String> newUnshiftStrings = U.unshift(strings, "four", "five");
// ["four", " five", "one", " two", "three"]
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
You should also ensure you set a reference to WindowsBase
. This is required to use the SDK as it handles System.IO.Packaging
(which is used for unzipping and opening the compressed .docx/.xlsx/.pptx as an OPC document).
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
It is better to create new environment with new name ($newenv):conda create -n $newenv tensorflow
Then by using anaconda navigator under environment tab you can find newenv in the middle column.
By clicking on the play button open terminal and type: activate tensorflow
Then install tensorflow inside the newenv by typing: pip install tensorflow
Now you have tensorflow inside the new environment so then install jupyter by typing: pip install jupyter notebook
Then just simply type: jupyter notebook
to run the jupyter notebook.
Inside of the jupyter notebook type: import tensorflow as tf
To test the the tf you can use THIS LINK
This is also an option:
x==2 && dosomething();
dosomething()
will only be called if x==2
is evaluated to true. This is called Short-circuiting.
It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:
if(x==2) dosomething();
You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)
I actually came across something like this not too long ago... check it out over on msdn (see the first answer)
in summary:
.cer - certificate stored in the X.509 standard format. This certificate contains information about the certificate's owner... along with public and private keys.
.pvk - files are used to store private keys for code signing. You can also create a certificate based on .pvk private key file.
.pfx - stands for personal exchange format. It is used to exchange public and private objects in a single file. A pfx file can be created from .cer file. Can also be used to create a Software Publisher Certificate.
I summarized the info from the page based on the suggestion from the comments.
You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
#include <string>
std::string wstrtostr(const std::wstring &wstr)
{
// Convert a Unicode string to an ASCII string
std::string strTo;
char *szTo = new char[wstr.length() + 1];
szTo[wstr.size()] = '\0';
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
strTo = szTo;
delete[] szTo;
return strTo;
}
std::wstring strtowstr(const std::string &str)
{
// Convert an ASCII string to a Unicode String
std::wstring wstrTo;
wchar_t *wszTo = new wchar_t[str.length() + 1];
wszTo[str.size()] = L'\0';
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
wstrTo = wszTo;
delete[] wszTo;
return wstrTo;
}
--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.
So you can understand this better:
//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
*pX = 10;
}
int main(int argc, char ** argv)
{
int X;
fillXWith10(&X);
return 0;
}
Only, if they accept different parameters. If there are no parameters, then you must have different names.
int doSomething(String s);
String doSomething(int); // this is fine
int doSomething(String s);
String doSomething(String s); // this is not
This is a simple way from XML only
spanCount for number of columns
layoutManager for making it grid or linear(Vertical or Horizontal)
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/personListRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
In our case, we receive an XML as a String
and need to get rid of the values that have some "special" characters, like &<>
etc. Basically someone can provide an XML to us in this form:
<notes>
<note>
<to>jenice & carl </to>
<from>your neighbor <; </from>
</note>
</notes>
So I need to find in that String
the values jenice & carl
and your neighbor <;
and properly escape &
and <
(otherwise this is an invalid xml if you later pass it to an engine that shall rename unnamed).
Doing this with regex is a rather dumb idea to begin with, but it's cheap and easy. So the brave ones that would like to do the same thing I did, here you go:
String xml = ...
Pattern p = Pattern.compile("<(.+)>(?!\\R<)(.+)</(\\1)>");
Matcher m = p.matcher(xml);
String result = m.replaceAll(mr -> {
if (mr.group(2).contains("&")) {
return "<" + m.group(1) + ">" + m.group(2) + "+ some change" + "</" + m.group(3) + ">";
}
return "<" + m.group(1) + ">" + mr.group(2) + "</" + m.group(3) + ">";
});
The issue Unexpected token '<' is because of missing the babel preset.
Solution : You have to configure your webpack configuration as follows
{
test : /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader : 'babel',
query : {
presets:[ 'react', 'es2015' ]
}
}
here .jsx checks both .js and .jsx formats.
you can simply install the babel dependency using node as follows
npm install babel-preset-react
Thank you
$location / switching between html5 and hashbang mode / link rewriting
The answers that use pattern and a regex write the user's password into the input properties as plain text pattern='mypassword'
. This will only be visible if developer tools are open but it still doesn't seem like a good idea.
Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.
I also think these methods won't work well if the user switches between inputs.
Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.
For a real page you would change the input types to 'password'.
<form>
<input type="text" id="password1" oninput="setPasswordConfirmValidity();">
<input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
function setPasswordConfirmValidity(str) {
const password1 = document.getElementById('password1');
const password2 = document.getElementById('password2');
if (password1.value === password2.value) {
password2.setCustomValidity('');
} else {
password2.setCustomValidity('Passwords must match');
}
console.log('password2 customError ', document.getElementById('password2').validity.customError);
console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
}
</script>
Division is performed using the /
operator:
result = a / b;
Modulo division is done using the %
operator:
result = a % b;
43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII
Try add 'commons-codec-1.8.jar' into your JRE folder!
As of conda 4.4, the command
conda activate <envname>
is the same on all platforms. The procedure to add conda
to the PATH
environment variable for non-Windows platforms (on Windows you should use the Anaconda Prompt), as well as the change in environment activation procedure, is detailed in the release notes for conda 4.4.0.
For conda versions older than 4.4, command is either
source activate <envname>
on Linux and macOS or
activate <envname>
on Windows. You need to remove the conda
.
Sometimes you don't want to join multiple filters together like this:
def your_dynamic_query_generator(self, event: Event):
qs \
.filter(shiftregistrations__event=event) \
.filter(shiftregistrations__shifts=False)
And the following code would actually not return the correct thing.
def your_dynamic_query_generator(self, event: Event):
return Q(shiftregistrations__event=event) & Q(shiftregistrations__shifts=False)
What you can do now is to use an annotation count-filter.
In this case we count all shifts which belongs to a certain event.
qs: EventQuerySet = qs.annotate(
num_shifts=Count('shiftregistrations__shifts', filter=Q(shiftregistrations__event=event))
)
Afterwards you can filter by annotation.
def your_dynamic_query_generator(self):
return Q(num_shifts=0)
This solution is also cheaper on large querysets.
Hope this helps.
div.section > div
Yo can use joda time.
private Date dateWitoutTime(Date date){
return new LocalDate(date).toDate()
}
and you call with:
Date date = new Date();
System.out.println("Without Time = " + dateWitoutTime(date) + "/n With time = " + date);
just :
mydict = {'A':4,'B':10,'C':0,'D':87}
max(mydict.items(), key=lambda x: x[1])
If you've deleted your root
user by mistake you can do one thing:
mysqld_safe --skip-grant-tables &
mysql -u root -p
and press enter.use mysql;
Then execute this query:
insert into `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
then restart the mysqld
EDIT: October 6, 2018
In case anyone else needs this answer, I tried it today using innodb_version 5.6.36-82.0 and 10.1.24-MariaDB and it works if you REMOVE THE BACKTICKS (no single quotes either, just remove them):
insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, ssl_type, ssl_cipher, x509_issuer, x509_subject, max_questions, max_updates, max_connections, max_user_connections)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
There are two categories as follows
Core java is a language basics. For example (Data structures, Semantics..etc) https://malalanayake.wordpress.com/category/java/data-structures/
But if you see the Java EE you can see the Sevlet, JSP, JSF all the web technologies and the patterns. https://malalanayake.wordpress.com/2014/10/10/jsp-servlet-scope-variables-and-init-parameters/
I know this question is old and has lots of great answers but I post this answer because of it's new flavor (es5+)
Object.defineProperties(JSON, {_x000D_
refStringify: {_x000D_
value: function(obj) {_x000D_
_x000D_
let objMap = new Map();_x000D_
let stringified = JSON.stringify(obj,_x000D_
function(key, value) {_x000D_
_x000D_
// only for objects_x000D_
if (typeof value == 'object') {_x000D_
// If has the value then return a reference to it_x000D_
if (objMap.has(value))_x000D_
return objMap.get(value);_x000D_
_x000D_
objMap.set(value, `ref${objMap.size + 1}`);_x000D_
}_x000D_
return value;_x000D_
});_x000D_
return stringified;_x000D_
}_x000D_
},_x000D_
refParse: {_x000D_
value: function(str) {_x000D_
_x000D_
let parsed = JSON.parse(str);_x000D_
let objMap = _createObjectMap(parsed);_x000D_
objMap.forEach((value, key) => _replaceKeyWithObject(value, key));_x000D_
return parsed;_x000D_
}_x000D_
},_x000D_
});_x000D_
_x000D_
// *************************** Example_x000D_
let a = {_x000D_
b: 32,_x000D_
c: {_x000D_
get a() {_x000D_
return a;_x000D_
},_x000D_
get c() {_x000D_
return a.c;_x000D_
}_x000D_
}_x000D_
};_x000D_
let stringified = JSON.refStringify(a);_x000D_
let parsed = JSON.refParse(stringified, 2);_x000D_
console.log(parsed, JSON.refStringify(parsed));_x000D_
// *************************** /Example_x000D_
_x000D_
// *************************** Helper_x000D_
function _createObjectMap(obj) {_x000D_
_x000D_
let objMap = new Map();_x000D_
JSON.stringify(obj, (key, value) => {_x000D_
if (typeof value == 'object') {_x000D_
if (objMap.has(value))_x000D_
return objMap.get(value);_x000D_
objMap.set(value, `ref${objMap.size + 1}`);_x000D_
_x000D_
}_x000D_
return value;_x000D_
});_x000D_
return objMap;_x000D_
}_x000D_
_x000D_
function _replaceKeyWithObject(key, obj, replaceWithObject = obj) {_x000D_
_x000D_
Object.keys(obj).forEach(k => {_x000D_
_x000D_
let val = obj[k];_x000D_
if (val == key)_x000D_
return (obj[k] = replaceWithObject);_x000D_
if (typeof val == 'object' && val != replaceWithObject)_x000D_
_replaceKeyWithObject(key, val, replaceWithObject);_x000D_
});_x000D_
}
_x000D_
This is an issue with the 64 bit version of Kepler and windows7 in my case. I downloaded the 32 bit and it worked immediately.
The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:
body {
margin: 0;
padding: 0;
text-align: center;
}
#main_container {
margin: 0 auto;
text-align: left;
}
If you are just visiting a webpage that you trust and you want to move forward fast, just:
1- Click the shield icon in the far right of the address bar.
2- In the pop-up window, click "Load anyway" or "Load unsafe script" (depending on your Chrome version).
If you want to set your Chrome browser to ALWAYS(in all webpages) allow mixed content:
1- In an open Chrome browser, press Ctrl+Shift+Q on your keyboard to force close Chrome. Chrome must be fully closed before the next steps.
2- Right-click the Google Chrome desktop icon (or Start Menu link). Select Properties.
3- At the end of the existing information in the Target field, add: " --allow-running-insecure-content" (There is a space before the first dash.)
4- Click OK.
5- Open Chrome and try to launch the content that was blocked earlier. It should work now.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
Update: since the time I answered this there has been a lot of work on this look at Apache Arrow for a better read and write of parquet. Also: http://wesmckinney.com/blog/python-parquet-multithreading/
There is a python parquet reader that works relatively well: https://github.com/jcrobak/parquet-python
It will create python objects and then you will have to move them to a Pandas DataFrame so the process will be slower than pd.read_csv
for example.
Check the permissions on the .pem file...openssh usually doesn't like world-readable private keys, and will fail (iir, scp doesn't do a great job of providing this feedback to the user).
Can you simply ssh with that key to your AWS host?
Sushant Gupta's answers are a tad bit outdated and don't work anymore.
The following snippet should be like this now :
collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});
Yes, there is a way. Two in fact. In October 2013 jshint added a way to ignore blocks of code like this:
// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */
// Code here will be linted with JSHint.
You can also ignore a single line with a trailing comment like this:
ignoreThis(); // jshint ignore:line
If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by
with out the need of any aggregate functions.
So the query can be simplified to this.
select * from comments_table group by commentname;
Try out the query in action here
let
and var
?var
statement is known throughout the function it is defined in, from the start of the function. (*)let
statement is only known in the block it is defined in, from the moment it is defined onward. (**)To understand the difference, consider the following code:
// i IS NOT known here
// j IS NOT known here
// k IS known here, but undefined
// l IS NOT known here
function loop(arr) {
// i IS known here, but undefined
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
for( var i = 0; i < arr.length; i++ ) {
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
};
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
for( let j = 0; j < arr.length; j++ ) {
// i IS known here, and has a value
// j IS known here, and has a value
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
};
// i IS known here, and has a value
// j IS NOT known here
// k IS known here, but has a value only the second time loop is called
// l IS NOT known here
}
loop([1,2,3,4]);
for( var k = 0; k < arr.length; k++ ) {
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here
};
for( let l = 0; l < arr.length; l++ ) {
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS known here, and has a value
};
loop([1,2,3,4]);
// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here
Here, we can see that our variable j
is only known in the first for loop, but not before and after. Yet, our variable i
is known in the entire function.
Also, consider that block scoped variables are not known before they are declared because they are not hoisted. You're also not allowed to redeclare the same block scoped variable within the same block. This makes block scoped variables less error prone than globally or functionally scoped variables, which are hoisted and which do not produce any errors in case of multiple declarations.
let
today?Some people would argue that in the future we'll ONLY use let statements and that var statements will become obsolete. JavaScript guru Kyle Simpson wrote a very elaborate article on why he believes that won't be the case.
Today, however, that is definitely not the case. In fact, we need actually to ask ourselves whether it's safe to use the let
statement. The answer to that question depends on your environment:
If you're writing server-side JavaScript code (Node.js), you can safely use the let
statement.
If you're writing client-side JavaScript code and use a browser based transpiler (like Traceur or babel-standalone), you can safely use the let
statement, however your code is likely to be anything but optimal with respect to performance.
If you're writing client-side JavaScript code and use a Node based transpiler (like the traceur shell script or Babel), you can safely use the let
statement. And because your browser will only know about the transpiled code, performance drawbacks should be limited.
If you're writing client-side JavaScript code and don't use a transpiler, you need to consider browser support.
There are still some browsers that don't support let
at all :
For an up-to-date overview of which browsers support the let
statement at the time of your reading this answer, see this Can I Use
page.
(*) Globally and functionally scoped variables can be initialized and used before they are declared because JavaScript variables are hoisted. This means that declarations are always much to the top of the scope.
(**) Block scoped variables are not hoisted
Something that should work with all versions of ActiveRecord
without depending on options or activerecord methods that may or may not exist.
module PlainModel
def self.included(base)
plainclass = Class.new(ActiveRecord::Base) do
self.table_name = base.table_name
end
base.const_set(:Plain, plainclass)
end
end
# usage
class User < ActiveRecord::Base
include PlainModel
validates_presence_of :email
end
User.create(email: "") # fail due to validation
User::Plain.create(email: "") # success. no validation, no callbacks
user = User::Plain.find(1)
user.email = ""
user.save
TLDR: use a "different activerecord model" over the same table
For primitive values like numbers and strings this is an easy solution:
a = [1,2,3]
b = [3,2,1]
a.sort().toString() == b.sort().toString()
The call to sort()
will ensure that the order of the elements does not matter. The toString()
call will create a string with the values comma separated so both strings can be tested for equality.
For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
Second file will be "bg_edittext_normal.xml" paste the lines of code in it
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#F6F6F6" />
<stroke
android:width="2dip"
android:color="#F6F6F6" />
<corners android:radius="2dip" />
<padding
android:bottom="7dip"
android:left="7dip"
android:right="7dip"
android:top="7dip" />
</shape>
In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
<item android:drawable="@drawable/bg_edittext_normal"/>
</selector>
Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background
<EditText
:::::
:::::
android:background="@drawable/bg_edittext"
:::::
:::::
/>
System.exit is needed
In your case, it does the exact same thing as the simple return-from-main.
You can find an easy guide here
The step are 2: - Copy the icon in the correct folder/folders - Change the AndroidManifest.xml
butangDonload.php
$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;
Try this,
<?php
$name=$_SESSION['name'];
download($name);
function download($name){
$file = $nama_fail;
?>
I think you set it as
var data = [];
but after some time you made it like:
data = 'some thing which is not an array';
then
data.push('')
will not work as it is not an array anymore.
You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:
pip install some-package.whl
If you have problem to install the wheel read this answer
Here's a more concise approach...
df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)
The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.
Result:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
NOTE: sort
is deprecated, use sort_values
instead
Sometimes the formatting is different in a cell when using print(res)
, but jupyter/ipython comes with a display
. See an example of the formatting difference using pandas below.
%%time
import pandas as pd
from IPython.display import display
df = pd.DataFrame({"col0":{"a":0,"b":0}
,"col1":{"a":1,"b":1}
,"col2":{"a":2,"b":2}
})
#compare the following
print(df)
display(df)
char *a = "stack overflow";
char *b = "new string, it's real";
int d = strlen(a);
b = malloc(d * sizeof(char));
b = strcpy(b,a);
printf("%s %s\n", a, b);
This will list all jpg
files in the folder you define under url: and append them to a div
as a paragraph. Can do it with ul li
as well.
$.ajax({
url: "YOUR FOLDER",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});
More cleaner way using LINQ
var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);
Uninitialized non-static members will contain random data. Actually, they will just have the value of the memory location they are assigned to.
Of course for object parameters (like string
) the object's constructor could do a default initialization.
In your example:
int *ptr; // will point to a random memory location
string name; // empty string (due to string's default costructor)
string *pname; // will point to a random memory location
string &rname; // it would't compile
const string &crname; // it would't compile
int age; // random value
Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.
Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.
How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.
How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.
Tools -> Options -> Source Control -> Current Source Control Plug-in: None
encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.
In the same location where the JVM's stdout is placed. If you have a Tomcat server, this will be the catalina_(date).out
file.
Shortest possible answer.
HTML
<a data-toggle="collapse" data-parent="#panel-quote-group" href="#collapseQuote">
<span class="toggle-icon glyphicon glyphicon-collapse-up"></span>
</a>
JS:
<script type="text/javascript">
$(function () {
$('a[data-toggle="collapse"]').click(function () {
$(this).find('span.toggle-icon').toggleClass('glyphicon-collapse-up glyphicon-collapse-down');
})
})
</script>
And of course, you can use anything for a selector instead of anchor tag a
and you can also use specific selector instead of this
if your icon lies outside your clicked element.
Often using a lock on a method level is too rude. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, you can create dummy objects to implement block level synchronization. The block level is more efficient because it does not lock the whole method.
Here some example
Method Level
class MethodLevel {
//shared among threads
SharedResource x, y ;
public void synchronized method1() {
//multiple threads can't access
}
public void synchronized method2() {
//multiple threads can't access
}
public void method3() {
//not synchronized
//multiple threads can access
}
}
Block Level
class BlockLevel {
//shared among threads
SharedResource x, y ;
//dummy objects for locking
Object xLock = new Object();
Object yLock = new Object();
public void method1() {
synchronized(xLock){
//access x here. thread safe
}
//do something here but don't use SharedResource x, y
// because will not be thread-safe
synchronized(xLock) {
synchronized(yLock) {
//access x,y here. thread safe
}
}
//do something here but don't use SharedResource x, y
//because will not be thread-safe
}//end of method1
}
[Edit]
For Collection
like Vector
and Hashtable
they are synchronized when ArrayList
or HashMap
are not and you need set synchronized keyword or invoke Collections synchronized method:
Map myMap = Collections.synchronizedMap (myMap); // single lock for the entire map
List myList = Collections.synchronizedList (myList); // single lock for the entire list
It would be much simpler to use the String.split method:
public static void fn(int guess) {
String[] sNums = Integer.toString(guess).split("");
for (String s : nums) {
...
To test for the existence of a command line paramater, use empty brackets:
IF [%1]==[] echo Value Missing
or
IF [%1] EQU [] echo Value Missing
The SS64 page on IF will help you here. Under "Does %1 exist?".
You can't set a positional parameter, so what you should do is do something like
SET MYVAR=%1
You can then re-set MYVAR based on its contents.
Use Convert.ToInt32() for conversion. You can have a look at How to convert string to ASCII value in C# and ASCII values.
With C++11 you can use the constexpr
keyword and write in your header:
private:
static constexpr const char* SOMETHING = "something";
Notes:
constexpr
makes SOMETHING
a constant pointer so you cannot write
SOMETHING = "something different";
later on.
Depending on your compiler, you might also need to write an explicit definition in the .cpp file:
constexpr const char* MyClass::SOMETHING;
I can't believe nobody offered plain shell:
while read -r a b c d; do echo "$d"; done < file
I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.
You can use the errorPlacement option to override the error message display with little css. Because css on its own will not be enough to produce the effect you need.
$(document).ready(function(){
$("#myForm").validate({
rules: {
"elem.1": {
required: true,
digits: true
},
"elem.2": {
required: true
}
},
errorElement: "div",
wrapper: "div", // a wrapper around the error message
errorPlacement: function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message'); // add a class to the wrapper
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
error.css('top', offset.top);
}
});
});
You can play with the left and top css attributes to show the error message on top, left, right or bottom of the element. For example to show the error on the top:
errorPlacement: function(error, element) {
element.before(error);
offset = element.offset();
error.css('left', offset.left);
error.css('top', offset.top - element.outerHeight());
}
And so on. You can refer to jQuery documentation about css for more options.
Here is the css I used. The result looks exactly like the one you want. With as little CSS as possible:
div.message{
background: transparent url(msg_arrow.gif) no-repeat scroll left center;
padding-left: 7px;
}
div.error{
background-color:#F3E6E6;
border-color: #924949;
border-style: solid solid solid none;
border-width: 2px;
padding: 5px;
}
And here is the background image you need:
(source: scriptiny.com)
If you want the error message to be displayed after a group of options or fields. Then group all those elements inside one container a 'div' or a 'fieldset'. Add a special class to all of them 'group' for example. And add the following to the begining of the errorPlacement function:
errorPlacement: function(error, element) {
if (element.hasClass('group')){
element = element.parent();
}
...// continue as previously explained
If you only want to handle specific cases you can use attr instead:
if (element.attr('type') == 'radio'){
element = element.parent();
}
That should be enough for the error message to be displayed next to the parent element.
You may need to change the width of the parent element to be less than 100%.
I've tried your code and it is working perfectly fine for me. Here is a preview:
I just made a very small adjustment to the message padding to make it fit in the line:
div.error {
padding: 2px 5px;
}
You can change those numbers to increase/decrease the padding on top/bottom or left/right. You can also add a height and width to the error message. If you are still having issues, try to replace the span with a div
<div class="group">
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</div>
And then give the container a width (this is very important)
div.group {
width: 50px; /* or any other value */
}
About the blank page. As I said I tried your code and it is working for me. It might be something else in your code that is causing the issue.
What client do you use? .Net, Java, Ruby, SQLPLUS, SQL DEVELOPER? Where did you write that simple select statement?
And why do you want to read the content of the blob, a blob contains binary data so that data is unreadable. You should use a clob instead of a blob if you want to store text instead of binary content.
I suggest that you download SQL DEVELOPER: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html . With SQL DEVELOPER you can see the content.
Here is Bjarne Stroustrup's wordings,
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
If you don't have another time interval bigger than days:
int days = (int) (milliseconds / (1000*60*60*24));
If you have weeks too:
int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));
It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.
You mean this?
git checkout destination_branch
git merge tag_name
I am using maven-assembly-plugin
for my maven packaging. The usage of Apache Maven Archiver in Joachim Sauer's answer could also work:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
<executions>
<execution .../>
</executions>
</plugin>
Because archiever is one of maven shared components, it could be used by multiple maven building plugins, which could also have conflict if two or more plugins introduced, including archive
configuration inside.
When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
Add the log4j.properties file to the runtime class path of the project. Some people add this to the root of the source tree (so that it gets copied to the root of the compiled classes).
Edit: If your project is a maven project, you can put the log4j.properties in the src/main/resources folder (and the src/test/resources for your unit tests).
If you have multiple environments (for example development and production), want different logging for each environment, and want to deploy the same jar (or war, or ear) file to each environment (as in one build for all environments) then store the log4j.properties file outside of the jar file and put it in the class path for each environment (configurable by environment). Historically, I would include some known directory in each environment in the classpath and deploy environment specific stuff there. For example, ~tomcat_user/localclasspath where ~tomcat_user is the home directory of the user that will be running the tomcat instance to which my war file will be deployed.
from xml :
app:tabIndicatorColor="#fff"
from java :
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
tabLayout.setSelectedTabIndicatorHeight((int) (2 * getResources().getDisplayMetrics().density));
Another easy way to do this is by using the following syntax to iterate through the object, keeping access to the key and value:
for(var key in object){
console.log(key + ' - ' + object[key])
}
so for yours:
for(var key in obj){
console.log(key + ' - ' + obj[key])
}
When I face this issue with TortoiseSVN (Windows), I go to Cygwin and run the 'svn cleanup' from there; it cleans up correctly for me, after which everything works from TortoiseSVN.
I am surprised that there's no concise answer yet, although such an expand/collapse animation is very easy to achieve with just 2 lines of code:
(recycler.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false // called once
together with
notifyItemChanged(position) // in adapter, whenever a child view in item's recycler gets hidden/shown
So for me, the explanations in the link below were really useful: https://medium.com/@nikola.jakshic/how-to-expand-collapse-items-in-recyclerview-49a648a403a6
Assembly.GetEntryAssembly()
New, improved answer to an old, frequently asked question...
How could I get its parent? Result should be the
store
node.
parent::
or ancestor::
axisMost answers here select the title
and then traverse up to the targeted parent or ancestor (store
) element. A simpler, direct approach is to select parent or ancestor element directly in the first place, obviating the need to traverse to a parent::
or ancestor::
axes:
//*[book/title = "50"]
Should the intervening elements vary in name:
//*[*/title = "50"]
Or, in name and depth:
//*[.//title = "50"]
If you want to use them as in swift 2, you can use these funcs:
For CGRectMake:
func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
return CGRect(x: x, y: y, width: width, height: height)
}
For CGPointMake:
func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
For CGSizeMake:
func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
Just put them outside any class and it should work. (Works for me at least)
I think that what you're after is DESCRIBE
DESCRIBE table;
You can also use SHOW TABLES
SHOW TABLES;
to get a list of the tables in your database.
Simple and powerful pagination solution
async getNextDocs(no_of_docs_required: number, last_doc_id?: string) {
let docs
if (!last_doc_id) {
// get first 5 docs
docs = await MySchema.find().sort({ _id: -1 }).limit(no_of_docs_required)
}
else {
// get next 5 docs according to that last document id
docs = await MySchema.find({_id: {$lt: last_doc_id}})
.sort({ _id: -1 }).limit(no_of_docs_required)
}
return docs
}
last_doc_id
: the last document id that you get
no_of_docs_required
: the number of docs that you want to fetch i.e. 5, 10, 50 etc.
last_doc_id
to the method, you'll get i.e. 5 latest docslast_doc_id
then you'll get the next i.e. 5 documents.In Python 3.x and 2.x you can use use list
to force a copy of the keys to be made:
for i in list(d):
In Python 2.x calling keys
made a copy of the keys that you could iterate over while modifying the dict
:
for i in d.keys():
But note that in Python 3.x this second method doesn't help with your error because keys
returns an a view object instead of copynig the keys into a list.
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update
).
But unfortunately there is no way to clone
/ mirror / update
the hooks, as I wanted...
I have found this very interesting thread about cloning/mirroring the hooks:
http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread
I learned:
The hooks are not considered part of the repository contents.
There is more data, like the .git/description
folder, which does not get cloned, just as the hooks.
The default hooks that appear in the hooks
dir comes from the TEMPLATE_DIR
There is this interesting template
feature on git.
So, I may either ignore this "clone the hooks thing", or go for a rsync
strategy, given the purposes of my mirror (backup + source for other clones, only).
Well... I will just forget about hooks cloning, and stick to the git remote update
way.
clone
/ update
process, but also stashes, rerere, etc... So, for a strict backup, rsync
or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update
.Thanks! Improved a bit of my own "git-fu"... :-)
Try this piece of code, rather than ObjectInputStream
.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
another possible solution:
public enum @base
{
x,
y,
z
}
public enum consume
{
x = @base.x,
y = @base.y,
z = @base.z,
a,b,c
}
// TODO: Add a unit-test to check that if @base and consume are aligned
HTH
you can use ClearContents. ex,
Range("X").Cells.ClearContents
public static byte[][] arrayCopy(byte[][] arr){
if(arr!=null){
int[][] arrCopy = new int[arr.length][] ;
System.arraycopy(arr, 0, arrCopy, 0, arr.length);
return arrCopy;
}else { return new int[][]{};}
}
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().hide();
hope this will help
I still prefer the method in one line
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())
I had a similar problem when trying to resolve host names using [system.net.dns]
. If the IP wasn't resolved .Net threw a terminating error.
To prevent the terminating error and still retain control of the output, I created a function using TRAP
.
E.G.
Function Get-IP
{PARAM ([string]$HostName="")
PROCESS {TRAP
{"" ;continue}
[system.net.dns]::gethostaddresses($HostName)
}
}
No! It's not a joke.
Take a look here: http://msdn.microsoft.com/en-us/library/ms186939.aspx
Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set.
And also here: http://en.wikipedia.org/wiki/UTF-16
The older UCS-2 (2-byte Universal Character Set) is a similar character encoding that was superseded by UTF-16 in version 2.0 of the Unicode standard in July 1996.
Extending the top voted comment.
Note that you should pass request as a parameter to your delete function in your views. An example would be like:
from django.shortcuts import redirect
def delete(request, id):
YourModelName.objects.filter(id=id).delete()
return redirect('url_name')
According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:
git checkout -- a
(where a
is the directory you want to hard-reset). The original behavior can be accessed via
git checkout --ignore-skip-worktree-bits -- a
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm
The W3Schools example isn't saying when you should use compound primary keys, and is only giving example syntax using the same example table as for other keys.
Their choice of example is perhaps misleading you by combining a meaningless key (P_Id) and a natural key (LastName). This odd choice of primary key says that the following rows are valid according to the schema and are necessary to uniquely identify a student. Intuitively this doesn't make sense.
1234 Jobs
1234 Gates
Further Reading: The great primary-key debate or just Google meaningless primary keys
or even peruse this SO question
FWIW - My 2 cents is to avoid multi-column primary keys and use a single generated id field (surrogate key) as the primary key and add additional (unique) constraints where necessary.
here is the trick:
$('body').on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});?
The $('...selector..').on('..event..', '...another-selector...', ...callback...);
syntax means:
Add a listener to ...selector..
(the body
in our example) for the event ..event..
('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector...
(.datepicker_recurring_start
in our example) , apply the event handler ...callback...
(the inline function in our example)
See http://api.jquery.com/on/ and especially the section about "delegated events"
If you are loading images, you are likely going to be working with one or both of matplotlib
and opencv
to manipulate and view the images.
For this reason, I tend to use their image readers and append those to lists, from which I make a NumPy array.
import os
import matplotlib.pyplot as plt
import cv2
import numpy as np
# Get the file paths
im_files = os.listdir('path/to/files/')
# imagine we only want to load PNG files (or JPEG or whatever...)
EXTENSION = '.png'
# Load using matplotlib
images_plt = [plt.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, H, W, C)
images = np.array(images_plt)
# Load using opencv
images_cv = [cv2.imread(f) for f in im_files if f.endswith(EXTENSION)]
# convert your lists into a numpy array of size (N, C, H, W)
images = np.array(images_cv)
The only difference to be aware of is the following:
So a single image that is 256*256 in size would produce matrices of size (3, 256, 256) with opencv and (256, 256, 3) using matplotlib.
a.button a:hover
means "a link that's being hovered over that is a child of a link with the class button
".
Go instead for a.button:hover
.
Using svn command line to unlock the local folders, just use svn cleanup
.
Before:
# svn commit -m "fixing #1234"
# svn st
# svn cleanup
After:
# svn st
# svn commit -m "fixing #1234"
Recently, I had a program batch processing files, I have certainly closed each file in the loop, but the error still there.
And later, I resolved this problem by garbage collect eagerly every hundreds of files:
int index;
while () {
try {
// do with outputStream...
} finally {
out.close();
}
if (index++ % 100 = 0)
System.gc();
}
I think you set the marquee width related to 5 images total width. It works fine
ex: <marquee style="width:700px"></marquee>
If you need to change a file just once. You should prefer making the change locally and build a new docker image with this file.
Say in a docker image, you need to change a file named myFile.xml under /path/to/docker/image/. So, you need to do.
FROM docker-repo:tag
ADD myFile.xml /path/to/docker/image/
Then build your own docker image with docker build -t docker-repo:v-x.x.x .
Then use your newly build docker image.
System.getProperty("java.class.path")
It can also be a bug in Mojarra 2.3 https://github.com/eclipse-ee4j/mojarra/issues/4734
You can do it by running with following command.
php -S localhost:8888
An oblique answer to the question is to write all the code as classes, apart from the index.php files, which are then the only points of entry. PHP files that contain classes will not cause anything to happen, even if they are invoked directly through Apache.
A direct answer is to include the following in .htaccess:
<FilesMatch "\.php$">
Order Allow,Deny
Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>
This will allow any file like index.php, index2.php etc to be accessed, but will refuse access of any kind to other .php files. It will not affect other file types.
As many people have stated, the solution is to use C++11 features to avoid finally blocks. One of the features is unique_ptr
.
Here is Mephane's answer written using RAII patterns.
#include <vector>
#include <memory>
#include <list>
using namespace std;
class Foo
{
...
};
void DoStuff(vector<string> input)
{
list<unique_ptr<Foo> > myList;
for (int i = 0; i < input.size(); ++i)
{
myList.push_back(unique_ptr<Foo>(new Foo(input[i])));
}
DoSomeStuff(myList);
}
Some more introduction to using unique_ptr with C++ Standard Library containers is here
You could do it easily with an extension function rather than a regex ...
public static bool IsAlphaNum(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
for (int i = 0; i < str.Length; i++)
{
if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
return false;
}
return true;
}
Per comment :) ...
public static bool IsAlphaNum(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}
Try this to see how you can create a object from strings.
var firstName = "xx";
var lastName = "xy";
var phone = "xz";
var adress = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);
window.onload = function() {
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.body.appendChild(iDiv);
var iiDiv = document.createElement('div');
iiDiv.className = 'block-2';
var s = document.getElementById('block');
s.appendChild(iiDiv);
}
a do while loop would be a nice way to wait for the user input. Like this:
int main()
{
do
{
cout << '\n' << "Press a key to continue...";
} while (cin.get() != '\n');
return 0;
}
You can also use the function system('PAUSE')
but I think this is a bit slower and platform dependent