Two more uses not mentioned in other answers:
Take this example script:
set -x
: Logging message here
example_command
The first line, set -x
, makes the shell print out the command before running it. It's quite a useful construct. The downside is that the usual echo Log message
type of statement now prints the message twice. The colon method gets round that. Note that you'll still have to escape special characters just like you would for echo
.
I've seen it being used in cron jobs, like this:
45 10 * * * : Backup for database ; /opt/backup.sh
This is a cron job that runs the script /opt/backup.sh
every day at 10:45. The advantage of this technique is that it makes for better looking email subjects when the /opt/backup.sh
prints some output.
Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):
I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.
Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:
"test".match( /t(e)st/ );
alert( RegExp.$1 );
will alert "e"
But also here it's not "magic" but simply part of the properties name
Here is a better way to loop over files as it handles spaces and newlines in file names:
#!/bin/bash
find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
echo "$line"
ls -l "$line"
done
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
In the end I solved it by using JSONObject.get
rather than JSONObject.getString
and then cast test
to a String
.
private void saveData(String result) {
try {
JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
JSONObject json2 = json.getJSONObject("results");
test = (String) json2.get("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:
SELINUX=disabled
I solved the issue by uninstalling apparently redundant Java software from my windows 7 x64 machine. I achieved this by first uninstalling all Java applications and then installing a fresh Java version. (Later I pointed R 3.4.3 x86_64-w64-mingw32 to the Java path, just to mention though I don't think this was the real issue.) Today only Java 8 Update 161 (64-bit) 8.0.1610.12 was left then. After this, install.packages("rJava"); library(rJava)
did work perfectly.
Make sure that Spring version and xsd version both are same.In my case I am using Spring 4.1.1 so my all xsd should be version *-4.1.xsd
@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
On your controller
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
The lists method now returns a Collection. Upgrading To 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
Solution using the "case" is universal, but then do not use the indexes.
order by case when MyDate is null then 1 else 0 end, MyDate
In my case, I needed performance.
SELECT smoneCol1,someCol2
FROM someSch.someTab
WHERE someCol2 = 2101 and ( someCol1 IS NULL )
UNION
SELECT smoneCol1,someCol2
FROM someSch.someTab
WHERE someCol2 = 2101 and ( someCol1 IS NOT NULL)
You could also look at it from the other way around...
from urlparse import urlparse
[el for el in ['text1', 'FTP://somewhere.com', 'text2', 'http://blah.com:8080/foo/bar#header'] if not urlparse(el).scheme]
Add a static method inside your functional interface
package example;
interface Action<T, U> {
U execute(T t);
static Action<Void,Void> invoke(Runnable runnable){
return (v) -> {
runnable.run();
return null;
};
}
}
public class Lambda {
public static void main(String[] args) {
Action<Void, Void> a = Action.invoke(() -> System.out.println("Do nothing!"));
Void t = null;
a.execute(t);
}
}
Output
Do nothing!
Java libs makes it almost a one liner to read the public cert, as generated by openssl:
val certificate: X509Certificate = ByteArrayInputStream(
publicKeyCert.toByteArray(Charsets.US_ASCII))
.use {
CertificateFactory.getInstance("X.509")
.generateCertificate(it) as X509Certificate
}
But, o hell, reading the private key was problematic:
RSAPrivateKey
.see this: Final solution in kotlin
There are few ways to create empty Set in Python :
So, This are 2 ways to create empty Set.
None of the other current answers will actually "merge" the files, as if you were using the merge command. (At best they'll require you to manually pick diffs.) If you actually want to take advantage of merging using the information from a common ancestor, you can follow a procedure based on one found in the "Advanced Merging" section of the git Reference Manual.
For this protocol, I'm assuming you're wanting to merge the file 'path/to/file.txt' from origin/master into HEAD - modify as appropriate. (You don't have to be in the top directory of your repository, but it helps.)
# Find the merge base SHA1 (the common ancestor) for the two commits:
git merge-base HEAD origin/master
# Get the contents of the files at each stage
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show HEAD:path/to/file.txt > ./file.ours.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt
# You can pre-edit any of the files (e.g. run a formatter on it), if you want.
# Merge the files
git merge-file -p ./file.ours.txt ./file.common.txt ./file.theirs.txt > ./file.merged.txt
# Resolve merge conflicts in ./file.merged.txt
# Copy the merged version to the destination
# Clean up the intermediate files
git merge-file should use all of your default merge settings for formatting and the like.
Also note that if your "ours" is the working copy version and you don't want to be overly cautious, you can operate directly on the file:
git merge-base HEAD origin/master
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt
git merge-file path/to/file.txt ./file.common.txt ./file.theirs.txt
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload
or DOMReady
event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
This is for those who want to a portable way to count cpu cores on *bsd, *nix or solaris (haven't tested on aix and hp-ux but should work). It has always worked for me.
dmesg | \
egrep 'cpu[. ]?[0-9]+' | \
sed 's/^.*\(cpu[. ]*[0-9]*\).*$/\1/g' | \
sort -u | \
wc -l | \
tr -d ' '
solaris grep
& egrep
don't have -o
option so sed
is used instead.
I had terrible trouble with the both the PEAR-based and the simpler alternatives shown. So here's a solution that leverages the Unix diff command (obviously, you have to be on a Unix system or have a working Windows diff command for it to work). Choose your favourite temporary directory, and change the exceptions to return codes if you prefer.
/**
* @brief Find the difference between two strings, lines assumed to be separated by "\n|
* @param $new string The new string
* @param $old string The old string
* @return string Human-readable output as produced by the Unix diff command,
* or "No changes" if the strings are the same.
* @throws Exception
*/
public static function diff($new, $old) {
$tempdir = '/var/somewhere/tmp'; // Your favourite temporary directory
$oldfile = tempnam($tempdir,'OLD');
$newfile = tempnam($tempdir,'NEW');
if (!@file_put_contents($oldfile,$old)) {
throw new Exception('diff failed to write temporary file: ' .
print_r(error_get_last(),true));
}
if (!@file_put_contents($newfile,$new)) {
throw new Exception('diff failed to write temporary file: ' .
print_r(error_get_last(),true));
}
$answer = array();
$cmd = "diff $newfile $oldfile";
exec($cmd, $answer, $retcode);
unlink($newfile);
unlink($oldfile);
if ($retcode != 1) {
throw new Exception('diff failed with return code ' . $retcode);
}
if (empty($answer)) {
return 'No changes';
} else {
return implode("\n", $answer);
}
}
There's actually quite a bit of useful information added to debug allocations. This table is more complete:
http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
Address Offset After HeapAlloc() After malloc() During free() After HeapFree() Comments 0x00320FD8 -40 0x01090009 0x01090009 0x01090009 0x0109005A Win32 heap info 0x00320FDC -36 0x01090009 0x00180700 0x01090009 0x00180400 Win32 heap info 0x00320FE0 -32 0xBAADF00D 0x00320798 0xDDDDDDDD 0x00320448 Ptr to next CRT heap block (allocated earlier in time) 0x00320FE4 -28 0xBAADF00D 0x00000000 0xDDDDDDDD 0x00320448 Ptr to prev CRT heap block (allocated later in time) 0x00320FE8 -24 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Filename of malloc() call 0x00320FEC -20 0xBAADF00D 0x00000000 0xDDDDDDDD 0xFEEEFEEE Line number of malloc() call 0x00320FF0 -16 0xBAADF00D 0x00000008 0xDDDDDDDD 0xFEEEFEEE Number of bytes to malloc() 0x00320FF4 -12 0xBAADF00D 0x00000001 0xDDDDDDDD 0xFEEEFEEE Type (0=Freed, 1=Normal, 2=CRT use, etc) 0x00320FF8 -8 0xBAADF00D 0x00000031 0xDDDDDDDD 0xFEEEFEEE Request #, increases from 0 0x00320FFC -4 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x00321000 +0 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321004 +4 0xBAADF00D 0xCDCDCDCD 0xDDDDDDDD 0xFEEEFEEE The 8 bytes you wanted 0x00321008 +8 0xBAADF00D 0xFDFDFDFD 0xDDDDDDDD 0xFEEEFEEE No mans land 0x0032100C +12 0xBAADF00D 0xBAADF00D 0xDDDDDDDD 0xFEEEFEEE Win32 heap allocations are rounded up to 16 bytes 0x00321010 +16 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321014 +20 0xABABABAB 0xABABABAB 0xABABABAB 0xFEEEFEEE Win32 heap bookkeeping 0x00321018 +24 0x00000010 0x00000010 0x00000010 0xFEEEFEEE Win32 heap bookkeeping 0x0032101C +28 0x00000000 0x00000000 0x00000000 0xFEEEFEEE Win32 heap bookkeeping 0x00321020 +32 0x00090051 0x00090051 0x00090051 0xFEEEFEEE Win32 heap bookkeeping 0x00321024 +36 0xFEEE0400 0xFEEE0400 0xFEEE0400 0xFEEEFEEE Win32 heap bookkeeping 0x00321028 +40 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping 0x0032102C +44 0x00320400 0x00320400 0x00320400 0xFEEEFEEE Win32 heap bookkeeping
How about catch it at EndRequest event?
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpRequest request = HttpContext.Current.Request;
HttpResponse response = HttpContext.Current.Response;
if ((request.HttpMethod == "POST") &&
(response.StatusCode == 404 && response.SubStatusCode == 13))
{
// Clear the response header but do not clear errors and
// transfer back to requesting page to handle error
response.ClearHeaders();
HttpContext.Current.Server.Transfer(request.AppRelativeCurrentExecutionFilePath);
}
}
These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.
The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.
For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html
You're missing the data-toggle="tab"
data-tag on your menu urls so your scripts can't tell where your tab switches are:
HTML
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab" href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
Another approach is to use inplace editing inside Ruby (not from the command line):
#!/usr/bin/ruby
def inplace_edit(file, bak, &block)
old_stdout = $stdout
argf = ARGF.clone
argf.argv.replace [file]
argf.inplace_mode = bak
argf.each_line do |line|
yield line
end
argf.close
$stdout = old_stdout
end
inplace_edit 'test.txt', '.bak' do |line|
line = line.gsub(/search1/,"replace1")
line = line.gsub(/search2/,"replace2")
print line unless line.match(/something/)
end
If you don't want to create a backup then change '.bak'
to ''
.
The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.
The expensive regex method and the css attribute selector with starts with ^ operator
Option Explicit
Public Sub test()
Debug.Print StartWithSubString("ab", "abc,d")
End Sub
Regex:
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft VBScript Regular Expressions
Dim re As VBScript_RegExp_55.RegExp
Set re = New VBScript_RegExp_55.RegExp
re.Pattern = "^" & substring
StartWithSubString = re.test(testString)
End Function
Css attribute selector with starts with operator
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft HTML Object Library
Dim html As MSHTML.HTMLDocument
Set html = New MSHTML.HTMLDocument
html.body.innerHTML = "<div test=""" & testString & """></div>"
StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0
End Function
Mac OS X Answer
You don't have write access to the node_modules directory
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
Add your User to the directory with write access
All you need is width:100%
somewhere that applies to the tag as shown by the various answers here.
Using col-xs-12:
<!-- adds float:left, which is usually not a problem -->
<img class='img-responsive col-xs-12' />
Or inline CSS:
<img class='img-responsive' style='width:100%;' />
Or, in your own CSS file, add an additional definition for .img-responsive
.img-responsive {
width:100%;
}
THE ROOT OF THE PROBLEM
This is a known FF bug that <fieldset>
does not respect overflow rules:
https://bugzilla.mozilla.org/show_bug.cgi?id=261037
A CSS "FIX" to fix the FireFox bug would be to make the <fieldset>
display:table-column
. However, doing so, according to the following link, will cause the display of the fieldset to fail in Opera:
https://github.com/TryGhost/Ghost/issues/789
So, just set your tag to 100% width as described in one of the solutions above.
Like many people I've been digging the net with no real answer :(
I've nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra 'js script' line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I've no doubt that the same technique can be use from PHP or others.
case ".html":
response.setHeader("Content-Type", "text/html");
response.write ("<script>location['GPSD_HTTP_AJAX']=true</script>")
// process the real contend of my page
Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ....]
On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile
// Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP
var corsbypass = true;
if (location['GPSD_HTTP_AJAX']) corsbypass = false;
if (corsbypass) { // Json & html served from two different web servers
var gpsdApi = "http://localhost:4080/geojson.rest?jsoncallback=?";
} else { // Json & html served from same web server [no ?jsoncallback=]
var gpsdApi = "geojson.rest?";
}
var gpsdRqt =
{key :123456789 // user authentication key
,cmd :'list' // rest command
,group :'all' // group to retreive
,round : true // ask server to round numbers
};
$.getJSON(gpsdApi,gpsdRqt, DevListCB);
For who ever would like to check my code: https://www.npmjs.org/package/gpsdtracking
This question has been addressed, in a slightly different form, at length, here:
But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:
Matasano's article on this is famous, but the lessons contained therein are pretty important:
To summarize:
<script>
function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
And to add a corollary of my own:
This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!
First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.
This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.
The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.
This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!
The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.
Is Digest authentication possible with jQuery?
A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.
Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.
http://tools.ietf.org/html/rfc5849
Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?
JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.
The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.
This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.
The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.
To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.
It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX
". Many of these policies are pretty good ideas.
However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/
The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.
tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.
The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?
Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.
It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.
Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:
Aside from that, though, it's no different from Token Auth, really.
This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.
OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."
The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."
Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.
There are two ways that OAuth 2.0 can help you:
But when it comes down to it, you're just... using tokens.
So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"
And the answer is: do whatever makes you happy.
The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.
The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.
Create images
folder in root level of your project.
Drop your image in this folder, it should look like
Go to your pubspec.yaml
file, add assets
header and pay close attention to all the spaces.
flutter:
uses-material-design: true
# add this
assets:
- images/profile.jpg
Tap on Packages get
at the top right corner of the IDE.
Now you can use your image anywhere using
Image.asset("images/profile.jpg")
You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).
However, if you don't want to use an external lib, then you would do something like this:
if (map.get(id) == null) { //gets the value for an id)
map.put(id, new ArrayList<String>()); //no ArrayList assigned, create new ArrayList
map.get(id).add(value); //adds value to list.
I think you'll get what you want with the -maxdepth 1
option, based on your current command structure. If not, you can try looking at the man page for find
.
Relevant entry (for convenience's sake):
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc-
tories below the command line arguments. `-maxdepth 0' means
only apply the tests and actions to the command line arguments.
Your options basically are:
# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f
Or:
# DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f
In Java 8:
Customer findCustomerByid(int id) {
return this.customers.stream()
.filter(customer -> customer.getId().equals(id))
.findFirst().get();
}
It might also be better to change the return type to Optional<Customer>
.
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
Simpler yet:
idx = (-arr).argsort()[:n]
where n is the number of maximum values.
Is there any other way to convert that array into string ?
You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.
<?php
$foo = array( 18 => 'Something' );
$value = array_shift( $foo );
echo $value; // 'Something'.
?>
Using array_shift you don't have to worry about the index.
EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.
You need to return a view which has a friendly error message to the user
catch (Exception ex)
{
// to do :log error
return View("Error");
}
You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.
If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions
[HttpPost]
public ActionResult Create(CustomerVM model)
{
try
{
//save customer
return Json(new { status="success",message="customer created"});
}
catch(Exception ex)
{
//to do: log error
return Json(new { status="error",message="error creating customer"});
}
}
If you want to show the error in the form user submitted, You may use ModelState.AddModelError
method along with the Html helper methods like Html.ValidationSummary
etc to show the error to the user in the form he submitted.
Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.
Instead of a line like this declaring a named method signature:
// C#
public delegate void SomeFunction();
declare an interface:
// Java
public interface ISomeBehaviour {
void SomeFunction();
}
For concrete implementations of the method, define a class that implements the behaviour:
// Java
public class TypeABehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeA behaviour
}
}
public class TypeBBehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeB behaviour
}
}
Then wherever you would have had a SomeFunction
delegate in C#, use an ISomeBehaviour
reference instead:
// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();
// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();
With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
...
}
...
SomeMethod(new ISomeBehaviour() {
@Override
public void SomeFunction() {
// your implementation
}
});
This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.
And then of course in Java 8, these do become basically lambda expressions:
// Java 8
SomeMethod(() -> { /* your implementation */ });
Bootstrap supports scss, and he has a special variables. If this is a case then you can add in your main variables.scss file
$table-border-width: 0;
More info here https://github.com/twbs/bootstrap/blob/6ffb0b48e455430f8a5359ed689ad64c1143fac2/scss/_variables.scss#L347-L380
As of 2016 I used datetimepicker like this:
$(function () {
$('#date_box').datetimepicker({
format: 'YYYY-MM-DD hh:mm'
});
});
OK, encouraged by jimhark here is an example of the old single hash table approach: -
CREATE PROCEDURE SP3 as
BEGIN
SELECT 1, 'Data1'
UNION ALL
SELECT 2, 'Data2'
END
go
CREATE PROCEDURE SP2 as
BEGIN
if exists (select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
INSERT INTO #tmp1
EXEC SP3
else
EXEC SP3
END
go
CREATE PROCEDURE SP1 as
BEGIN
EXEC SP2
END
GO
/*
--I want some data back from SP3
-- Just run the SP1
EXEC SP1
*/
/*
--I want some data back from SP3 into a table to do something useful
--Try run this - get an error - can't nest Execs
if exists (select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
DROP TABLE #tmp1
CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))
INSERT INTO #tmp1
EXEC SP1
*/
/*
--I want some data back from SP3 into a table to do something useful
--However, if we run this single hash temp table it is in scope anyway so
--no need for the exec insert
if exists (select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
DROP TABLE #tmp1
CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))
EXEC SP1
SELECT * FROM #tmp1
*/
Get the querystring collection, parse it into a (name=value pair
) string, excluding the one you want to REMOVE, and name it newQueryString
Then call Response.Redirect(known_path?newqueryString)
;
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data
key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
write a button tag and on click function
var x = document.getElementById('codeRefer').innerHTML;
document.getElementById('codeRefer').innerHTML = x;
write this all in onclick function
Probably the simplest way is using subplot2grid
, described in Customizing Location of Subplot Using GridSpec.
ax = plt.subplot2grid((2, 2), (0, 0))
is equal to
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
so bmu's example becomes:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
The simple <u>some text</u>
should work for you.
There are automatic backup under %systemdrive%\inetpub\history but it may not help much if you already made lots of changes.
http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx
You will have to regularly back up manually using appcmd.
If you try to reinstall IIS, please first uninstall IIS and WAS via Add/Remove Programs, and then delete all existing files under C:\inetpub and C:\Windows\system32\inetsrv directories. Then you can install again cleanly.
WARN: beginners on IIS are not recommended to execute the steps above without a full backup of the system. The steps should be executed with caution and good understanding of IIS. If you are not capable of or you have doubt, make sure you open a support case with Microsoft via http://support.microsoft.com and consult.
this is actually pretty easily done. You're almost there, doing what you've done with background-position: right center;
. What is actually needed in this case is something very much like that. Let's convert these to percentages. We know that center
=50%
, so that's easy enough. Now, in order to get the padding you wanted, you need to position the background like so: background-position: 99% 50%
.
The second, and more effective way of going about this, is to use the same background-position
idea, and just use background-position: 400px (width of parent) 50%;
. Of course, this method requires a static width, but will give you the same thing every time.
Free tools supporting panning / zooming:
Free tools without built in pan / zoom support:
Paid tools with built in pan / zoom support:
Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])
For implementing the timeout on the function, this stackoverflow thread has answers on that.
Don't try to be too sneaky, especially when it needlessly affects performance. If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
this turns the recursion in to a loop:
def checkNextID(ID):
global numOfRuns, curRes, lastResult
while ID < lastResult:
try:
numOfRuns += 1
if numOfRuns % 10 == 0:
time.sleep(3) # sleep every 10 iterations
if isValid(ID + 8):
parseHTML(curRes)
ID = ID + 8
elif isValid(ID + 18):
parseHTML(curRes)
ID = ID + 18
elif isValid(ID + 7):
parseHTML(curRes)
ID = ID + 7
elif isValid(ID + 17):
parseHTML(curRes)
ID = ID + 17
elif isValid(ID+6):
parseHTML(curRes)
ID = ID + 6
elif isValid(ID + 16):
parseHTML(curRes)
ID = ID + 16
else:
ID = ID + 1
except Exception, e:
print "somethin went wrong: " + str(e)
another solution using dplyr is:
df <- ## your data ##
df <- df %>%
mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
The easiest way to strip all leading 0
s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0
character, as the question implies, you could use
s = s.replace(/^0/, "");
Instead of using a ugly log file, you can also activate Fusion log via ETW/xperf by turning on the DotnetRuntime Private provider (Microsoft-Windows-DotNETRuntimePrivate
) with GUID 763FD754-7086-4DFE-95EB-C01A46FAF4CA
and the FusionKeyword
keyword (0x4) on.
@echo off
echo Press a key when ready to start...
pause
echo .
echo ...Capturing...
echo .
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -on PROC_THREAD+LOADER+PROFILE -stackwalk Profile -buffersize 1024 -MaxFile 2048 -FileMode Circular -f Kernel.etl
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -start ClrSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+763FD754-7086-4DFE-95EB-C01A46FAF4CA:0x4:0x5 -f clr.etl -buffersize 1024
echo Press a key when you want to stop...
pause
pause
echo .
echo ...Stopping...
echo .
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -start ClrRundownSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+Microsoft-Windows-DotNETRuntimeRundown:0x118:0x5:'stack' -f clr_DCend.etl -buffersize 1024
timeout /t 15
set XPERF_CreateNGenPdbs=1
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -stop ClrSession ClrRundownSession
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -stop
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -merge kernel.etl clr.etl clr_DCend.etl Result.etl -compress
del kernel.etl
del clr.etl
del clr_DCend.etl
When you now open the ETL file in PerfView and look under the Events table, you can find the Fusion data:
I created a custom class MyButton extended from UIButton
. Then added this inside the Identity Inspector
:
After this, change the button type to Custom:
Then you can set attributes like textColor
and UIFont
for your UIButton
for the different states:
Then I also created two methods inside MyButton
class which I have to call inside my code when I want a UIButton
to be displayed as highlighted:
- (void)changeColorAsUnselection{
[self setTitleColor:[UIColor colorFromHexString:acColorGreyDark]
forState:UIControlStateNormal &
UIControlStateSelected &
UIControlStateHighlighted];
}
- (void)changeColorAsSelection{
[self setTitleColor:[UIColor colorFromHexString:acColorYellow]
forState:UIControlStateNormal &
UIControlStateHighlighted &
UIControlStateSelected];
}
You have to set the titleColor
for normal, highlight and selected UIControlState
because there can be more than one state at a time according to the documentation of UIControlState
.
If you don't create these methods, the UIButton
will display selection or highlighting but they won't stay in the UIColor
you setup inside the UIInterface Builder
because they are just available for a short display of a selection, not for displaying selection itself.
Presenting to you
left.merge(right, how='cross')
import pandas as pd
pd.__version__
# '1.2.0'
left = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
right = pd.DataFrame({'col3': [5, 6]})
left.merge(right, how='cross')
col1 col2 col3
0 1 3 5
1 1 3 6
2 2 4 5
3 2 4 6
Indexes are ignored in the result.
Implementation wise, this uses the join on common key column method as described in the accepted answer. The upsides of using the API is that it saves you a lot of typing and handles some corner cases pretty well. I'd almost always recommend this syntax as my first preference for cartesian product in pandas unless you're looking for something more performant.
When you have Overridden Methods with same Name Use the helper below
public static TValue GetControllerMethodAttributeValue<T, TT, TAttribute, TValue>(this T type, Expression<Func<T, TT>> exp, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute
{
var memberExpression = exp?.Body as MethodCallExpression;
if (memberExpression.Method.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault() is TAttribute attr && valueSelector != null)
{
return valueSelector(attr);
}
return default(TValue);
}
Usage: var someController = new SomeController(Some params); var str = typeof(SomeController).GetControllerMethodAttributeValue(x => someController.SomeMethod(It.IsAny()), (RouteAttribute routeAttribute) => routeAttribute.Template);
android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."
checkout changes for Android Support Library, revision 22.1.0 (April 2015)
For phone numbers you can simply exclude all non-digit characters with \D in regex:
import re
phone_number = '(619) 459-3635'
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)
When you see "Verify return code: 19 (self signed certificate in certificate chain)
", then, either the servers is really trying to use a self-signed certificate (which a client is never going to be able to verify), or OpenSSL hasn't got access to the necessary root but the server is trying to provide it itself (which it shouldn't do because it's pointless - a client can never trust a server to supply the root corresponding to the server's own certificate).
Again, adding -showcerts will help you diagnose which.
That's because you're using a non-blocking
socket and the output buffer is full.
From the send()
man page
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-block-
ing I/O mode. In non-blocking mode it would return EAGAIN in this
case.
EAGAIN is the error code tied to "Resource temporarily unavailable"
Consider using select()
to get a better control of this behaviours
Nothing could be simple than this. Use OkHttpLibrary
Create your json
JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);
and send it like this.
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.addHeader("Content-Type","application/json")
.url(url)
.post(requestObject.toString())
.build();
okhttp3.Response response = client.newCall(request).execute();
Try to make use of linq to Dataset
(from b in table1.AsEnumerable()
select new { id = b.Field<int>("id")}).Except(
from a in table2.AsEnumerable()
select new {id = a.Field<int>("id")})
Check this article : Comparing DataSets using LINQ
980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.
Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.
Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/
You should consider not displaying your error messages instead!
Set ini_set('display_errors', 'Off');
in your PHP code (or directly into your ini file if possible), and leave error_reporting on E_ALL
or whatever kind of messages you would like to find in your logs.
This way you can handle errors later, while your users still don't see them.
define('DEBUG', true);
error_reporting(E_ALL);
if (DEBUG)
{
ini_set('display_errors', 'On');
}
else
{
ini_set('display_errors', 'Off');
}
define('DEBUG', true);
error_reporting(E_ALL);
ini_set('display_errors', DEBUG ? 'On' : 'Off');
Which version of .NET are you using? Since .NET 3.5, there's an assembly System.Data.DataSetExtensions, which contains various useful extensions for dataTables, dataRows and the like.
You can try using
row.Field<type>("fieldName");
if that doesn't work, you can do this:
DataTable table = new DataTable();
var myColumn = table.Columns.Cast<DataColumn>().SingleOrDefault(col => col.ColumnName == "myColumnName");
if (myColumn != null)
{
// just some roww
var tableRow = table.AsEnumerable().First();
var myData = tableRow.Field<string>(myColumn);
// or if above does not work
myData = tableRow.Field<string>(table.Columns.IndexOf(myColumn));
}
Actually, user477494's answer is in principle correct.
I've applied the same logic in other environments (OS X host - virtual Windows XP) and that does the trick. I did have to cycle the host LAMP stack to get the IP address and Apache port to resolve, but once I'd figured that out, I was laughing.
catch needs to return an observable.
.catch(e => { console.log(e); return Observable.of(e); })
if you'd like to stop the pipeline after a caught error, then do this:
.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)
this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.
edit:
better way of stopping the pipeline is to do
.catch(e => Observable.empty())
Its easy to switch between prefork or worker mpm in Apache 2.4 on RHEL7
Check MPM type by executing
sudo httpd -V
Server version: Apache/2.4.6 (Red Hat Enterprise Linux)
Server built: Jul 26 2017 04:45:44
Server's Module Magic Number: 20120211:24
Server loaded: APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture: 64-bit
Server MPM: prefork
threaded: no
forked: yes (variable process count)
Server compiled with....
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=256
-D HTTPD_ROOT="/etc/httpd"
-D SUEXEC_BIN="/usr/sbin/suexec"
-D DEFAULT_PIDLOG="/run/httpd/httpd.pid"
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
-D DEFAULT_ERRORLOG="logs/error_log"
-D AP_TYPES_CONFIG_FILE="conf/mime.types"
-D SERVER_CONFIG_FILE="conf/httpd.conf"
Now to change MPM edit following file and uncomment required MPM
/etc/httpd/conf.modules.d/00-mpm.conf
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:
# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
#LoadModule mpm_event_module modules/mod_mpm_event.so
Just to extend previous answers - it could help someone. If your getArguments()
returns null
, put it to onCreate()
method and not to constructor of your fragment:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int index = getArguments().getInt("index");
}
Is the name of your service class really IService (on the Service namespace)? What you probably had originally was a mismatch in the name of the service class in the name
attribute of the <service>
element.
to handle undefined, null, and NaN: Null behaves like 0, NaN and undefined goes to end.
array = [3, 5, -1, 1, NaN, 6, undefined, 2, null]
array.sort((a,b) => isNaN(a) || a-b)
// [-1, null, 1, 2, 3, 5, 6, NaN, undefined]
How about something like
CREATE TABLE testRequest (
wardNo nchar(5),
BHTNo nchar(5),
testID nchar(5),
reqDateTime datetime,
PRIMARY KEY (wardNo, BHTNo, testID)
);
Have a look at this example
this might not be the most efficient solution but I had to use it since the wasabeef/Blurry library didn't work for me. this could be handy if you intend to have some getting-blurry animation:
1- you need to have 2 versions of the picture, normal one and the blurry one u make with photoshop or whatever
2- set the images fit on each other in your xml, then one of them could be seen and that's the upper one
3- set fadeout animation on the upper one:
final Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {upperone.setVisibility(View.GONE);}
@Override
public void onAnimationRepeat(Animation animation) {}
});
upperone.startAnimation(fadeOut);
This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.
It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.
The relevant section is:
select *
from
( select *
from emp
order by sal desc )
where ROWNUM <= 5;
I use PyDev/LiClipse and haven't really figured out how to run all tests at once from the GUI. (edit: you right click the root test folder and choose Run as -> Python unit-test
This is my current workaround:
import unittest
def load_tests(loader, tests, pattern):
return loader.discover('.')
if __name__ == '__main__':
unittest.main()
I put this code in a module called all
in my test directory. If I run this module as a unittest from LiClipse then all tests are run. If I ask to only repeat specific or failed tests then only those tests are run. It doesn't interfere with my commandline test runner either (nosetests) -- it's ignored.
You may need to change the arguments to discover
based on your project setup.
Well, I guess the other posters have provided you with a means to directly include an @section within your partial (by using 3rd party html helpers).
But, I reckon that, if your script is tightly coupled to your partial, just put your javascript directly inside an inline <script>
tag within your partial and be done with it (just be careful of script duplication if you intend on using the partial more than once in a single view);
The inverse, as the name says, but sometimes "close enough" is "close enough"; an interesting read anyway.
Try using:
xattr -rd com.apple.quarantine directoryname
This takes care of recursively removing the pesky attribute everywhere.
CREATE TABLE #CountMe (Col1 char(1));
INSERT INTO #CountMe VALUES ('A');
INSERT INTO #CountMe VALUES ('B');
INSERT INTO #CountMe VALUES ('A');
INSERT INTO #CountMe VALUES ('B');
SELECT
COUNT(CASE WHEN Col1 = 'A' THEN 1 END) AS CountWithoutElse,
COUNT(CASE WHEN Col1 = 'A' THEN 1 ELSE NULL END) AS CountWithElseNull,
COUNT(CASE WHEN Col1 = 'A' THEN 1 ELSE 0 END) AS CountWithElseZero
FROM #CountMe;
Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.
Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.
You can move this code to index.html for preload images from any url
<link rel="preload" href="https://via.placeholder.com/160" as="image">
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
ThisWorkbook.Path
is what you would use.
More flexible way is to use FileTimeFilterJS.bat
:
@echo off
::::::::::::::::::::::
set "_DIR=C:\Users\npocmaka\Downloads"
set "_DAYS=-5"
::::::::::::::::::::::
for /f "tokens=* delims=" %%# in ('FileTimeFilterJS.bat "%_DIR%" -dd %_DAYS%') do (
echo deleting "%%~f#"
echo del /q /f "%%~f#"
)
The script will allow you to use measurements like days, minutes ,seconds or hours. To choose weather to filter the files by time of creation, access or modification To list files before or after a certain date (or between two dates) To choose if to show files or dirs (or both) To be recursive or not
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left
Use a cyclic scheduler. This gives you the ability to add regular maintenance times to check the correctness of critical data. The problem most often encountered is corruption of the stack. If your software is cyclical you can reinitialise the stack between cycles. Do not reuse the stacks for interrupt calls, setup a separate stack of each important interrupt call.
Similar to the Watchdog concept is deadline timers. Start a hardware timer before calling a function. If the function does not return before the deadline timer interrupts then reload the stack and try again. If it still fails after 3/5 tries you need reload from ROM.
Split your software into parts and isolate these parts to use separate memory areas and execution times (Especially in a control environment). Example: signal acquisition, prepossessing data, main algorithm and result implementation/transmission. This means a failure in one part will not cause failures through the rest of the program. So while we are repairing the signal acquisition the rest of tasks continues on stale data.
Everything needs CRCs. If you execute out of RAM even your .text needs a CRC. Check the CRCs regularly if you using a cyclical scheduler. Some compilers (not GCC) can generate CRCs for each section and some processors have dedicated hardware to do CRC calculations, but I guess that would fall out side of the scope of your question. Checking CRCs also prompts the ECC controller on the memory to repair single bit errors before it becomes a problem.
If it fits your purpose you can add the hover functionality without using css and using the onmouseover
event in javascript
Here is a code snippet
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
For a short answer you should use np.save
and np.load
. The advantages of these is that they are made by developers of the numpy library and they already work (plus are likely already optimized nicely) e.g.
import numpy as np
from pathlib import Path
path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)
lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2
np.save(path/'x', x)
np.save(path/'y', y)
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
print(x is x_loaded) # False
print(x == x_loaded) # [[ True True True True True]]
Expanded answer:
In the end it really depends in your needs because you can also save it human readable format (see this Dump a NumPy array into a csv file) or even with other libraries if your files are extremely large (see this best way to preserve numpy arrays on disk for an expanded discussion).
However, (making an expansion since you use the word "properly" in your question) I still think using the numpy function out of the box (and most code!) most likely satisfy most user needs. The most important reason is that it already works. Trying to use something else for any other reason might take you on an unexpectedly LONG rabbit hole to figure out why it doesn't work and force it work.
Take for example trying to save it with pickle. I tried that just for fun and it took me at least 30 minutes to realize that pickle wouldn't save my stuff unless I opened & read the file in bytes mode with wb
. Took time to google, try thing, understand the error message etc... Small detail but the fact that it already required me to open a file complicated things in unexpected ways. To add that it required me to re-read this (which btw is sort of confusing) Difference between modes a, a+, w, w+, and r+ in built-in open function?.
So if there is an interface that meets your needs use it unless you have a (very) good reason (e.g. compatibility with matlab or for some reason your really want to read the file and printing in python really doesn't meet your needs, which might be questionable). Furthermore, most likely if you need to optimize it you'll find out later down the line (rather than spend ages debugging useless stuff like opening a simple numpy file).
So use the interface/numpy provide. It might not be perfect it's most likely fine, especially for a library that's been around as long as numpy.
I already spent the saving and loading data with numpy in a bunch of way so have fun with it, hope it helps!
import numpy as np
import pickle
from pathlib import Path
path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)
lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2
# using save (to npy), savez (to npz)
np.save(path/'x', x)
np.save(path/'y', y)
np.savez(path/'db', x=x, y=y)
with open(path/'db.pkl', 'wb') as db_file:
pickle.dump(obj={'x':x, 'y':y}, file=db_file)
## using loading npy, npz files
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
db = np.load(path/'db.npz')
with open(path/'db.pkl', 'rb') as db_file:
db_pkl = pickle.load(db_file)
print(x is x_loaded)
print(x == x_loaded)
print(x == db['x'])
print(x == db_pkl['x'])
print('done')
Some comments on what I learned:
np.save
as expected, this already compresses it well (see https://stackoverflow.com/a/55750128/1601580), works out of the box without any file opening. Clean. Easy. Efficient. Use it.np.savez
uses a uncompressed format (see docs) Save several arrays into a single file in uncompressed
.npz format.
If you decide to use this (you were warned to go away from the standard solution so expect bugs!) you might discover that you need to use argument names to save it, unless you want to use the default names. So don't use this if the first already works (or any works use that!)hdf5
for large files. Cool! https://stackoverflow.com/a/9619713/1601580Note this is not an exhaustive answer. But for other resources check this:
np.save
): Save Numpy Array using PickleTry this
box-sizing: border-box;
Try to use org.apache.commons.io.FileUtils (General file manipulation utilities). Facilities are provided in the following methods:
(1) FileUtils.moveDirectory(File srcDir, File destDir) => Moves a directory.
(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.
(3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.
(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.
(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.
It's simple, easy and fast.
You must be root.
sudo su -
asterisk -r
Use transform: scale(...);
and add matching margin: -...px
to compensate free space from scaling. (you can use * {outline: 1px solid}
to see element boundaries).
http://www.unicode.org is the place to look for symbol names.
? BLACK CIRCLE 25CF
? MEDIUM BLACK CIRCLE 26AB
? BLACK LARGE CIRCLE 2B24
or even:
NEW MOON SYMBOL 1F311
Good luck finding a font that supports them all. Only one shows up in Windows 7 with Chrome.
java.net.URLEncoder.encode(finalPartOfString, "utf-8");
This will URL-encode the string.
finalPartOfString
is the part after the last slash - in your case, the name of the song, as it seems.
Note that you may need to do something like ./gradlew <module_directory>:<module_name>:dependencies
if the module has extra directory before reach its build.gradle. When in doubt, do ./gradlew tasks --all
to check the name.
Or use good old "find". For example in order to look for old mysql v5.7:
cd /
find . type -d -name "[email protected]"
Another option, if you are using pandas and would like to suppress scientific notation for all floats, is to adjust the pandas options.
import pandas as pd
pd.options.display.float_format = '{:.2f}'.format
You should use
inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
Math.Round rounds a double-precision floating-point value to a specified number of fractional digits.
Specifies how mathematical rounding methods should process a number that is midway between two numbers.
Basically the function above will take your inputvalue and round it to 2 (or whichever number you specify) decimal places. With MidpointRounding.AwayFromZero
when a number is halfway between two others, it is rounded toward the nearest number that is away from zero. There is also another option you can use that rounds towards the nearest even number.
Performance-wise it's the same as a named method. The big problem is when you do the following:
MyButton.Click -= (o, i) =>
{
//snip
}
It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.
Use the Underscore.js findWhere function (http://underscorejs.org/#findWhere):
var purposeObjects = [
{purpose: "daily"},
{purpose: "weekly"},
{purpose: "monthly"}
];
var daily = _.findWhere(purposeObjects, {purpose: 'daily'});
daily
would equal:
{"purpose":"daily"}
Here's a fiddle: http://jsfiddle.net/spencerw/oqbgc21x/
To return more than one (if you had more in your array) you could use _.where(...)
The array has a Length
property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1
.
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
When declaring an array in C#, the number you give is the length of the array:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
Here is an alternative way if the object you are working with doesn't have
(InvokeRequired)
This is useful if you are working with the main form in a class other than the main form with an object that is in the main form, but doesn't have InvokeRequired
delegate void updateMainFormObject(FormObjectType objectWithoutInvoke, string text);
private void updateFormObjectType(FormObjectType objectWithoutInvoke, string text)
{
MainForm.Invoke(new updateMainFormObject(UpdateObject), objectWithoutInvoke, text);
}
public void UpdateObject(ToolStripStatusLabel objectWithoutInvoke, string text)
{
objectWithoutInvoke.Text = text;
}
It works the same as above, but it is a different approach if you don't have an object with invokerequired, but do have access to the MainForm
For what it is worth, i have ubuntu and many packages installed and it went in conflict with it.
For me the right answer was:
sudo -i -u postgres-xc
psql
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
Here is the jsFiddle
#backdrop{
border: 2px solid red;
width: 400px;
height: 200px;
position: absolute;
}
#curtain {
border: 1px solid blue;
width: 400px;
height: 200px;
position: absolute;
}
Use Z-index to move the one you want on top.
Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.
class demo
{private int hour,min,sec;
void input(int hour,int min,int sec)
{this.hour=hour;
this.min=min;
this.sec=sec;
}
demo add(demo d2)//demo because we are returning object
{ demo obj=new demo();
obj.hour=hour+d2.hour;
obj.min=min+d2.min;
obj.sec=sec+d2.sec;
return obj;//Returning object and later on it gets allocated to demo d3
}
void display()
{
System.out.println(hour+":"+min+":"+sec);
}
public static void main(String args[])
{
demo d1=new demo();
demo d2=new demo();
d1.input(2, 5, 10);
d2.input(3, 3, 3);
demo d3=d1.add(d2);//Note another object is created
d3.display();
}
}
Modified Time Addition Program
class demo
{private int hour,min,sec;
void input(int hour,int min,int sec)
{this.hour=(hour>12&&hour<24)?(hour-12):hour;
this.min=(min>60)?0:min;
this.sec=(sec>60)?0:sec;
}
demo add(demo d2)
{ demo obj=new demo();
obj.hour=hour+d2.hour;
obj.min=min+d2.min;
obj.sec=sec+d2.sec;
if(obj.sec>60)
{obj.sec-=60;
obj.min++;
}
if(obj.min>60)
{ obj.min-=60;
obj.hour++;
}
return obj;
}
void display()
{
System.out.println(hour+":"+min+":"+sec);
}
public static void main(String args[])
{
demo d1=new demo();
demo d2=new demo();
d1.input(12, 55, 55);
d2.input(12, 7, 6);
demo d3=d1.add(d2);
d3.display();
}
}
You may try it like this:
DECLARE @i int = 0
WHILE @i < 300
BEGIN
SET @i = @i + 1
/* your code*/
END
Try this instead:
$journalName = preg_replace('/\s+/', '_', $journalName);
Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).
Jon really gave a nice solution, I didn't know you could do that!
At times what I resorted to was inheriting from the class and creating its constructors. E.g.
public class FooList : List<Foo> { ... }
Not the best solution (unless your assembly gets used by other people), but it works.
Activator.CreateInstance()
returns an object, which doesn't have an Output method.
It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.
Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?
If you absolutely want to load the assembly via Assembly.Load
, you will have to go via reflection to call any members on c
Something like type.GetMethod("Output").Invoke(c, null);
should do it.
Imagine the use case:
Idea to have individual ES instance per each index - is huge overhead in this case.
Based on my experience, this kind of use case is very complex to support with Elasticsearch.
Why?
FIRST.
The major problem is fundamental back compatibility disregard.
Breaking changes are so cool! (Note: imagine SQL-server which require you to do small change in all your SQL-statements, when upgraded... can't imagine it. But for ES it's normal)
Deprecations which will dropped in next major release are so sexy! (Note: you know, Java contain some deprecations, which 20+ years old, but still working in actual Java version...)
And not only that, sometimes you even have something which nowhere documented (personally came across only once but... )
So. If you want to upgrade ES (because you need new features for some app or you want to get bug fixes) - you are in hell. Especially if it is about major version upgrade.
Client API will not back compatible. Index settings will not back compatible. And upgrade all app/services same moment with ES upgrade is not realistic.
But you must do it time to time. No other way.
Existing indexes is automatically upgraded? - Yes. But it not help you when you will need to change some old-index settings.
To live with that, you need constantly invest a lot of power in ... forward compatibility of you apps/services with future releases of ES. Or you need to build(and anyway constantly support) some kind of middleware between you app/services and ES, which provide you back compatible client API. (And, you can't use Transport Client (because it required jar upgrade for every minor version ES upgrade), and this fact do not make your life easier)
Is it looks simple & cheap? No, it's not. Far from it. Continuous maintenance of complex infrastructure which based on ES, is way to expensive in all possible senses.
SECOND. Simple API ? Well... no really. When you is really using complex conditions and aggregations.... JSON-request with 5 nested levels is whatever, but not simple.
Unfortunately, I have no experience with SOLR, can't say anything about it.
But Sphinxsearch is much better it this scenario, becasue of totally back compatible SphinxQL.
Note: Sphinxsearch/Manticore are indeed interesting. It's not Lucine based, and as result seriously different. Contain several unique features from the box which ES do not have and crazy fast with small/middle size indexes.
It has already been answered, the best way work-around is to convert the Stored Procedure into an SQL Function or a View.
The short answer, just as mentioned above, is that you cannot directly JOIN a Stored Procedure in SQL, not unless you create another stored procedure or function using the stored procedure's output into a temporary table and JOINing the temporary table, as explained above.
I will answer this by converting your Stored Procedure into an SQL function and show you how to use it inside a query of your choice.
CREATE FUNCTION fnMyFunc()
RETURNS TABLE AS
RETURN
(
SELECT tenant.ID AS TenantID,
SUM(ISNULL(trans.Amount,0)) AS TenantBalance
FROM tblTenant tenant
LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
GROUP BY tenant.ID
)
Now to use that function, in your SQL...
SELECT t.TenantName,
t.CarPlateNumber,
t.CarColor,
t.Sex,
t.SSNO,
t.Phone,
t.Memo,
u.UnitNumber,
p.PropertyName
FROM tblTenant t
LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
LEFT JOIN tblProperty p ON u.PropertyID = p.ID
LEFT JOIN dbo.fnMyFunc() AS a
ON a.TenantID = t.TenantID
ORDER BY p.PropertyName, t.CarPlateNumber
If you wish to pass parameters into your function from within the above SQL, then I recommend you use CROSS APPLY
or CROSS OUTER APPLY
.
Read up on that here.
Cheers
It depends on what the thing is.
Top-level types (that is, classes, enums, interfaces, and annotation types not declared inside another type) are package-private by default. (JLS §6.6.1)
In classes, all members (that means fields, methods, and nested type declarations) and constructors are package-private by default. (JLS §6.6.1)
In enums, constructors are private by default. Indeed, enum contructors must be private, and it is an error to specify them as public or protected. Enum constants are always public, and do not permit any access specifier. Other members of enums are package-private by default. (JLS §8.9)
In interfaces and annotation types, all members (again, that means fields, methods, and nested type declarations) are public by default. Indeed, members of interfaces and annotation types must be public, and it is an error to specify them as private or protected. (JLS §9.3 to 9.5)
Local classes are named classes declared inside a method, constructor, or initializer block. They are scoped to the {
..}
block in which they are declared and do not permit any access specifier. (JLS §14.3) Using reflection, you can instantiate local classes from elsewhere, and they are package-private, although I'm not sure if that detail is in the JLS.
Anonymous classes are custom classes created with new
which specify a class body directly in the expression. (JLS §15.9.5) Their syntax does not permit any access specifier. Using reflection, you can instantiate anonymous classes from elsewhere, and both they and their generated constructors are are package-private, although I'm not sure if that detail is in the JLS.
Instance and static initializer blocks do not have access specifiers at the language level (JLS §8.6 & 8.7), but static initializer blocks are implemented as a method named <clinit>
(JVMS §2.9), so the method must, internally, have some access specifier. I examined classes compiled by javac and by Eclipse's compiler using a hex editor and found that both generate the method as package-private. However, you can't call <clinit>()
within the language because the <
and >
characters are invalid in a method name, and the reflection methods are hardwired to deny its existence, so effectively its access specifier is no access. The method can only be called by the VM, during class initialization. Instance initializer blocks are not compiled as separate methods; their code is copied into each constructor, so they can't be accessed individually, even by reflection.
In case of springboot app on tomcat, I needed to create an additional class as below and this worked:
@SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
}
It turns out setting these configuration properties is pretty straight forward, but the official documentation is more general so it might be hard to find when searching specifically for connection pool configuration information.
To set the maximum pool size for tomcat-jdbc, set this property in your .properties or .yml file:
spring.datasource.maxActive=5
You can also use the following if you prefer:
spring.datasource.max-active=5
You can set any connection pool property you want this way. Here is a complete list of properties supported by tomcat-jdbc
.
To understand how this works more generally you need to dig into the Spring-Boot code a bit.
Spring-Boot constructs the DataSource like this (see here, line 102):
@ConfigurationProperties(prefix = DataSourceAutoConfiguration.CONFIGURATION_PREFIX)
@Bean
public DataSource dataSource() {
DataSourceBuilder factory = DataSourceBuilder
.create(this.properties.getClassLoader())
.driverClassName(this.properties.getDriverClassName())
.url(this.properties.getUrl())
.username(this.properties.getUsername())
.password(this.properties.getPassword());
return factory.build();
}
The DataSourceBuilder is responsible for figuring out which pooling library to use, by checking for each of a series of know classes on the classpath. It then constructs the DataSource and returns it to the dataSource()
function.
At this point, magic kicks in using @ConfigurationProperties
. This annotation tells Spring to look for properties with prefix CONFIGURATION_PREFIX
(which is spring.datasource
). For each property that starts with that prefix, Spring will try to call the setter on the DataSource with that property.
The Tomcat DataSource is an extension of DataSourceProxy, which has the method setMaxActive()
.
And that's how your spring.datasource.maxActive=5
gets applied correctly!
I haven't tried, but if you are using one of the other Spring-Boot supported connection pools (currently HikariCP or Commons DBCP) you should be able to set the properties the same way, but you'll need to look at the project documentation to know what is available.
docker build -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .
If you create your test classes in a seperate folder which you then add to your build path,
Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.
But dont forget to remove the folder from the build path for your release build.
1.modify "/etc/profile" file.
#vi /etc/profile
Press "i" key to enter editing status and move cursor to the end of the file,Additional entries:
export PATH=$PATH:/path/to/dir;
Press "Esc" key exit edit status,':wq' save the file.
2.Make configuration effective
source /etc/profile
Explain: profile file works for all users,if you want to be valid only for the active user, set the ".bashrc" file
Like Obediah Stane said, it's necessary to create your own format
method. But I would change a few things:
Create a subclass directly derived from Formatter
, not from SimpleFormatter
. The SimpleFormatter
has nothing to add anymore.
Be careful with creating a new Date
object! You should make sure to represent the date of the LogRecord
. When creating a new Date
with the default constructor, it will represent the date and time the Formatter
processes the LogRecord
, not the date that the LogRecord
was created.
The following class can be used as formatter in a Handler
, which in turn can be added to the Logger
. Note that it ignores all class and method information available in the LogRecord
.
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public final class LogFormatter extends Formatter {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(new Date(record.getMillis()))
.append(" ")
.append(record.getLevel().getLocalizedName())
.append(": ")
.append(formatMessage(record))
.append(LINE_SEPARATOR);
if (record.getThrown() != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
// ignore
}
}
return sb.toString();
}
}
This worked for me:
git remote set-url heroku <repo git>
This replacement old url heroku.
You can check with:
git remote -v
I wrote Class Visualizer, which does it. It's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post. For each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view. Class relations diagram allows to traverse through the whole structure. It has full support for annotations and generics plus special support for JPA entities. Works very well with big projects (thousands of classes).
For me, it was nothing more than re-importing the certificate with "Allow private key to be exported" checked.
I guess it is necessary, but it does make me nervous as it is a third party app accessing this certificate.
Simple Solution, just type the below:
conda update pandas
Type this in your preferred shell (on Windows, use Anaconda Prompt as administrator).
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Button2_Click(Sender, e)
End Sub
This Code call button click event programmatically
With the help of spark-csv we can write to a CSV file.
val dfsql = sqlContext.sql("select * from tablename")
dfsql.write.format("com.databricks.spark.csv").option("header","true").save("output.csv")`
# Set the HEAD to the old commit that we want to tag
git checkout 9fceb02
# temporarily set the date to the date of the HEAD commit, and add the tag
GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" \
git tag -a v1.2 -m"v1.2"
# set HEAD back to whatever you want it to be
git checkout master
The answer by @dkinzer creates tags whose date is the current date (when you ran the git tag
command), not the date of the commit. The Git help for tag
has a section "On Backdating Tags" which says:
If you have imported some changes from another VCS and would like to add tags for major releases of your work, it is useful to be able to specify the date to embed inside of the tag object; such data in the tag object affects, for example, the ordering of tags in the gitweb interface.
To set the date used in future tag objects, set the environment variable
GIT_COMMITTER_DATE
(see the later discussion of possible values; the most common form is "YYYY-MM-DD HH:MM").For example:
$ GIT_COMMITTER_DATE="2006-10-02 10:31" git tag -s v1.0.1
The page "How to Tag in Git" shows us that we can extract the time of the HEAD commit via:
git show --format=%aD | head -1
#=> Wed, 12 Feb 2014 12:36:47 -0700
We could extract the date of a specific commit via:
GIT_COMMITTER_DATE="$(git show 9fceb02 --format=%aD | head -1)" \
git tag -a v1.2 9fceb02 -m "v1.2"
However, instead of repeating the commit twice, it seems easier to just change the HEAD to that commit and use it implicitly in both commands:
git checkout 9fceb02
GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" git tag -a v1.2 -m "v1.2"
You should adhere your application to the XDG Base Directory Specification. Most answers here are either obsolete or wrong.
Your application should store and load data and configuration files to/from the directories pointed by the following environment variables:
$XDG_DATA_HOME
(default: "$HOME/.local/share"
): user-specific data files.$XDG_CONFIG_HOME
(default: "$HOME/.config"
): user-specific configuration files.$XDG_DATA_DIRS
(default: "/usr/local/share/:/usr/share/"
): precedence-ordered set of system data directories.$XDG_CONFIG_DIRS
(default: "/etc/xdg"
): precedence-ordered set of system configuration directories.$XDG_CACHE_HOME
(default: "$HOME/.cache"
): user-specific non-essential data files.You should first determine if the file in question is:
$XDG_CONFIG_HOME:$XDG_CONFIG_DIRS
);$XDG_DATA_HOME:$XDG_DATA_DIRS
); or$XDG_CACHE_HOME
).It is recommended that your application put its files in a subdirectory of the above directories. Usually, something like $XDG_DATA_DIRS/<application>/filename
or $XDG_DATA_DIRS/<vendor>/<application>/filename
.
When loading, you first try to load the file from the user-specific directories ($XDG_*_HOME
) and, if failed, from system directories ($XDG_*_DIRS
). When saving, save to user-specific directories only (since the user probably won't have write access to system directories).
For other, more user-oriented directories, refer to the XDG User Directories Specification. It defines directories for the Desktop, downloads, documents, videos, etc.
You can't use float
inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle
.
So if you want to position child
element to right of parent
element you can use margin-left: auto
but now child
element will also push other div
to the right as you can see here Fiddle
.
What you can do now is change order of elements and set order: 2
on child
element so it doesn't affect second div
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
margin-left: auto;_x000D_
order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">Ignore parent?</div>_x000D_
<div>another child</div>_x000D_
</div>
_x000D_
From PHP using single quotes for the line break worked for me to support the line breaks when I pass that var to an HTML text area value attribute
PHP
foreach ($videoUrls as $key => $value) {
$textAreaValue .= $value->video_url . '\n';
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTML/JS
$( document ).ready(function() {
var text = "<?= htmlspecialchars($textAreaValue); ?>";
document.getElementById("video_urls_textarea").value = text;
});
I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B
and /C
options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1
Create a simple project with pom.xml only. Add your dependency and run:
mvn dependency:tree
Unfortunately dependency mojo must use pom.xml or you get following error:
Cannot execute mojo: tree. It requires a project with an existing pom.xml, but the build is not using one.
Dependencies are described In pom.xml of your artifact. Find it using maven infrastructure.
Go to https://search.maven.org/ and enter your groupId and artifactId.
Or you can go to https://repo1.maven.org/maven2/ and navigate first using plugins groupId, later using artifactId and finally using its version.
For example see org.springframework:spring-core
Part of dependency artifact is a pom.xml. That specifies it's dependency. And you can execute mvn dependency:tree on this pom.
As an additional note, there is no need for the for loop because of R's vectorization.
This:
P <- 243.51
t <- 31 / 365
n <- 365
for (r in seq(0.15, 0.22, by = 0.01))
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
}
is equivalent to:
P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
Because r
is a vector, the expression above containing it is performed for all values of the vector.
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
In you specific case:
version: "3"
services:
node:
image: USER/Your-Pre-Built-Image
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
volumes:
- logs
networks:
default:
driver: overlay
Note:
Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:
ports:
- 80:80
The correct way of use forms now in Angular2 is:
<form (ngSubmit)="onSubmit()">
<label>Username:</label>
<input type="text" class="form-control" [(ngModel)]="user.username" name="username" #username="ngModel" required />
<label>Contraseña:</label>
<input type="password" class="form-control" [(ngModel)]="user.password" name="password" #password="ngModel" required />
<input type="submit" value="Entrar" class="btn btn-primary"/>
</form>
The old way doesn't works anymore
I implemented maxlength
behaviour on textarea
recently, and run into problem described in this question: Chrome counts characters wrong in textarea with maxlength attribute.
So all implementations listed here will work little buggy. To solve this issue I add .replace(/(\r\n|\n|\r)/g, "11")
before .length
. And kept it in mind when cuting string.
I ended with something like this:
var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
el.val(val.slice(0, maxlength - (realLength - length)));
}
Don't sure if it solves problem completely, but it works for me for now.
From the File menu, choose Project Structure (if you're running 0.4.4 there's a bug and the menu item doesn't have a title, but it still works), and choose the Android SDK item. You should see something like this where you can set up your JDK and SDK.
After setting it, quit Android Studio and relaunch it for good measure.
Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations
Or this will work too the same way but without a save as choice:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
}//]]>
</script>
</head>
<body>
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "qm5AG"
}], "*")
}
</script>
</body>
</html>
SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
FROM product AS p
LEFT JOIN customer1 AS c1
ON p.cid = c1.cid
LEFT JOIN customer2 AS c2
ON p.cid = c2.cid
this.label1.BackColor = System.Drawing.Color.Transparent;
Another method
Cancel local git repository
rm -rf .git
Then; Create git repostory again
git init
Then; Repeat the remote repo connect
git remote add origin REPO_URL
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:tar cfz archive.tar.gz file tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.
SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log
method has been changed (added Object[] p5):
SLF4J 1.5.11:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Throwable p5 )
SLF4J 1.6.0:
LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
String p4, Object[] p5, Throwable p6 )
See compatibility reports for other SLF4J versions on this page.
You can generate such reports by the japi-compliance-checker tool.
Another approach that we can do is to :
You can use Firephp an add-on to firebug to debug php in the same environment as javascript.
I also use Xdebug mentioned earlier for profiling php.
You don't have to use CASE...WHEN, you could use an OR condition, like this:
WHERE
pw='correct'
AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
this means that if id<800, success has to be 1 for the condition to be evaluated as true. Otherwise, it will be true anyway.
It is less common, however you could still use CASE WHEN, like this:
WHERE
pw='correct'
AND CASE WHEN id<800 THEN success=1 ELSE TRUE END
AND YEAR(timestamp)=2011
this means: return success=1
(which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise.
It's relative to default browser font-size unless you override it with a value in pt or px.
I think, Maatkit utilits helps for you! You can use mk-table-sync. Please see this link: http://www.maatkit.org/doc/mk-table-sync.html
You must first convert the string to a string array, like this:
$recipients = "Marcel <[email protected]>,Marcelt <[email protected]>"
[string[]]$To = $recipients.Split(',')
Then use Send-MailMessage
like this:
Send-MailMessage -From "[email protected]" -To $To -subject "New files" -body "$teloadmin" -BodyAsHtml -priority High -dno onSuccess, onFailure -smtpServer 192.168.170.61
function negative(n) {
return n < 0;
}
Your regex should work fine for string numbers, but this is probably faster. (edited from comment in similar answer above, conversion with +n
is not needed.)
I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.
Check out this article
shorter ios swift 4 version:
@IBAction func checkBoxBtnTapped(_ sender: UIButton) {
if checkBoxBtn.isSelected {
checkBoxBtn.setBackgroundImage(#imageLiteral(resourceName: "ic_signup_unchecked"), for: .normal)
} else {
checkBoxBtn.setBackgroundImage(#imageLiteral(resourceName: "ic_signup_checked"), for:.normal)
}
checkBoxBtn.isSelected = !checkBoxBtn.isSelected
}
I wrote this script to skip or execute tests if there are changes:
#!/bin/bash
set -e -o pipefail -u
paths=()
while [ "$1" != "--" ]; do
paths+=( "$1" ); shift
done
shift
if git diff --quiet --exit-code "${BASE_BRANCH:-origin/master}"..HEAD ${paths[@]}; then
echo "No changes in ${paths[@]}, skipping $@..." 1>&2
exit 0
fi
echo "Changes found in ${paths[@]}, running $@..." 1>&2
exec "$@"
So you can do something like:
./scripts/git-run-if-changed.sh cmd vendor go.mod go.sum fixtures/ tools/ -- go test
For anyone that searched and pressed on this link, i solved it by simply searching for mysql notifier and stop mysql from running there, Then run mysql in xampp again and it runs. why this works ? iam not expert, but i think it is easy : port was taken already by mysql notifier so had to stop it there and run it here.
netstat! That's a network command line utility which ships with windows. It shows all current established connections and all ports currently being listened to. You can use this program to check, but if you want to do this from code look into the System.Net.NetworkInformation namespace? It's a new namespace as of 2.0. There's some goodies there. But eventually if you wanna get the same kind of information that's available through the command netstat you'll need to result to P/Invoke...
That namespace contains a bunch of classes you can use for figuring out things about the network.
I wasn't able to find that old pice of code but I think you can write something similar yourself. A good start is to check out the IP Helper API. Google MSDN for the GetTcpTable WINAPI function and use P/Invoke to enumerate until you have the information you need.
Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.
pod --version used this to check the version of the last installed pod
Here's an example of a raw query in Doctrine 2 that I'm doing:
public function getAuthoritativeSportsRecords()
{
$sql = "
SELECT name,
event_type,
sport_type,
level
FROM vnn_sport
";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
Python 3.5+ introduces %-interpolation (printf
-style formatting) for bytes:
>>> b'%d\r\n' % 3
b'3\r\n'
See PEP 0461 -- Adding % formatting to bytes and bytearray.
On earlier versions, you could use str
and .encode('ascii')
the result:
>>> s = '%d\r\n' % 3
>>> s.encode('ascii')
b'3\r\n'
Note: It is different from what int.to_bytes
produces:
>>> n = 3
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x03'
>>> b'3' == b'\x33' != '\x03'
True
var joinedString= string.Join(";", myDict.Select(x => x.Key + "=" + x.Value));
if(isset($_GET['id']))
{
// Do something
}
You want something like that
If you have a directory open in VSCode, and want to search a subdirectory, then either:
files to include
field enter the path with a leading ./
,or
Find in Folder...
option.Open Anaconda cmd in base mode:
Then use conda update conda to update Anaconda.
You can then use conda update --all to update all the requirements for Anaconda:
conda update conda
conda update --all
I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.
I was able to list all untracked files reported by svn st
in bash by doing:
echo $(svn st | grep -P "^\?" | cut -c 9-)
If you are feeling lucky, you could replace echo
with rm
to delete untracked files. Or copy the files you want to delete by hand, if you are feeling a less lucky.
(I used @abe-voelker 's answer to revert the remaining files: https://stackoverflow.com/a/6204601/1695680)
I start standalone instance in my machine, and encounter the same problem. Finally, I change from ip "127.0.0.1" to "localhost" and the problem is gone.
The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:
CRLF
and LF
in the same file.How this happens is not the issue here, but it does happen.
I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:
| Resulting conversion when | Resulting conversion when | committing files with various | checking out FROM repo - | EOLs INTO repo and | with mixed files in it and | core.autocrlf value: | core.autocrlf value: -------------------------------------------------------------------------------- File | true | input | false | true | input | false -------------------------------------------------------------------------------- Windows-CRLF | CRLF -> LF | CRLF -> LF | as-is | as-is | as-is | as-is Unix -LF | as-is | as-is | as-is | LF -> CRLF | as-is | as-is Mac -CR | as-is | as-is | as-is | as-is | as-is | as-is Mixed-CRLF+LF | as-is | as-is | as-is | as-is | as-is | as-is Mixed-CRLF+LF+CR | as-is | as-is | as-is | as-is | as-is | as-is
As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.
Upon checkout (3 right columns), there is only 1 case where conversion happens when:
core.autocrlf
is true
and LF
EOL.Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF
+LF
get normalized.
Note also that "old" Mac EOLs of CR
only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLF
s+LF
s, by just converting LF
s to CRLF
s, then it will leave the file in a mixed mode with "lonely" CR
s wherever a CRLF
was converted to CRCRLF
.
Git will then not convert anything, even in true
mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.
I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input
or false
mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true
.
This will hide your console. Implement these lines in your code first to start hiding your console at first.
import win32gui, win32con
the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)
Update May 2020 :
If you've got trouble on pip install win32con
on Command Prompt, you can simply pip install pywin32
.Then on your python script, execute import win32.lib.win32con as win32con
instead of import win32con
.
To show back your program again win32con.SW_SHOW
works fine:
win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)
First thing is you need to run the gradle task that you mentioned for this wrapper. Ex : gradle wrapper
After running this command, check your directory for gradlew and gradlew.bat files. gradlew is the shell script file & can be used in linux/Mac OS. gradlew.bat is the batch file for windows OS. Then run,
./gradlew build
(linux/mac). It will work.
For IE, how about using a CSS expression:
<style type="text/css">
table td {
h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );
}
</style>
Give this a go:
<form name="postcontent" id="postcontent">
<input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
<textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
<script>
(function() {
$("#postcontent").on('submit', function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url:"add_new_post.php",
data:$("#postcontent").serialize(),
beforeSend:function(){
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},success:function(response){
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
});
})();
</script>
Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.
Here is a macro to do a find/replace on a var:
<macrodef name="replaceVarText">
<attribute name="varName" />
<attribute name="from" />
<attribute name="to" />
<sequential>
<local name="replacedText"/>
<local name="textToReplace"/>
<local name="fromProp"/>
<local name="toProp"/>
<property name="textToReplace" value = "${@{varName}}"/>
<property name="fromProp" value = "@{from}"/>
<property name="toProp" value = "@{to}"/>
<script language="javascript">
project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
</script>
<ac:var name="@{varName}" value = "${replacedText}"/>
</sequential>
</macrodef>
Then call the macro like:
<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>
Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.
There's no pretty way. You might be able to use a proxy with the handler having the target methods and delegating everything else to them. Of course you'll have to use a factory because there'll be no constructor.
As of PostgreSQL 9.4, you can use the ?
operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
You can even index the ?
query on the "food"
key if you switch to the jsonb type instead:
alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
Of course, you probably don't have time for that as a full-time rabbit keeper.
Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:
d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
modinfo
does the trick.
root@nyx:/usr/src# modinfo nvidia|grep version:
version: 331.113
A simple solution which is Maven compatible and works for any (thus also third party) class:
private static Optional<String> getVersionFromManifest(Class<?> clazz) {
try {
File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
if (file.isFile()) {
JarFile jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
Attributes attributes = manifest.getMainAttributes();
final String version = attributes.getValue("Bundle-Version");
return Optional.of(version);
}
} catch (Exception e) {
// ignore
}
return Optional.empty();
}
The prior value for the key is dropped and replaced with the new one.
If you'd like to keep all the values a key is given, you might consider implementing something like this:
import org.apache.commons.collections.MultiHashMap;
import java.util.Set;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
public class MultiMapExample {
public static void main(String[] args) {
MultiHashMap mp=new MultiHashMap();
mp.put("a", 10);
mp.put("a", 11);
mp.put("a", 12);
mp.put("b", 13);
mp.put("c", 14);
mp.put("e", 15);
List list = null;
Set set = mp.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
list=(List)mp.get(me.getKey());
for(int j=0;j<list.size();j++)
{
System.out.println(me.getKey()+": value :"+list.get(j));
}
}
}
}
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
I'll add 2 points:
So, the 2 expressions are simply not equal.
WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
(
some_col = 1 OR
some_col = 2 OR
some_col = 3 OR
some_col = 4 OR
some_col = 5
)
AND
some_other_expr
So, when you break the IN clause up, you split the serial ORs up, and changed precedence.
For Python >= 2.7, use subprocess.check_output()
.
http://docs.python.org/2/library/subprocess.html#subprocess.check_output
@Min
and @Max
are used for validating numeric fields which could be String
(representing number), int
, short
, byte
etc and their respective primitive wrappers.
@Size
is used to check the length constraints on the fields.
As per documentation @Size
supports String
, Collection
, Map
and arrays
while @Min
and @Max
supports primitives and their wrappers. See the documentation.
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
Concatenation:
The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).
if one wants to use .post() then this will set headers for all future request made with jquery
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
then make your .post() calls as normal.
I had a similar problem with wget to my own live web site returning errors after installing a new SSL certificate. I'd already checked several browsers and they didn't report any errors:
wget --no-cache -O - "https://example.com/..." ERROR: The certificate of ‘example.com’ is not trusted. ERROR: The certificate of ‘example.com’ hasn't got a known issuer.
The problem was I had installed the wrong certificate authority .pem/.crt file from the issuer. Usually they bundle the SSL certificate and CA file as a zip file, but DigiCert email you the certificate and you have to figure out the matching CA on your own. https://www.digicert.com/help/ has an SSL certificate checker which lists the SSL authority and the hopefully matching CA with a nice blue link graphic if they agree:
`SSL Cert: Issuer GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1
CA: Subject GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1 Valid from 16/Jul/2020 to 31/May/2023 Issuer DigiCert Global Root CA`
Horizontal scrollbars in a HTML Select are not natively supported. However, here's a way to create the appearance of a horizontal scrollbar:
1. First create a css class
<style type="text/css">
.scrollable{
overflow: auto;
width: 70px; /* adjust this width depending to amount of text to display */
height: 80px; /* adjust height depending on number of options to display */
border: 1px silver solid;
}
.scrollable select{
border: none;
}
</style>
2. Wrap the SELECT inside a DIV - also, explicitly set the size to the number of options.
<div class="scrollable">
<select size="6" multiple="multiple">
<option value="1" selected>option 1 The Long Option</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5 Another Longer than the Long Option ;)</option>
<option value="6">option 6</option>
</select>
</div>
I got frustrated too. My need was very straightforward. All I wanted was the ARGB color from the resources, so I wrote a simple static method.
protected static int getARGBColor(Context c, int resId)
throws Resources.NotFoundException {
TypedValue color = new TypedValue();
try {
c.getResources().getValue(resId, color, true);
}
catch (Resources.NotFoundException e) {
throw(new Resources.NotFoundException(
String.format("Failed to find color for resourse id 0x%08x",
resId)));
}
if (color.type != TYPE_INT_COLOR_ARGB8) {
throw(new Resources.NotFoundException(
String.format(
"Resourse id 0x%08x is of type 0x%02d. Expected TYPE_INT_COLOR_ARGB8",
resId, color.type))
);
}
return color.data;
}
To actually answer the question:
console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);
Instead of error, you can also use info, log or warn.
Simple Swift 3 function:
@discardableResult
func getLanguageISO() -> String {
let locale = Locale.current
guard let languageCode = locale.languageCode,
let regionCode = locale.regionCode else {
return "de_DE"
}
return languageCode + "_" + regionCode
}
It's a mess. MAPI or CDO via a .NET interop DLL is officially unsupported by Microsoft--it will appear to work fine, but there are problems with memory leaks due to their differing memory models. You could use CDOEX, but that only works on the Exchange server itself, not remotely; useless. You could interop with Outlook, but now you've just made a dependency on Outlook; overkill. Finally, you could use Exchange 2003's WebDAV support, but WebDAV is complicated, .NET has poor built-in support for it, and (to add insult to injury) Exchange 2007 nearly completely drops WebDAV support.
What's a guy to do? I ended up using AfterLogic's IMAP component to communicate with my Exchange 2003 server via IMAP, and this ended up working very well. (I normally seek out free or open-source libraries, but I found all of the .NET ones wanting--especially when it comes to some of the quirks of 2003's IMAP implementation--and this one was cheap enough and worked on the first try. I know there are others out there.)
If your organization is on Exchange 2007, however, you're in luck. Exchange 2007 comes with a SOAP-based Web service interface that finally provides a unified, language-independent way of interacting with the Exchange server. If you can make 2007+ a requirement, this is definitely the way to go. (Sadly for me, my company has a "but 2003 isn't broken" policy.)
If you need to bridge both Exchange 2003 and 2007, IMAP or POP3 is definitely the way to go.
Use:
<?php
$url = "targetpage"
function redirect$url(){
if (headers_sent()) == false{
echo '<script>window.location.href="' . $url . '";</script>';
}
}
?>
First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert
if(tv.tv_usec<10)
{
printf("00000");
}
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
printf("0000");
}
and so on...
8 years late. But I like:
import os
import requests
os.environ['HTTP_PROXY'] = os.environ['http_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['HTTPS_PROXY'] = os.environ['https_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['NO_PROXY'] = os.environ['no_proxy'] = '127.0.0.1,localhost,.local'
r = requests.get('https://example.com') # , verify=False
To center a block object (e.g. the ul
) you need to set a width on it and then you can set that objects left and right margins to auto.
To center the inline content of block object (e.g. the inline content of li
) you can set the css property text-align: center;
.
You need to believe me. I got this error for the simple reason that I forgot to add the connection string in the App.Config(mine is a wpf project) of your startup project.
The entire config in my case
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ZzaDbContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ZaaDbInDepth;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>