Getting "project" nuget configuration is invalid error
NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.
Updating Visual Studio to 'Update 2' got it working again.
Tools -> Extensions and Updates ->Visual Studio Update 2
As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.
How to get a table cell value using jQuery?
try this :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript"><!--
function getVal(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
alert(targ.innerHTML);
}
onload = function() {
var t = document.getElementById("main").getElementsByTagName("td");
for ( var i = 0; i < t.length; i++ )
t[i].onclick = getVal;
}
</script>
<body>
<table id="main"><tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr><tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr><tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr></table>
</body>
</html>
Check if value exists in enum in TypeScript
There is a very simple and easy solution to your question:
var districtId = 210;
if (DistrictsEnum[districtId] != null) {
// Returns 'undefined' if the districtId not exists in the DistrictsEnum
model.handlingDistrictId = districtId;
}
Disabled form fields not submitting data
We can also use the readonly only with below attributes -
readonly onclick='return false;'
This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.
Identify duplicate values in a list in Python
You can print duplicate and Unqiue using below logic using list.
def dup(x):
duplicate = []
unique = []
for i in x:
if i in unique:
duplicate.append(i)
else:
unique.append(i)
print("Duplicate values: ",duplicate)
print("Unique Values: ",unique)
list1 = [1, 2, 1, 3, 2, 5]
dup(list1)
change PATH permanently on Ubuntu
Add the following line in your .profile
file in your home directory (using vi ~/.profile
):
PATH=$PATH:/home/me/play
export PATH
Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile
How to print a int64_t type in C
Coming from the embedded world, where even uclibc is not always available, and code like
uint64_t myval = 0xdeadfacedeadbeef;
printf("%llx", myval);
is printing you crap or not working at all -- i always use a tiny helper, that allows me to dump properly uint64_t hex:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
char* ullx(uint64_t val)
{
static char buf[34] = { [0 ... 33] = 0 };
char* out = &buf[33];
uint64_t hval = val;
unsigned int hbase = 16;
do {
*out = "0123456789abcdef"[hval % hbase];
--out;
hval /= hbase;
} while(hval);
*out-- = 'x', *out = '0';
return out;
}
Missing artifact com.sun:tools:jar
I just posted over on this question about this same issue and how I resolved it, but I'll paste (and expand on) it here as well, since it seems more relevant.
I had the same issue when using Eclipse in Windows 7, even when I removed the JRE from the list of JREs in the Eclipse settings and just had the JDK there.
What I ended up having to do (as you mentioned in your question) was modify the command-line for the shortcut I use to launch Eclipse to add the -vm argument to it like so:
-vm "T:\Program Files\Java\jdk1.6.0_26\bin"
Of course, you would adjust that to point to the bin directory of your JDK install. What this does is cause Eclipse itself to be running using the JDK instead of JRE, and then it's able to find the tools.jar
properly.
I believe this has to do with how Eclipse finds its default JRE when none is specified. I'm guessing it tends to prefer JRE over JDK (why, I don't know) and goes for the first compatible JRE it finds. And if it's going off of Windows registry keys like Vladiat0r's answer suggests, it looks for the HKLM\Software\JavaSoft\Java Runtime Environment
key first instead of the HKLM\Software\JavaSoft\Java Development Kit
key.
Access VBA | How to replace parts of a string with another string
Since the string "North" might be the beginning of a street name, e.g. "Northern Boulevard", street directions are always between the street number and the street name, and separated from street number and street name.
Public Function strReplace(varValue As Variant) as Variant
Select Case varValue
Case "Avenue"
strReplace = "Ave"
Case " North "
strReplace = " N "
Case Else
strReplace = varValue
End Select
End Function
How to cast the size_t to double or int C++
A cast, as Blaz Bratanic suggested:
size_t data = 99999999;
int convertdata = static_cast<int>(data);
is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).
But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t
to int
really could overflow.
If at all possible, design your program so you don't need to convert a size_t
value to int
. Just store it in a size_t
variable (as you've already done) and use that.
Converting to double
will not cause an overflow, but it could result in a loss of precision for a very large size_t
value. Again, it doesn't make a lot of sense to convert a size_t
to a double
; you're still better off keeping the value in a size_t
variable.
(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)
Algorithm to return all combinations of k elements from n
There is no need for collection manipulations. The problem is almost the same as cycling over K nested loops but you have to be careful with the indexes and bounds (ignoring Java and OOP stuff):
public class CombinationsGen {
private final int n;
private final int k;
private int[] buf;
public CombinationsGen(int n, int k) {
this.n = n;
this.k = k;
}
public void combine(Consumer<int[]> consumer) {
buf = new int[k];
rec(0, 0, consumer);
}
private void rec(int index, int next, Consumer<int[]> consumer) {
int max = n - index;
if (index == k - 1) {
for (int i = 0; i < max && next < n; i++) {
buf[index] = next;
next++;
consumer.accept(buf);
}
} else {
for (int i = 0; i < max && next + index < n; i++) {
buf[index] = next;
next++;
rec(index + 1, next, consumer);
}
}
}
}
Use like so:
CombinationsGen gen = new CombinationsGen(5, 2);
AtomicInteger total = new AtomicInteger();
gen.combine(arr -> {
System.out.println(Arrays.toString(arr));
total.incrementAndGet();
});
System.out.println(total);
Get expected results:
[0, 1]
[0, 2]
[0, 3]
[0, 4]
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
10
Finally, map the indexes to whatever set of data you may have.
Using Python Requests: Sessions, Cookies, and POST
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
T-SQL substring - separating first and last name
validate last name is blank
SELECT
person.fullName,
(CASE WHEN 0 = CHARINDEX(' ', person.fullName)
then person.fullName
ELSE SUBSTRING(person.fullName, 1, CHARINDEX(' ', person.fullName)) end) as first_name,
(CASE WHEN 0 = CHARINDEX(' ', person.fullName)
THEN ''
ELSE SUBSTRING(person.fullName,CHARINDEX(' ', person.fullName), LEN(person.fullName) )end) last_name
FROM person
Passing $_POST values with cURL
Another simple PHP example of using cURL:
<?php
$ch = curl_init(); // Initiate cURL
$url = "http://www.somesite.com/curl_example.php"; // Where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
$output = curl_exec ($ch); // Execute
curl_close ($ch); // Close cURL handle
var_dump($output); // Show output
?>
Example found here: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/
Instead of using curl_setopt
you can use curl_setopt_array
.
http://php.net/manual/en/function.curl-setopt-array.php
Git checkout - switching back to HEAD
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
Can you write nested functions in JavaScript?
Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:
function calculate(a,b,fn) {
var c = a * 3 + b + fn(a,b);
return c;
}
function sum(a,b) {
return a+b;
}
function product(a,b) {
return a*b;
}
document.write(calculate (10,20,sum)); //80
document.write(calculate (10,20,product)); //250
How do I wrap text in a pre tag?
I've found that skipping the pre tag and using white-space: pre-wrap on a div is a better solution.
<div style="white-space: pre-wrap;">content</div>
How to make a div center align in HTML
I think that the the align="center"
aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.
text-align
is doing a similar sort of thing.
left:50%
is ignored unless you set the div's position to be something like relative or absolute.
The generally accepted methods is to use the following properties
width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;
the margins being auto means they grow/shrink to match the browser window (or parent div)
UPDATE
Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.
margin:0 auto;
this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.
Daemon Threads Explanation
Chris already explained what daemon threads are, so let's talk about practical usage. Many thread pool implementations use daemon threads for task workers. Workers are threads which execute tasks from task queue.
Worker needs to keep waiting for tasks in task queue indefinitely as they don't know when new task will appear. Thread which assigns tasks (say main thread) only knows when tasks are over. Main thread waits on task queue to get empty and then exits. If workers are user threads i.e. non-daemon, program won't terminate. It will keep waiting for these indefinitely running workers, even though workers aren't doing anything useful. Mark workers daemon threads, and main thread will take care of killing them as soon as it's done handling tasks.
Generator expressions vs. list comprehensions
The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.
For example:
sum(x*2 for x in xrange(256))
dict( (k, some_func(k)) for k in some_list_of_keys )
The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)
You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.
For example:
reversed( [x*2 for x in xrange(256)] )
What is the best way to manage a user's session in React?
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
Is null check needed before calling instanceof?
The instanceof
operator does not need explicit null
checks, as it does not throw a NullPointerException
if the operand is null
.
At run time, the result of the instanceof
operator is true if the value of the relational expression is not null
and the reference could be cast to the reference type without raising a class cast exception.
If the operand is null
, the instanceof
operator returns false
and hence, explicit null checks are not required.
Consider the below example,
public static void main(String[] args) {
if(lista != null && lista instanceof ArrayList) { //Violation
System.out.println("In if block");
}
else {
System.out.println("In else block");
}
}
The correct usage of instanceof
is as shown below,
public static void main(String[] args) {
if(lista instanceof ArrayList){ //Correct way
System.out.println("In if block");
}
else {
System.out.println("In else block");
}
}
plot is not defined
Change that import to
from matplotlib.pyplot import *
Note that this style of imports (from X import *
) is generally discouraged. I would recommend using the following instead:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
Print a div content using Jquery
I update this function
now you can print any tag or any part of the page with its full style
must include jquery.js file
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >
JavaScript
function printtag(tagid) {
var hashid = "#"+ tagid;
var tagname = $(hashid).prop("tagName").toLowerCase() ;
var attributes = "";
var attrs = document.getElementById(tagid).attributes;
$.each(attrs,function(i,elem){
attributes += " "+ elem.name+" ='"+elem.value+"' " ;
})
var divToPrint= $(hashid).html() ;
var head = "<html><head>"+ $("head").html() + "</head>" ;
var allcontent = head + "<body onload='window.print()' >"+ "<" + tagname + attributes + ">" + divToPrint + "</" + tagname + ">" + "</body></html>" ;
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write(allcontent);
newWin.document.close();
// setTimeout(function(){newWin.close();},10);
}
Sequence Permission in Oracle
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
Lodash .clone and .cloneDeep behaviors
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
Python read in string from file and split it into values
Use open(file, mode)
for files.
The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.
Use open
with readline()
or readlines()
. The former will return a line at a time, while the latter returns a list of the lines.
Use split(delimiter)
to split on the comma.
Lastly, you need to cast each item to an integer: int(foo)
. You'll probably want to surround your cast with a try block followed by except ValueError
as in the link below.
You can also use 'multiple assignment' to assign a and b at once:
>>>a, b = map(int, "2342342,2234234".split(","))
>>>print a
2342342
>>>type(a)
<type 'int'>
python io docs
python casting
When to use Comparable and Comparator
Comparator does everything that comparable does, plus more.
| | Comparable | Comparator
._______________________________________________________________________________
Is used to allow Collections.sort to work | yes | yes
Can compare multiple fields | yes | yes
Lives inside the class you’re comparing and serves | |
as a “default” way to compare | yes | yes
Can live outside the class you’re comparing | no | yes
Can have multiple instances with different method names | no | yes
Input arguments can be a list of | just Object| Any type
Can use enums | no | yes
I found the best approach to use comparators as anonymous classes as follows:
private static void sortAccountsByPriority(List<AccountRecord> accounts) {
Collections.sort(accounts, new Comparator<AccountRecord>() {
@Override
public int compare(AccountRecord a1, AccountRecord a2) {
return a1.getRank().compareTo(a2.getRank());
}
});
}
You can create multiple versions of such methods right inside the class you’re planning to sort. So you can have:
Now, you can use these sort methods anywhere and get code reuse.
This gives me everything a comparable would, plus more ... so I don’t see any reason to use comparable at all.
Comparing Java enum members: == or equals()?
One of the Sonar rules is Enum values should be compared with "=="
. The reasons are as follows:
Testing equality of an enum value with equals()
is perfectly valid because an enum is an Object and every Java developer knows ==
should not be used to compare the content of an Object. At the same time, using ==
on enums:
provides the same expected comparison (content) as equals()
is more null-safe than equals()
provides compile-time (static) checking rather than runtime checking
For these reasons, use of ==
should be preferred to equals()
.
Last but not least, the ==
on enums is arguably more readable (less verbose) than equals()
.
How do you remove a specific revision in the git history?
All the answers so far don't address the trailing concern:
Is there an efficient method when there are hundreds of revisions
after the one to be deleted?
The steps follow, but for reference, let's assume the following history:
[master] -> [hundreds-of-commits-including-merges] -> [C] -> [R] -> [B]
C:
commit just following the commit to be removed (clean)
R:
The commit to be removed
B:
commit just preceding the commit to be removed (base)
Because of the "hundreds of revisions" constraint, I'm assuming the following pre-conditions:
- there is some embarrassing commit that you wish never existed
- there are ZERO subsequent commits that actually depend on that embarassing commit (zero conflicts on revert)
- you don't care that you will be listed as the 'Committer' of the hundreds of intervening commits ('Author' will be preserved)
- you have never shared the repository
- or you actually have enough influence over all the people who have ever cloned history with that commit in it to convince them to use your new history
- and you don't care about rewriting history
This is a pretty restrictive set of constraints, but there is an interesting answer that actually works in this corner case.
Here are the steps:
git branch base B
git branch remove-me R
git branch save
git rebase --preserve-merges --onto base remove-me
If there are truly no conflicts, then this should proceed with no further interruptions. If there are conflicts, you can resolve them and rebase --continue
or decide to just live with the embarrassment and rebase --abort
.
Now you should be on master
that no longer has commit R in it. The save
branch points to where you were before, in case you want to reconcile.
How you want to arrange everyone else's transfer over to your new history is up to you. You will need to be acquainted with stash
, reset --hard
, and cherry-pick
. And you can delete the base
, remove-me
, and save
branches
Multiple returns from a function
I have implement like this for multiple return value PHP function. be nice with your code. thank you.
<?php
function multi_retun($aa)
{
return array(1,3,$aa);
}
list($one,$two,$three)=multi_retun(55);
echo $one;
echo $two;
echo $three;
?>
What is an example of the Liskov Substitution Principle?
Likov's Substitution Principle states that if a program module is using a Base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.
Intent - Derived types must be completely substitute able for their base types.
Example - Co-variant return types in java.
Setting the default Java character encoding
I can't answer your original question but I would like to offer you some advice -- don't depend on the JVM's default encoding. It's always best to explicitly specify the desired encoding (i.e. "UTF-8") in your code. That way, you know it will work even across different systems and JVM configurations.
Simple way to unzip a .zip file using zlib
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
Where is git.exe located?
On windows if you have git installed through cygwin (open up cygwin and type git --version
to check) then the path will most likely be something like C:\cygwin64\bin\git.exe
No numeric types to aggregate - change in groupby() behaviour?
I got this error generating a data frame consisting of timestamps and data:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))
Adding the suggested solution works for me:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))
Thanks Chang She!
Example:
data
2005-01-01 00:10:00 7.53
2005-01-01 00:20:00 7.54
2005-01-01 00:30:00 7.62
2005-01-01 00:40:00 7.68
2005-01-01 00:50:00 7.81
2005-01-01 01:00:00 7.95
2005-01-01 01:10:00 7.96
2005-01-01 01:20:00 7.95
2005-01-01 01:30:00 7.98
2005-01-01 01:40:00 8.06
2005-01-01 01:50:00 8.04
2005-01-01 02:00:00 8.06
2005-01-01 02:10:00 8.12
2005-01-01 02:20:00 8.12
2005-01-01 02:30:00 8.25
2005-01-01 02:40:00 8.27
2005-01-01 02:50:00 8.17
2005-01-01 03:00:00 8.21
2005-01-01 03:10:00 8.29
2005-01-01 03:20:00 8.31
2005-01-01 03:30:00 8.25
2005-01-01 03:40:00 8.19
2005-01-01 03:50:00 8.17
2005-01-01 04:00:00 8.18
data
2005-01-01 00:00:00 7.636000
2005-01-01 01:00:00 7.990000
2005-01-01 02:00:00 8.165000
2005-01-01 03:00:00 8.236667
2005-01-01 04:00:00 8.180000
Calculating number of full months between two dates in SQL
This answer follows T-SQL format. I conceptualize this problem as one of a linear-time distance between two date points in datetime format, call them Time1 and Time2; Time1 should be aligned to the 'older in time' value you are dealing with (say a Birth date or a widget Creation date or a journey Start date) and Time2 should be aligned with the 'newer in time' value (say a snapshot date or a widget completion date or a journey checkpoint-reached date).
DECLARE @Time1 DATETIME
SET @Time1 = '12/14/2015'
DECLARE @Time2 DATETIME
SET @Time2 = '12/15/2016'
The solution leverages simple measurement, conversion and calculations of the serial intersections of multiple cycles of different lengths; here: Century,Decade,Year,Month,Day (Thanks Mayan Calendar for the concept!). A quick note of thanks: I thank other contributors to Stack Overflow for showing me some of the component functions in this process that I've stitched together. I've positively rated these in my time on this forum.
First, construct a horizon that is the linear set of the intersections of the Century,Decade,Year,Month cycles, incremental by month. Use the cross join Cartesian function for this. (Think of this as creating the cloth from which we will cut a length between two 'yyyy-mm' points in order to measure distance):
SELECT
Linear_YearMonths = (centuries.century + decades.decade + years.[year] + months.[Month]),
1 AS value
INTO #linear_months
FROM
(SELECT '18' [century] UNION ALL
SELECT '19' UNION ALL
SELECT '20') centuries
CROSS JOIN
(SELECT '0' [decade] UNION ALL
SELECT '1' UNION ALL
SELECT '2' UNION ALL
SELECT '3' UNION ALL
SELECT '4' UNION ALL
SELECT '5' UNION ALL
SELECT '6' UNION ALL
SELECT '7' UNION ALL
SELECT '8' UNION ALL
SELECT '9') decades
CROSS JOIN
(SELECT '1' [year] UNION ALL
SELECT '2' UNION ALL
SELECT '3' UNION ALL
SELECT '4' UNION ALL
SELECT '5' UNION ALL
SELECT '6' UNION ALL
SELECT '7' UNION ALL
SELECT '8' UNION ALL
SELECT '9' UNION ALL
SELECT '0') years
CROSS JOIN
(SELECT '-01' [month] UNION ALL
SELECT '-02' UNION ALL
SELECT '-03' UNION ALL
SELECT '-04' UNION ALL
SELECT '-05' UNION ALL
SELECT '-06' UNION ALL
SELECT '-07' UNION ALL
SELECT '-08' UNION ALL
SELECT '-09' UNION ALL
SELECT '-10' UNION ALL
SELECT '-11' UNION ALL
SELECT '-12') [months]
ORDER BY 1
Then, convert your Time1 and Time2 date points into the 'yyyy-mm' format (Think of these as the coordinate cut points on the whole cloth). Retain the original datetime versions of the points as well:
SELECT
Time1 = @Time1,
[YYYY-MM of Time1] = CASE
WHEN LEFT(MONTH(@Time1),1) <> '1' OR MONTH(@Time1) = '1'
THEN (CAST(YEAR(@Time1) AS VARCHAR) + '-' + '0' + CAST(MONTH(@Time1) AS VARCHAR))
ELSE (CAST(YEAR(@Time1) AS VARCHAR) + '-' + CAST(MONTH(@Time1) AS VARCHAR))
END,
Time2 = @Time2,
[YYYY-MM of Time2] = CASE
WHEN LEFT(MONTH(@Time2),1) <> '1' OR MONTH(@Time2) = '1'
THEN (CAST(YEAR(@Time2) AS VARCHAR) + '-' + '0' + CAST(MONTH(@Time2) AS VARCHAR))
ELSE (CAST(YEAR(@Time2) AS VARCHAR) + '-' + CAST(MONTH(@Time2) AS VARCHAR))
END
INTO #datepoints
Then, Select the ordinal distance of 'yyyy-mm' units, less one to convert to cardinal distance (i.e. cut a piece of cloth from the whole cloth at the identified cut points and get its raw measurement):
SELECT
d.*,
Months_Between = (SELECT (SUM(l.value) - 1) FROM #linear_months l
WHERE l.[Linear_YearMonths] BETWEEN d.[YYYY-MM of Time1] AND d.[YYYY-MM of Time2])
FROM #datepoints d
Raw Output:
I call this a 'raw distance' because the month component of the 'yyyy-mm' cardinal distance may be one too many; the day cycle components within the month need to be compared to see if this last month value should count. In this example specifically, the raw output distance is '12'. But this wrong as 12/14 is before 12/15, so therefore only 11 full months have lapsed--its just one day shy of lapsing through the 12th month. We therefore have to bring in the intra-month day cycle to get to a final answer. Insert a 'month,day' position comparison between the to determine if the latest date point month counts nominally, or not:
SELECT
d.*,
Months_Between = (SELECT (SUM(l.value) - 1) FROM AZ_VBP.[MY].[edg_Linear_YearMonths] l
WHERE l.[Linear_YearMonths] BETWEEN d.[YYYY-MM of Time1] AND d.[YYYY-MM of Time2])
+ (CASE WHEN DAY(Time1) < DAY(Time2)
THEN -1
ELSE 0
END)
FROM #datepoints d
Final Output:
The correct answer of '11' is now our output. And so, I hope this helps. Thanks!
How do I auto-hide placeholder text upon focus using css or jquery?
Pure CSS Solution (no JS required)
Building on @Hexodus and @Casey Chu's answers, here is an updated and cross-browser solution that leverages CSS opacity and transitions to fade the placeholder text out. It works for any element that can use placeholders, including textarea
and input
tags.
_x000D_
_x000D_
::-webkit-input-placeholder { opacity: 1; -webkit-transition: opacity .5s; transition: opacity .5s; } /* Chrome <=56, Safari < 10 */
:-moz-placeholder { opacity: 1; -moz-transition: opacity .5s; transition: opacity .5s; } /* FF 4-18 */
::-moz-placeholder { opacity: 1; -moz-transition: opacity .5s; transition: opacity .5s; } /* FF 19-51 */
:-ms-input-placeholder { opacity: 1; -ms-transition: opacity .5s; transition: opacity .5s; } /* IE 10+ */
::placeholder { opacity: 1; transition: opacity .5s; } /* Modern Browsers */
*:focus::-webkit-input-placeholder { opacity: 0; } /* Chrome <=56, Safari < 10 */
*:focus:-moz-placeholder { opacity: 0; } /* FF 4-18 */
*:focus::-moz-placeholder { opacity: 0; } /* FF 19-50 */
*:focus:-ms-input-placeholder { opacity: 0; } /* IE 10+ */
*:focus::placeholder { opacity: 0; } /* Modern Browsers */
_x000D_
<div>
<div><label for="a">Input:</label></div>
<input id="a" type="text" placeholder="CSS native fade out this placeholder text on click/focus" size="60">
</div>
<br>
<div>
<div><label for="b">Textarea:</label></div>
<textarea id="b" placeholder="CSS native fade out this placeholder text on click/focus" rows="3"></textarea>
</div>
_x000D_
_x000D_
_x000D_
Revisions
- Edit 1 (2017): Updated to support modern browsers.
- Edit 2 (2020): Added the runnable Stack Snippet.
What is the difference between a generative and a discriminative algorithm?
A generative algorithm models how the data was generated in order to categorize a signal. It asks the question: based on my generation assumptions, which category is most likely to generate this signal?
A discriminative algorithm does not care about how the data was generated, it simply categorizes a given signal.
Sort ObservableCollection<string> through C#
Here is a slight variation on Shimmy's one for collection of classes that already implement the well-known IComparable<T>
interface. In this case, the "order by" selector is implicit.
public class SortedObservableCollection<T> : ObservableCollection<T> where T : IComparable<T>
{
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
if (e.Action != NotifyCollectionChangedAction.Reset &&
e.Action != NotifyCollectionChangedAction.Move &&
e.Action != NotifyCollectionChangedAction.Remove)
{
var query = this.Select((item, index) => (Item: item, Index: index)).OrderBy(tuple => tuple.Item, Comparer.Default);
var map = query.Select((tuple, index) => (OldIndex: tuple.Index, NewIndex: index)).Where(o => o.OldIndex != o.NewIndex);
using (var enumerator = map.GetEnumerator())
{
if (enumerator.MoveNext())
{
base.MoveItem(enumerator.Current.OldIndex, enumerator.Current.NewIndex);
}
}
}
}
// (optional) user is not allowed to move items in a sorted collection
protected override void MoveItem(int oldIndex, int newIndex) => throw new InvalidOperationException();
protected override void SetItem(int index, T item) => throw new InvalidOperationException();
private class Comparer : IComparer<T>
{
public static readonly Comparer Default = new Comparer();
public int Compare(T x, T y) => x.CompareTo(y);
}
// explicit sort; sometimes needed.
public virtual void Sort()
{
if (Items.Count <= 1)
return;
var items = Items.ToList();
Items.Clear();
items.Sort();
foreach (var item in items)
{
Items.Add(item);
}
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
Difference between using bean id and name in Spring configuration file
Since Spring 3.1 the id
attribute is an xsd:string
and permits the same range of characters as the name
attribute.
The only difference between an id
and a name
is that a name
can contain multiple aliases separated by a comma, semicolon or whitespace, whereas an id
must be a single value.
From the Spring 3.2 documentation:
In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are alphanumeric ('myBean', 'fooService', etc), but may special characters as well. If you want to introduce other aliases to the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id attribute was typed as an xsd:ID, which constrained possible characters. As of 3.1, it is now xsd:string. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.
Is there Selected Tab Changed Event in the standard WPF Tab Control
The event generated is bubbling up until it is handled.
This xaml portion below triggers ui_Tab_Changed
after ui_A_Changed
when the item selected in the ListView
changes, regardless of TabItem
change in the TabControl
.
<TabControl SelectionChanged="ui_Tab_Changed">
<TabItem>
<ListView SelectionChanged="ui_A_Changed" />
</TabItem>
<TabItem>
<ListView SelectionChanged="ui_B_Changed" />
</TabItem>
</TabControl>
We need to consume the event in ui_A_Changed
(and ui_B_Changed
, and so on):
private void ui_A_Changed(object sender, SelectionChangedEventArgs e) {
// do what you need to do
...
// then consume the event
e.Handled = true;
}
Format cell color based on value in another sheet and cell
Here's how I did it in Excel 2003 using conditional formatting.
To apply conditional formatting to Sheet1
using values from Sheet2
, you need to mirror the values into Sheet1
.
Creating a mirror of Sheet2, column B in Sheet 1
- Go to
Sheet1
.
- Insert a new column by right-clicking column A's header and selecting "Insert".
Enter the following formula into A1:
=IF(ISBLANK(Sheet2!B1),"",Sheet2!B1)
- Copy
A1
by right-clicking it and selecting "Copy
".
- Paste the formula into column
A
by right-clicking its header and selecting "Paste
".
Sheet1
, column A
should now exactly mirror the values in Sheet2
, column B
.
(Note: if you don't like it in column A
, it works just as well to have it in column Z
or anywhere else.)
Applying the conditional formatting
- Stay on
Sheet1
.
- Select column
B
by left-clicking its header.
- Select the menu item
Format > Conditional Formatting...
Change Condition 1
to "Formula is
" and enter this formula:
=MATCH(B1,$A:$A,0)
Click the Format...
button and select a green background.
You should now see the green background applied to the matching cells in Sheet1
.
Hiding the mirror column
- Stay on
Sheet1
.
- Right-click the header on column
A
and select "Hide
".
This should automatically update Sheet1
whenever anything in Sheet2
is changed.
CSS force new line
How about with a :before
pseudoelement:
a:before {
content: '\a';
white-space: pre;
}
Difference between numpy dot() and Python 3.5+ matrix multiplication @
Here is a comparison with np.einsum
to show how the indices are projected
np.allclose(np.einsum('ijk,ijk->ijk', a,b), a*b) # True
np.allclose(np.einsum('ijk,ikl->ijl', a,b), a@b) # True
np.allclose(np.einsum('ijk,lkm->ijlm',a,b), a.dot(b)) # True
Resolving ORA-4031 "unable to allocate x bytes of shared memory"
Don't forget about fragmentation.
If you have a lot of traffic, your pools can be fragmented and even if you have several MB free, there could be no block larger than 4KB.
Check size of largest free block with a query like:
select
'0 (<140)' BUCKET, KSMCHCLS, KSMCHIDX,
10*trunc(KSMCHSIZ/10) "From",
count(*) "Count" ,
max(KSMCHSIZ) "Biggest",
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ<140
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 10*trunc(KSMCHSIZ/10)
UNION ALL
select
'1 (140-267)' BUCKET,
KSMCHCLS,
KSMCHIDX,
20*trunc(KSMCHSIZ/20) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ between 140 and 267
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 20*trunc(KSMCHSIZ/20)
UNION ALL
select
'2 (268-523)' BUCKET,
KSMCHCLS,
KSMCHIDX,
50*trunc(KSMCHSIZ/50) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ between 268 and 523
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 50*trunc(KSMCHSIZ/50)
UNION ALL
select
'3-5 (524-4107)' BUCKET,
KSMCHCLS,
KSMCHIDX,
500*trunc(KSMCHSIZ/500) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ between 524 and 4107
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 500*trunc(KSMCHSIZ/500)
UNION ALL
select
'6+ (4108+)' BUCKET,
KSMCHCLS,
KSMCHIDX,
1000*trunc(KSMCHSIZ/1000) ,
count(*) ,
max(KSMCHSIZ) ,
trunc(avg(KSMCHSIZ)) "AvgSize",
trunc(sum(KSMCHSIZ)) "Total"
from
x$ksmsp
where
KSMCHSIZ >= 4108
and
KSMCHCLS='free'
group by
KSMCHCLS, KSMCHIDX, 1000*trunc(KSMCHSIZ/1000);
Code from
if else condition in blade file (laravel 5.3)
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
Import CSV file with mixed data types
For the case when you know how many columns of data there will be in your CSV file, one simple call to textscan
like Amro suggests will be your best solution.
However, if you don't know a priori how many columns are in your file, you can use a more general approach like I did in the following function. I first used the function fgetl
to read each line of the file into a cell array. Then I used the function textscan
to parse each line into separate strings using a predefined field delimiter and treating the integer fields as strings for now (they can be converted to numeric values later). Here is the resulting code, placed in a function read_mixed_csv
:
function lineArray = read_mixed_csv(fileName, delimiter)
fid = fopen(fileName, 'r'); % Open the file
lineArray = cell(100, 1); % Preallocate a cell array (ideally slightly
% larger than is needed)
lineIndex = 1; % Index of cell to place the next line in
nextLine = fgetl(fid); % Read the first line from the file
while ~isequal(nextLine, -1) % Loop while not at the end of the file
lineArray{lineIndex} = nextLine; % Add the line to the cell array
lineIndex = lineIndex+1; % Increment the line index
nextLine = fgetl(fid); % Read the next line from the file
end
fclose(fid); % Close the file
lineArray = lineArray(1:lineIndex-1); % Remove empty cells, if needed
for iLine = 1:lineIndex-1 % Loop over lines
lineData = textscan(lineArray{iLine}, '%s', ... % Read strings
'Delimiter', delimiter);
lineData = lineData{1}; % Remove cell encapsulation
if strcmp(lineArray{iLine}(end), delimiter) % Account for when the line
lineData{end+1} = ''; % ends with a delimiter
end
lineArray(iLine, 1:numel(lineData)) = lineData; % Overwrite line data
end
end
Running this function on the sample file content from the question gives this result:
>> data = read_mixed_csv('myfile.csv', ';')
data =
Columns 1 through 7
'04' 'abc' 'def' 'ghj' 'klm' '' ''
'' '' '' '' '' 'Test' 'text'
'' '' '' '' '' 'asdfhsdf' 'dsafdsag'
Columns 8 through 10
'' '' ''
'0xFF' '' ''
'0x0F0F' '' ''
The result is a 3-by-10 cell array with one field per cell where missing fields are represented by the empty string ''
. Now you can access each cell or a combination of cells to format them as you like. For example, if you wanted to change the fields in the first column from strings to integer values, you could use the function str2double
as follows:
>> data(:, 1) = cellfun(@(s) {str2double(s)}, data(:, 1))
data =
Columns 1 through 7
[ 4] 'abc' 'def' 'ghj' 'klm' '' ''
[NaN] '' '' '' '' 'Test' 'text'
[NaN] '' '' '' '' 'asdfhsdf' 'dsafdsag'
Columns 8 through 10
'' '' ''
'0xFF' '' ''
'0x0F0F' '' ''
Note that the empty fields results in NaN
values.
Why use String.Format?
Several reasons:
String.Format()
is very powerful. You can use simple format indicators (like fixed width, currency, character lengths, etc) right in the format string. You can even create your own format providers for things like expanding enums, mapping specific inputs to much more complicated outputs, or localization.
- You can do some powerful things by putting format strings in configuration files.
String.Format()
is often faster, as it uses a StringBuilder
and an efficient state machine behind the scenes, whereas string concatenation in .Net is relatively slow. For small strings the difference is negligible, but it can be noticable as the size of the string and number of substituted values increases.
String.Format()
is actually more familiar to many programmers, especially those coming from backgrounds that use variants of the old C printf()
function.
Finally, don't forget StringBuilder.AppendFormat()
. String.Format()
actually uses this method behind the scenes*, and going to the StringBuilder
directly can give you a kind of hybrid approach: explicitly use .Append()
(analogous to concatenation) for some parts of a large string, and use .AppendFormat()
in others.
* [edit] Original answer is now 8 years old, and I've since seen an indication this may have changed when string interpolation was added to .Net. However, I haven't gone back to the reference source to verify the change yet.
Explicitly select items from a list or tuple
>>> map(myList.__getitem__, (2,2,1,3))
('baz', 'baz', 'bar', 'quux')
You can also create your own List
class which supports tuples as arguments to __getitem__
if you want to be able to do myList[(2,2,1,3)]
.
How to use Boost in Visual Studio 2010
A small addition to KTC's very informative main answer:
If you are using the free Visual Studio c++ 2010 Express, and managed to get that one to compile 64-bits binaries, and now want to use that to use a 64-bits version of the Boost libaries, you may end up with 32-bits libraries (your mileage may vary of course, but on my machine this is the sad case).
I could fix this using the following: inbetween the steps described above as
- Start a 32-bit MSVC command prompt and change to the directory where Boost was unzipped.
- Run: bootstrap
I inserted a call to 'setenv' to set the environment. For a release build, the above steps become:
- Start a 32-bit MSVC command prompt and change to the directory where Boost was unzipped.
- Run: "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\setenv.cmd" /Release /x64
- Run: bootstrap
I found this info here:
http://boost.2283326.n4.nabble.com/64-bit-with-VS-Express-again-td3044258.html
How to solve WAMP and Skype conflict on Windows 7?
In Skype:
Go to Tools ? Options ? Advanced ? Connections
and uncheck the box use port 80 and 443 as alternative
. This should help.
As Salman Quader said: In the updated skype(8.x), there is no menu option to change the port. This means this answer is no longer valid.
Retrofit and GET using parameters
@QueryMap
worked for me instead of FieldMap
If you have a bunch of GET params, another way to pass them into your url is a HashMap
.
class YourActivity extends Activity {
private static final String BASEPATH = "http://www.example.com";
private interface API {
@GET("/thing")
void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
API service = rest.create(API.class);
Map<String, String> params = new HashMap<String, String>();
params.put("key1", "val1");
params.put("key2", "val2");
// ... as much as you need.
service.getMyThing(params, new Callback<String>() {
// ... do some stuff here.
});
}
}
The URL called will be http://www.example.com/thing/?key1=val1&key2=val2
How do I set GIT_SSL_NO_VERIFY for specific repos only?
There is an easy way of configuring GIT to handle your server the right way.
Just add an specific http section for your git server and specify which certificate (Base64 encoded) to trust:
~/.gitconfig
[http "https://repo.your-server.com"]
# windows path use double back slashes
# sslCaInfo = C:\\Users\\<user>\\repo.your-server.com.cer
# unix path to certificate (Base64 encoded)
sslCaInfo = /home/<user>/repo.your-server.com.cer
This way you will have no more SSL errors and validate the (usually) self-signed certificate. This is the best way to go, as it protects you from man-in-the-middle attacks. When you just disable ssl verification you are vulnerable to these kind of attacks.
https://git-scm.com/docs/git-config#git-config-httplturlgt
change <audio> src with javascript
with jQuery:
$("#playerSource").attr("src", "new_src");
var audio = $("#player");
audio[0].pause();
audio[0].load();//suspends and restores all audio element
if (isAutoplay)
audio[0].play();
Command CompileSwift failed with a nonzero exit code in Xcode 10
It seems like this is a pretty vague error, so I will share what I did to fix it when I ran into this:
Using Xcode 10.1 and Swift 4.2 I tried pretty much all the suggestions here but none of them worked for me, then I realized a dependency I was using was not compatible with Swift 4.2 and that was causing me to get this error on other pods. So to fix it I just had to force that pod to use Swift 4.0 by putting this at the end of my Podfile
:
post_install do |installer|
installer.pods_project.targets.each do |target|
if ['TKRadarChart'].include? target.name
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '4.0'
end
end
end
end
Sending HTML email using Python
Here's sample code. This is inspired from code found on the Python Cookbook site (can't find the exact link)
def createhtmlmail (html, text, subject, fromEmail):
"""Create a mime-message that will render HTML in popular
MUAs, text in better ones"""
import MimeWriter
import mimetools
import cStringIO
out = cStringIO.StringIO() # output buffer for our message
htmlin = cStringIO.StringIO(html)
txtin = cStringIO.StringIO(text)
writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
writer.addheader("From", fromEmail)
writer.addheader("Subject", subject)
writer.addheader("MIME-Version", "1.0")
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
writer.startmultipartbody("alternative")
writer.flushheaders()
#
# the plain text section
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
pout = subpart.startbody("text/plain", [("charset", 'us-ascii')])
mimetools.encode(txtin, pout, 'quoted-printable')
txtin.close()
#
# start the html subpart of the message
#
subpart = writer.nextpart()
subpart.addheader("Content-Transfer-Encoding", "quoted-printable")
#
# returns us a file-ish object we can write to
#
pout = subpart.startbody("text/html", [("charset", 'us-ascii')])
mimetools.encode(htmlin, pout, 'quoted-printable')
htmlin.close()
#
# Now that we're done, close our writer and
# return the message body
#
writer.lastpart()
msg = out.getvalue()
out.close()
print msg
return msg
if __name__=="__main__":
import smtplib
html = 'html version'
text = 'TEST VERSION'
subject = "BACKUP REPORT"
message = createhtmlmail(html, text, subject, 'From Host <[email protected]>')
server = smtplib.SMTP("smtp_server_address","smtp_port")
server.login('username', 'password')
server.sendmail('[email protected]', '[email protected]', message)
server.quit()
launch sms application with an intent
The below code works on android 6.0.
It will open the search activity in the default messaging application with the conversations related to specific string provided.
Intent smsIntent = new Intent(Intent.ACTION_MAIN);
smsIntent.addCategory(Intent.CATEGORY_LAUNCHER);
smsIntent.setClassName("com.android.mms", "com.android.mms.ui.SearchActivity");
smsIntent.putExtra("intent_extra_data_key", "string_to_search_for");
startActivity(smsIntent);
You can start the search activity with an intent. This will open the search activity of the default messaging application.
Now, to show a list of specific conversations in the search activity, you can provide the search string as string extra with the key as
"intent_extra_data_key"
as is shown in the onCreate of this class
String searchStringParameter = getIntent().getStringExtra(SearchManager.QUERY);
if (searchStringParameter == null) {
searchStringParameter = getIntent().getStringExtra("intent_extra_data_key" /*SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA*/);
}
final String searchString = searchStringParameter != null ? searchStringParameter.trim() : searchStringParameter;
You can also pass the SENDER_ADDRESS of the sms as string extra, which will list out all the conversations with that specific sender address.
Check com.android.mms.ui.SearchActivity for more information
You can also check this answer
What is the C# version of VB.net's InputDialog?
Returns the string the user entered; empty string if they hit Cancel:
public static String InputBox(String caption, String prompt, String defaultText)
{
String localInputText = defaultText;
if (InputQuery(caption, prompt, ref localInputText))
{
return localInputText;
}
else
{
return "";
}
}
Returns the String
as a ref parameter, returning true
if they hit OK, or false
if they hit Cancel:
public static Boolean InputQuery(String caption, String prompt, ref String value)
{
Form form;
form = new Form();
form.AutoScaleMode = AutoScaleMode.Font;
form.Font = SystemFonts.IconTitleFont;
SizeF dialogUnits;
dialogUnits = form.AutoScaleDimensions;
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.Text = caption;
form.ClientSize = new Size(
Toolkit.MulDiv(180, dialogUnits.Width, 4),
Toolkit.MulDiv(63, dialogUnits.Height, 8));
form.StartPosition = FormStartPosition.CenterScreen;
System.Windows.Forms.Label lblPrompt;
lblPrompt = new System.Windows.Forms.Label();
lblPrompt.Parent = form;
lblPrompt.AutoSize = true;
lblPrompt.Left = Toolkit.MulDiv(8, dialogUnits.Width, 4);
lblPrompt.Top = Toolkit.MulDiv(8, dialogUnits.Height, 8);
lblPrompt.Text = prompt;
System.Windows.Forms.TextBox edInput;
edInput = new System.Windows.Forms.TextBox();
edInput.Parent = form;
edInput.Left = lblPrompt.Left;
edInput.Top = Toolkit.MulDiv(19, dialogUnits.Height, 8);
edInput.Width = Toolkit.MulDiv(164, dialogUnits.Width, 4);
edInput.Text = value;
edInput.SelectAll();
int buttonTop = Toolkit.MulDiv(41, dialogUnits.Height, 8);
//Command buttons should be 50x14 dlus
Size buttonSize = Toolkit.ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8);
System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button();
bbOk.Parent = form;
bbOk.Text = "OK";
bbOk.DialogResult = DialogResult.OK;
form.AcceptButton = bbOk;
bbOk.Location = new Point(Toolkit.MulDiv(38, dialogUnits.Width, 4), buttonTop);
bbOk.Size = buttonSize;
System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button();
bbCancel.Parent = form;
bbCancel.Text = "Cancel";
bbCancel.DialogResult = DialogResult.Cancel;
form.CancelButton = bbCancel;
bbCancel.Location = new Point(Toolkit.MulDiv(92, dialogUnits.Width, 4), buttonTop);
bbCancel.Size = buttonSize;
if (form.ShowDialog() == DialogResult.OK)
{
value = edInput.Text;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Multiplies two 32-bit values and then divides the 64-bit result by a
/// third 32-bit value. The final result is rounded to the nearest integer.
/// </summary>
public static int MulDiv(int nNumber, int nNumerator, int nDenominator)
{
return (int)Math.Round((float)nNumber * nNumerator / nDenominator);
}
Note: Any code is released into the public domain. No attribution required.
Adding HTML entities using CSS content
In CSS you need to use a Unicode escape sequence in place of HTML Entities. This is based on the hexadecimal value of a character.
I found that the easiest way to convert symbol to their hexadecimal equivalent is, such as from ▾ (▾
) to \25BE
is to use the Microsoft calculator =)
Yes. Enable programmers mode, turn on the decimal system, enter 9662
, then switch to hex and you'll get 25BE
. Then just add a backslash \
to the beginning.
Build error, This project references NuGet
It's a bit old post but I recently ran into this issue.
All I did was deleted all the nuget packages from packages folder and restored it.
I was able to build the solution successfully.
Hopefully helpful to someone.
++i or i++ in for loops ??
when you use postfix it instantiates on more object in memory. Some people say that it is better to use suffix operator in for loop
how to reset <input type = "file">
You need to wrap <input type = “file”>
in to <form>
tags and then you can reset input by resetting your form:
onClick="this.form.reset()"
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How to split an integer into an array of digits?
Another solution that does not involve converting to/from strings:
from math import log10
def decompose(n):
if n == 0:
return [0]
b = int(log10(n)) + 1
return [(n // (10 ** i)) % 10 for i in reversed(range(b))]
Is there a bash command which counts files?
Lots of answers here, but some don't take into account
- file names with spaces, newlines, or control characters in them
- file names that start with hyphens (imagine a file called
-l
)
- hidden files, that start with a dot (if the glob was
*.log
instead of log*
- directories that match the glob (e.g. a directory called
logs
that matches log*
)
- empty directories (i.e. the result is 0)
- extremely large directories (listing them all could exhaust memory)
Here's a solution that handles all of them:
ls 2>/dev/null -Ubad1 -- log* | wc -l
Explanation:
-U
causes ls
to not sort the entries, meaning it doesn't need to load the entire directory listing in memory
-b
prints C-style escapes for nongraphic characters, crucially causing newlines to be printed as \n
.
-a
prints out all files, even hidden files (not strictly needed when the glob log*
implies no hidden files)
-d
prints out directories without attempting to list the contents of the directory, which is what ls
normally would do
-1
makes sure that it's on one column (ls does this automatically when writing to a pipe, so it's not strictly necessary)
2>/dev/null
redirects stderr so that if there are 0 log files, ignore the error message. (Note that shopt -s nullglob
would cause ls
to list the entire working directory instead.)
wc -l
consumes the directory listing as it's being generated, so the output of ls
is never in memory at any point in time.
--
File names are separated from the command using --
so as not to be understood as arguments to ls
(in case log*
is removed)
The shell will expand log*
to the full list of files, which may exhaust memory if it's a lot of files, so then running it through grep is be better:
ls -Uba1 | grep ^log | wc -l
This last one handles extremely large directories of files without using a lot of memory (albeit it does use a subshell). The -d
is no longer necessary, because it's only listing the contents of the current directory.
How to Update a Component without refreshing full page - Angular
Angular will automatically update a component when it detects a variable change .
So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts
or via an @Input
variable...
an example...
main.html
<app-header [header-data]="headerData"></app-header>
main.component.ts
public headerData:int = 0;
ngOnInit(){
setInterval(()=>{this.headerData++;}, 250);
}
header.html
<p>{{data}}</p>
header.ts
@Input('header-data') data;
In the above example, the header will recieve the new data every 250ms and thus update the component.
For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks
docker container ssl certificates
Mount the certs onto the Docker container using -v
:
docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"
SQL WITH clause example
This has been fully answered here.
See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:
WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'
how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?
BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH!
Then installed the latest version, 8u151-i586, rebooted no warning.
I added lines in PATH as above, didn't do anything.
My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found.
Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.
How do I properly clean up Excel interop objects?
Make sure that you release all objects related to Excel!
I spent a few hours by trying several ways. All are great ideas but I finally found my mistake: If you don't release all objects, none of the ways above can help you like in my case. Make sure you release all objects including range one!
Excel.Range rng = (Excel.Range)worksheet.Cells[1, 1];
worksheet.Paste(rng, false);
releaseObject(rng);
The options are together here.
Detect if Android device has Internet connection
The latest way to do that from the documentation is to use the ConnectivityManager
to query the active network and determine if it has Internet connectivity.
public boolean hasInternetConnectivity() {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return (activeNetwork != null &&
activeNetwork.isConnectedOrConnecting());
}
Add these two permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
PHP cURL HTTP CODE return 0
If you connect with the server, then you can get a return code from it, otherwise it will fail and you get a 0. So if you try to connect to "www.google.com/lksdfk" you will get a return code of 400, if you go directly to google.com, you will get 302 (and then 200 if you forward to the next page... well I do because it forwards to google.com.br, so you might not get that), and if you go to "googlecom" you will get a 0 (host no found), so with the last one, there is nobody to send a code back.
Tested using the code below.
<?php
$html_brand = "www.google.com";
$ch = curl_init();
$options = array(
CURLOPT_URL => $html_brand,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $httpCode != 200 ){
echo "Return code is {$httpCode} \n"
.curl_error($ch);
} else {
echo "<pre>".htmlspecialchars($response)."</pre>";
}
curl_close($ch);
Change icon on click (toggle)
Try this:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.hasClass("icon-circle-arrow-down"){
icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down");
}else{
icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up");
}
})
or even better, as Kevin said:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down")
})
JavaFX - create custom button with image
You just need to create your own class inherited from parent.
Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.
public class ImageButton extends Parent {
private static final Image NORMAL_IMAGE = ...;
private static final Image PRESSED_IMAGE = ...;
private final ImageView iv;
public ImageButton() {
this.iv = new ImageView(NORMAL_IMAGE);
this.getChildren().add(this.iv);
this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(PRESSED_IMAGE);
}
});
// TODO other event handlers like mouse up
}
}
Object cannot be cast from DBNull to other types
TryParse is usually the most elegant way to handle this type of thing:
long temp = 0;
if (Int64.TryParse(dataAccCom.GetParameterValue(IDbCmd, "op_Id").ToString(), out temp))
{
DataTO.Id = temp;
}
How to set underline text on textview?
Android supports string formatting using HTML tags in the strings xml. So the following would work:
<string name="label_testinghtmltags"><u>This text has an underscore</u></string>
Then you just use it as you normally would. You can see more in the documentation here
Update:
To further expand on the answer, the documentation says:
... the format(String, Object...)
and getString(int, Object...)
methods strip all the style information from the string. . The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place
For example, the resulting string from the following code snippet will not show up as containing underscored elements:
<string name="html_bold_test">This <u>%1$s</u> has an underscore</string>
String result = getString(R.string.html_bold_test, "text")
However the result from the following snippet would contain underscores:
<string name="html_bold_test">This <u> %1$s </u> has an underscore</string>
String result = Html.fromHtml(getString(R.string.html_bold_test, "text"))
How to create a DataFrame of random integers with Pandas?
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
How can I disable the default console handler, while using the java logging API?
The default console handler is attached to the root logger, which is a parent of all other loggers including yours. So I see two ways to solve your problem:
If this is only affects this particular class of yours, the simplest solution would be to disable passing the logs up to the parent logger:
logger.setUseParentHandlers(false);
If you want to change this behaviour for your whole app, you could remove the default console handler from the root logger altogether before adding your own handlers:
Logger globalLogger = Logger.getLogger("global");
Handler[] handlers = globalLogger.getHandlers();
for(Handler handler : handlers) {
globalLogger.removeHandler(handler);
}
Note: if you want to use the same log handlers in other classes too, the best way is to move the log configuration into a config file in the long run.
How to display line numbers in 'less' (GNU)
You can also press =
while less
is open to just display (at the bottom of the screen) information about the current screen, including line numbers, with format:
myfile.txt lines 20530-20585/1816468 byte 1098945/116097872 1% (press RETURN)
So here for example, the screen was currently showing lines 20530-20585
, and the files has a total of 1816468
lines.
Fill DataTable from SQL Server database
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
How can I concatenate strings in VBA?
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
What is Robocopy's "restartable" option?
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
C# DateTime to "YYYYMMDDHHMMSS" format
DateTime.Now.ToString("MM/dd/yyyy") 05/29/2015
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50 AM
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50 AM
DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss") Friday, 29 May 2015 05:50:06
DateTime.Now.ToString("MM/dd/yyyy HH:mm") 05/29/2015 05:50
DateTime.Now.ToString("MM/dd/yyyy hh:mm tt") 05/29/2015 05:50 AM
DateTime.Now.ToString("MM/dd/yyyy H:mm") 05/29/2015 5:50
DateTime.Now.ToString("MM/dd/yyyy h:mm tt") 05/29/2015 5:50 AM
DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") 05/29/2015 05:50:06
DateTime.Now.ToString("MMMM dd") May 29
DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK") 2015-05-16T05:50:06.7199222-04:00
DateTime.Now.ToString("ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT’") Fri, 16 May 2015 05:50:06 GMT
DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss") 2015-05-16T05:50:06
DateTime.Now.ToString("HH:mm") 05:50
DateTime.Now.ToString("hh:mm tt") 05:50 AM
DateTime.Now.ToString("H:mm") 5:50
DateTime.Now.ToString("h:mm tt") 5:50 AM
DateTime.Now.ToString("HH:mm:ss") 05:50:06
DateTime.Now.ToString("yyyy MMMM") 2015 May
PHP cURL error code 60
IMPORTANT: after 4 hours , working with laravel 5.7 and php 7.+ and run/use php artison serve
on localhost trying to connect to mailgun .
IMPORTANT to Resolve the problem do not work with ip http://127.0.0.1:8000
use localhost or set domain name by host file
ok ,
Python: Figure out local timezone
In Python 3.x, local timezone can be figured out like this:
import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
It's a tricky use of datetime
's code .
For python >= 3.6, you'll need
import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo
UIImageView - How to get the file name of the image assigned?
Nope. You can't do that.
The reason is that a UIImageView
instance does not store an image file. It stores a displays a UIImage
instance. When you make an image from a file, you do something like this:
UIImage *picture = [UIImage imageNamed:@"myFile.png"];
Once this is done, there is no longer any reference to the filename. The UIImage
instance contains the data, regardless of where it got it. Thus, the UIImageView
couldn't possibly know the filename.
Also, even if you could, you would never get filename info from a view. That breaks MVC.
Combine or merge JSON on node.js without jQuery
The below code will help you to merge two JSON object which has nested objects.
function mergeJSON(source1,source2){
/*
* Properties from the Souce1 object will be copied to Source2 Object.
* Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
* */
var mergedJSON = Object.create(source2);// Copying Source2 to a new Object
for (var attrname in source1) {
if(mergedJSON.hasOwnProperty(attrname)) {
if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
/*
* Recursive call if the property is an object,
* Iterate the object and set all properties of the inner object.
*/
mergedJSON[attrname] = zrd3.utils.mergeJSON(source1[attrname], mergedJSON[attrname]);
}
} else {//else copy the property from source1
mergedJSON[attrname] = source1[attrname];
}
}
return mergedJSON;
}
Error:(1, 0) Plugin with id 'com.android.application' not found
I was using IntelliJ IDEA 13.1.5 and faced with the same problem after I changed versions of Picasso and Retrofit in dependencies
in build.gradle
file. I tried use many solutions, but without result.
Then I cloned my project from remote git (where I pushed it before changing versions of dependencies) and it worked! After that I just closed current project and imported old project from Gradle file to IntelliJ IDEA again and it worked too! So, I think it was strange bug in intersection of IDEA, Gradle and Android plugin. I hope this information can be useful for IDEA-users or anyone else.
navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't
You don't get an error message because it has no timeout by default (At least i think). I have had the same problem with firefox only for me firefox always gives an timeout. You can set a timeout yourself like this.
My function works great in chrome but i get a timeout everytime in firefox.
navigator.geolocation.getCurrentPosition(
function(position) {
//do succes handling
},
function errorCallback(error) {
//do error handling
},
{
timeout:5000
}
);
I recommend to watch your errors carefully. Be expected for everything. Have a backup plan for everything. I use some default values or values from my database myself in case both google geolocations and navigator geolocations fails.
UILabel text margin
If label is created programmatically, padding can be calculated using the sizeThatFits method. If using more than one line, the text will be line broken at the max width value.
let text = UILabel()
let padding = 10
text.layer.cornerRadius = 5
text.layer.masksToBounds = true
text.text = "Hello"
text.font = UIFont(name: text.font.fontName, size: 18)
text.textAlignment = NSTextAlignment.center
text.numberOfLines = 1
let maxSize = CGSize(width: 100, height: 100)
var size = text.sizeThatFits(maxSize)
size.width = size.width + padding * 2
size.height = size.height + padding * 2
text.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
Digital Certificate: How to import .cer file in to .truststore file using?
The way you import a .cer file into the trust store is the same way you'd import a .crt file from say an export from Firefox.
You do not have to put an alias and the password of the keystore, you can just type:
keytool -v -import -file somefile.crt -alias somecrt -keystore my-cacerts
Preferably use the cacerts file that is already in your Java installation (jre\lib\security\cacerts) as it contains secure "popular" certificates.
Update regarding the differences of cer and crt (just to clarify)
According to Apache with SSL - How to convert CER to CRT certificates? and user @Spawnrider
CER is a X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.
It is not the same encoding.
Short circuit Array.forEach like calling break
This isn't the most efficient, since you still cycle all the elements, but I thought it might be worth considering the very simple:
let keepGoing = true;
things.forEach( (thing) => {
if (noMore) keepGoing = false;
if (keepGoing) {
// do things with thing
}
});
Control flow in T-SQL SP using IF..ELSE IF - are there other ways?
Also you can try to formulate your answer in the form of a SELECT CASE
Statement. You can then later create simple if then's that use your results if needed as you have narrowed down the possibilities.
SELECT @Result =
CASE @inputParam
WHEN 1 THEN 1
WHEN 2 THEN 2
WHEN 3 THEN 1
ELSE 4
END
IF @Result = 1
BEGIN
...
END
IF @Result = 2
BEGIN
....
END
IF @Result = 4
BEGIN
//Error handling code
END
How can I add some small utility functions to my AngularJS application?
Here is a simple, compact and easy to understand method I use.
First, add a service in your js.
app.factory('Helpers', [ function() {
// Helper service body
var o = {
Helpers: []
};
// Dummy function with parameter being passed
o.getFooBar = function(para) {
var valueIneed = para + " " + "World!";
return valueIneed;
};
// Other helper functions can be added here ...
// And we return the helper object ...
return o;
}]);
Then, in your controller, inject your helper object and use any available function with something like the following:
app.controller('MainCtrl', [
'$scope',
'Helpers',
function($scope, Helpers){
$scope.sayIt = Helpers.getFooBar("Hello");
console.log($scope.sayIt);
}]);
What's the fastest way to do a bulk insert into Postgres?
PostgreSQL has a guide on how to best populate a database initially, and they suggest using the COPY command for bulk loading rows. The guide has some other good tips on how to speed up the process, like removing indexes and foreign keys before loading the data (and adding them back afterwards).
Get a file name from a path
std::string getfilename(std::string path)
{
path = path.substr(path.find_last_of("/\\") + 1);
size_t dot_i = path.find_last_of('.');
return path.substr(0, dot_i);
}
Making custom right-click context menus for my web-app
here is an example for right click context menu in javascript:
Right Click Context Menu
Used raw javasScript Code for context menu functionality. Can you please check this, hope this will help you.
Live Code:
_x000D_
_x000D_
(function() {_x000D_
_x000D_
"use strict";_x000D_
_x000D_
_x000D_
/*********************************************** Context Menu Function Only ********************************/_x000D_
function clickInsideElement( e, className ) {_x000D_
var el = e.srcElement || e.target;_x000D_
if ( el.classList.contains(className) ) {_x000D_
return el;_x000D_
} else {_x000D_
while ( el = el.parentNode ) {_x000D_
if ( el.classList && el.classList.contains(className) ) {_x000D_
return el;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
function getPosition(e) {_x000D_
var posx = 0, posy = 0;_x000D_
if (!e) var e = window.event;_x000D_
if (e.pageX || e.pageY) {_x000D_
posx = e.pageX;_x000D_
posy = e.pageY;_x000D_
} else if (e.clientX || e.clientY) {_x000D_
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;_x000D_
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;_x000D_
}_x000D_
return {_x000D_
x: posx,_x000D_
y: posy_x000D_
}_x000D_
}_x000D_
_x000D_
// Your Menu Class Name_x000D_
var taskItemClassName = "thumb";_x000D_
var contextMenuClassName = "context-menu",contextMenuItemClassName = "context-menu__item",contextMenuLinkClassName = "context-menu__link", contextMenuActive = "context-menu--active";_x000D_
var taskItemInContext, clickCoords, clickCoordsX, clickCoordsY, menu = document.querySelector("#context-menu"), menuItems = menu.querySelectorAll(".context-menu__item");_x000D_
var menuState = 0, menuWidth, menuHeight, menuPosition, menuPositionX, menuPositionY, windowWidth, windowHeight;_x000D_
_x000D_
function initMenuFunction() {_x000D_
contextListener();_x000D_
clickListener();_x000D_
keyupListener();_x000D_
resizeListener();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for contextmenu events._x000D_
*/_x000D_
function contextListener() {_x000D_
document.addEventListener( "contextmenu", function(e) {_x000D_
taskItemInContext = clickInsideElement( e, taskItemClassName );_x000D_
_x000D_
if ( taskItemInContext ) {_x000D_
e.preventDefault();_x000D_
toggleMenuOn();_x000D_
positionMenu(e);_x000D_
} else {_x000D_
taskItemInContext = null;_x000D_
toggleMenuOff();_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for click events._x000D_
*/_x000D_
function clickListener() {_x000D_
document.addEventListener( "click", function(e) {_x000D_
var clickeElIsLink = clickInsideElement( e, contextMenuLinkClassName );_x000D_
_x000D_
if ( clickeElIsLink ) {_x000D_
e.preventDefault();_x000D_
menuItemListener( clickeElIsLink );_x000D_
} else {_x000D_
var button = e.which || e.button;_x000D_
if ( button === 1 ) {_x000D_
toggleMenuOff();_x000D_
}_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for keyup events._x000D_
*/_x000D_
function keyupListener() {_x000D_
window.onkeyup = function(e) {_x000D_
if ( e.keyCode === 27 ) {_x000D_
toggleMenuOff();_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Window resize event listener_x000D_
*/_x000D_
function resizeListener() {_x000D_
window.onresize = function(e) {_x000D_
toggleMenuOff();_x000D_
};_x000D_
}_x000D_
_x000D_
/**_x000D_
* Turns the custom context menu on._x000D_
*/_x000D_
function toggleMenuOn() {_x000D_
if ( menuState !== 1 ) {_x000D_
menuState = 1;_x000D_
menu.classList.add( contextMenuActive );_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Turns the custom context menu off._x000D_
*/_x000D_
function toggleMenuOff() {_x000D_
if ( menuState !== 0 ) {_x000D_
menuState = 0;_x000D_
menu.classList.remove( contextMenuActive );_x000D_
}_x000D_
}_x000D_
_x000D_
function positionMenu(e) {_x000D_
clickCoords = getPosition(e);_x000D_
clickCoordsX = clickCoords.x;_x000D_
clickCoordsY = clickCoords.y;_x000D_
menuWidth = menu.offsetWidth + 4;_x000D_
menuHeight = menu.offsetHeight + 4;_x000D_
_x000D_
windowWidth = window.innerWidth;_x000D_
windowHeight = window.innerHeight;_x000D_
_x000D_
if ( (windowWidth - clickCoordsX) < menuWidth ) {_x000D_
menu.style.left = (windowWidth - menuWidth)-0 + "px";_x000D_
} else {_x000D_
menu.style.left = clickCoordsX-0 + "px";_x000D_
}_x000D_
_x000D_
// menu.style.top = clickCoordsY + "px";_x000D_
_x000D_
if ( Math.abs(windowHeight - clickCoordsY) < menuHeight ) {_x000D_
menu.style.top = (windowHeight - menuHeight)-0 + "px";_x000D_
} else {_x000D_
menu.style.top = clickCoordsY-0 + "px";_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
function menuItemListener( link ) {_x000D_
var menuSelectedPhotoId = taskItemInContext.getAttribute("data-id");_x000D_
console.log('Your Selected Photo: '+menuSelectedPhotoId)_x000D_
var moveToAlbumSelectedId = link.getAttribute("data-action");_x000D_
if(moveToAlbumSelectedId == 'remove'){_x000D_
console.log('You Clicked the remove button')_x000D_
}else if(moveToAlbumSelectedId && moveToAlbumSelectedId.length > 7){_x000D_
console.log('Clicked Album Name: '+moveToAlbumSelectedId);_x000D_
}_x000D_
toggleMenuOff();_x000D_
}_x000D_
initMenuFunction();_x000D_
_x000D_
})();
_x000D_
/* For Body Padding and content */_x000D_
body { padding-top: 70px; }_x000D_
li a { text-decoration: none !important; }_x000D_
_x000D_
/* Thumbnail only */_x000D_
.thumb {_x000D_
margin-bottom: 30px;_x000D_
}_x000D_
.thumb:hover a, .thumb:active a, .thumb:focus a {_x000D_
border: 1px solid purple;_x000D_
}_x000D_
_x000D_
/************** For Context menu ***********/_x000D_
/* context menu */_x000D_
.context-menu { display: none; position: absolute; z-index: 9999; padding: 12px 0; width: 200px; background-color: #fff; border: solid 1px #dfdfdf; box-shadow: 1px 1px 2px #cfcfcf; }_x000D_
.context-menu--active { display: block; }_x000D_
_x000D_
.context-menu__items { list-style: none; margin: 0; padding: 0; }_x000D_
.context-menu__item { display: block; margin-bottom: 4px; }_x000D_
.context-menu__item:last-child { margin-bottom: 0; }_x000D_
.context-menu__link { display: block; padding: 4px 12px; color: #0066aa; text-decoration: none; }_x000D_
.context-menu__link:hover { color: #fff; background-color: #0066aa; }_x000D_
.context-menu__items ul { position: absolute; white-space: nowrap; z-index: 1; left: -99999em;}_x000D_
.context-menu__items > li:hover > ul { left: auto; padding-top: 5px ; min-width: 100%; }_x000D_
.context-menu__items > li li ul { border-left:1px solid #fff;}_x000D_
.context-menu__items > li li:hover > ul { left: 100%; top: -1px; }_x000D_
.context-menu__item ul { background-color: #ffffff; padding: 7px 11px; list-style-type: none; text-decoration: none; margin-left: 40px; }_x000D_
.page-media .context-menu__items ul li { display: block; }_x000D_
/************** For Context menu ***********/
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<!-- Page Content -->_x000D_
<div class="container">_x000D_
_x000D_
<div class="row">_x000D_
_x000D_
<div class="col-lg-12">_x000D_
<h1 class="page-header">Thumbnail Gallery <small>(Right click to see the context menu)</small></h1>_x000D_
</div>_x000D_
_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
_x000D_
</div>_x000D_
<!-- /.container -->_x000D_
_x000D_
_x000D_
<!-- / The Context Menu -->_x000D_
<nav id="context-menu" class="context-menu">_x000D_
<ul class="context-menu__items">_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Delete This Photo"><i class="fa fa-empire"></i> Delete This Photo</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 2"><i class="fa fa-envira"></i> Photo Option 2</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 3"><i class="fa fa-first-order"></i> Photo Option 3</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 4"><i class="fa fa-gitlab"></i> Photo Option 4</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 5"><i class="fa fa-ioxhost"></i> Photo Option 5</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link"><i class="fa fa-arrow-right"></i> Add Photo to</a>_x000D_
<ul>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-one"><i class="fa fa-camera-retro"></i> Album One</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-two"><i class="fa fa-camera-retro"></i> Album Two</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-three"><i class="fa fa-camera-retro"></i> Album Three</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-four"><i class="fa fa-camera-retro"></i> Album Four</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<!-- End # Context Menu -->_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_
Cast int to varchar
I will be answering this in general terms, and very thankful to the above contributers.
I am using MySQL on MySQL Workbench. I had a similar issue trying to concatenate a char
and an int
together using the GROUP_CONCAT
method.
In summary, what has worked for me is this:
let's say your char
is 'c' and int
is 'i', so, the query becomes:
...GROUP_CONCAT(CONCAT(c,' ', CAST(i AS CHAR))...
Checking for a null int value from a Java ResultSet
Another solution:
public class DaoTools {
static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {
int nValue = rs.getInt(strColName);
return rs.wasNull() ? null : nValue;
}
}
Use and meaning of "in" in an if statement?
This may be a very late answer.
in operator checks for memberships. That is, it checks if its left operand is a member of its right operand. In this case, raw_input() returns an str object of what is supplied by the user at the standard input. So, the if condition checks whether the input contains substrings "0" or "1". Considering the typecasting (int()) in the following line, the if condition essentially checks if the input contains digits 0 or 1.
What is an Android PendingIntent?
A future intent that other apps can use.
And here's an example for creating one:
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(context, 0, intent, 0);
Tkinter scrollbar for frame
Please note that the proposed code is only valid with Python 2
Here is an example:
from Tkinter import * # from x import * is bad practice
from ttk import *
# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
class VerticalScrolledFrame(Frame):
"""A pure Tkinter scrollable frame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable frame
* Construct and pack/place/grid normally
* This frame only allows vertical scrolling
"""
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
if __name__ == "__main__":
class SampleApp(Tk):
def __init__(self, *args, **kwargs):
root = Tk.__init__(self, *args, **kwargs)
self.frame = VerticalScrolledFrame(root)
self.frame.pack()
self.label = Label(text="Shrink the window to activate the scrollbar.")
self.label.pack()
buttons = []
for i in range(10):
buttons.append(Button(self.frame.interior, text="Button " + str(i)))
buttons[-1].pack()
app = SampleApp()
app.mainloop()
It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.
edit:
to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.
to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).
to 3)
Well, it positions the window on the canvas.
One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.
Excel cell value as string won't store as string
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
getString Outside of a Context or Activity
Yes, we can access resources without using `Context`
You can use:
Resources.getSystem().getString(android.R.string.somecommonstuff)
... everywhere in your application, even in static constants declarations.
Unfortunately, it supports the system resources only.
For local resources use this solution. It is not trivial, but it works.
findViewById in Fragment
Use
imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);
imageview = (ImageView) getActivity().findViewById(R.id.imageview1);
it will work
How to format date in angularjs
This will work:
{{ oD.OrderDate.replace('/Date(','').replace(')/','') | date:"MM/dd/yyyy" }}
NOTE: once you replace these then remaining date/millis will be converted to given foramt.
Running a CMD or BAT in silent mode
I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)
That should answer your question.
Here it is:
From your first script, call your second script with the following line:
wscript.exe invis.vbs run.bat %*
Actually, you are calling a vbs script with:
- the [path]\name of your script
- all the other arguments needed by your script (
%*
)
Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:
- intWindowStyle : 0 means "invisible windows"
- bWaitOnReturn : false means your first script does not need to wait for your second script to finish
See the question for the full invis.vbs script:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
^
means "invisible window" ---|
Update after Tammen's feedback:
If you are in a DOS session and you want to launch another script "in the background", a simple /b
(as detailed in the same aforementioned question) can be enough:
You can use start /b second.bat
to launch a second batch file asynchronously from your first that shares your first one's window.
Setting width to wrap_content for TextView through code
A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.
If you want to update e.g. only the width you can do that with the following line in Kotlin.
tv.updateLayoutParams { width = WRAP_CONTENT }
How to convert a factor to integer\numeric without loss of information?
type.convert(f)
on a factor whose levels are completely numeric is another base option.
Performance-wise it's about equivalent to as.numeric(as.character(f))
but not nearly as quick as as.numeric(levels(f))[f]
.
identical(type.convert(f), as.numeric(levels(f))[f])
[1] TRUE
That said, if the reason the vector was created as a factor in the first instance has not been addressed (i.e. it likely contained some characters that could not be coerced to numeric) then this approach won't work and it will return a factor.
levels(f)[1] <- "some character level"
identical(type.convert(f), as.numeric(levels(f))[f])
[1] FALSE
ReSharper "Cannot resolve symbol" even when project builds
No soft caches removal solutions worked for me, it looks like there were issues generated between different RS versions installed over the years.
What worked for me was:
- Uninstal resharper
- remove all JetBrains folders within AppData\Local
and AppData\Roaming
- Install resharper again
All the settings need to be redone, etc but I couldnt get any better solution even with help of JetBrains team.
Round to 5 (or other number) in Python
Modified version of divround :-)
def divround(value, step, barrage):
result, rest = divmod(value, step)
return result*step if rest < barrage else (result+1)*step
How do I compile jrxml to get jasper?
**A full example of POM file**.
Command to Build All **Jrxml** to **Jasper File** in maven
If you used eclipse then right click on the project and Run as maven Build and add goals antrun:run@compile-jasper-reports
compile-jasper-reports is the id you gave in the pom file.
**<id>compile-jasper-reports</id>**
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.jasper</groupId>
<artifactId>testJasper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>TestJasper</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.3.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>compile-jasper-reports</id>
<goals>
<goal>run</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<target>
<echo message="Start compile of jasper reports" />
<mkdir dir="${project.build.directory}/classes/reports"/>
<echo message="${basedir}/src/main/resources/jasper/jasperreports" />
<taskdef name="jrc" classname="net.sf.jasperreports.ant.JRAntCompileTask"
classpathref="maven.compile.classpath" />
<jrc srcdir="${basedir}/src/main/resources/jasper/jasperreports" destdir="${basedir}/src/main/resources/jasper/jasperclassfile"
xmlvalidation="true">
<classpath refid="maven.compile.classpath"/>
<include name="**/*.jrxml" />
</jrc>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Correct way to delete cookies server-side
At the time of my writing this answer, the accepted answer to this question appears to state that browsers are not required to delete a cookie when receiving a replacement cookie whose Expires
value is in the past. That claim is false. Setting Expires
to be in the past is the standard, spec-compliant way of deleting a cookie, and user agents are required by spec to respect it.
Using an Expires
attribute in the past to delete a cookie is correct and is the way to remove cookies dictated by the spec. The examples section of RFC 6255 states:
Finally, to remove a cookie, the server returns a Set-Cookie header
with an expiration date in the past. The server will be successful
in removing the cookie only if the Path and the Domain attribute in
the Set-Cookie header match the values used when the cookie was
created.
The User Agent Requirements section includes the following requirements, which together have the effect that a cookie must be immediately expunged if the user agent receives a new cookie with the same name whose expiry date is in the past
If [when receiving a new cookie] the cookie store contains a cookie with the same name, domain, and path as the newly created cookie:
- ...
- ...
- Update the creation-time of the newly created cookie to match the creation-time of the old-cookie.
- Remove the old-cookie from the cookie store.
Insert the newly created cookie into the cookie store.
A cookie is "expired" if the cookie has an expiry date in the past.
The user agent MUST evict all expired cookies from the cookie store
if, at any time, an expired cookie exists in the cookie store.
Points 11-3, 11-4, and 12 above together mean that when a new cookie is received with the same name, domain, and path, the old cookie must be expunged and replaced with the new cookie. Finally, the point below about expired cookies further dictates that after that is done, the new cookie must also be immediately evicted. The spec offers no wiggle room to browsers on this point; if a browser were to offer the user the option to disable cookie expiration, as the accepted answer suggests some browsers do, then it would be in violation of the spec. (Such a feature would also have little use, and as far as I know it does not exist in any browser.)
Why, then, did the OP of this question observe this approach failing? Though I have not dusted off a copy of Internet Explorer to check its behaviour, I suspect it was because the OP's Expires
value was malformed! They used this value:
expires=Thu, Jan 01 1970 00:00:00 UTC;
However, this is syntactically invalid in two ways.
The syntax section of the spec dictates that the value of the Expires
attribute must be a
rfc1123-date, defined in [RFC2616], Section 3.3.1
Following the second link above, we find this given as an example of the format:
Sun, 06 Nov 1994 08:49:37 GMT
and find that the syntax definition...
requires that dates be written in day month year format, not month day year format as used by the question asker.
Specifically, it defines rfc1123-date
as follows:
rfc1123-date = wkday "," SP date1 SP time SP "GMT"
and defines date1
like this:
date1 = 2DIGIT SP month SP 4DIGIT
; day month year (e.g., 02 Jun 1982)
and
doesn't permit UTC
as a timezone.
The spec contains the following statement about what timezone offsets are acceptable in this format:
All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception.
What's more if we dig deeper into the original spec of this datetime format, we find that in its initial spec in https://tools.ietf.org/html/rfc822, the Syntax section lists "UT" (meaning "universal time") as a possible value, but does not list not UTC (Coordinated Universal Time) as valid. As far as I know, using "UTC" in this date format has never been valid; it wasn't a valid value when the format was first specified in 1982, and the HTTP spec has adopted a strictly more restrictive version of the format by banning the use of all "zone" values other than "GMT".
If the question asker here had instead used an Expires
attribute like this, then:
expires=Thu, 01 Jan 1970 00:00:00 GMT;
then it would presumably have worked.
No Persistence provider for EntityManager named
In my case it was about mistake in two properties as below. When I changed them ‘No Persistence provider for EntityManager named’ disappered.
So you could try test connection with your properties to check if everything is correct.
<property name="javax.persistence.jdbc.url" value="...”/>
<property name="javax.persistence.jdbc.password" value="...”/>
Strange error, I was totally confused because of it.
How do I select a random value from an enumeration?
Personally, I'm a fan of extension methods, so I would use something like this (while not really an extension, it looks similar):
public enum Options {
Zero,
One,
Two,
Three,
Four,
Five
}
public static class RandomEnum {
private static Random _Random = new Random(Environment.TickCount);
public static T Of<T>() {
if (!typeof(T).IsEnum)
throw new InvalidOperationException("Must use Enum type");
Array enumValues = Enum.GetValues(typeof(T));
return (T)enumValues.GetValue(_Random.Next(enumValues.Length));
}
}
[TestClass]
public class RandomTests {
[TestMethod]
public void TestMethod1() {
Options option;
for (int i = 0; i < 10; ++i) {
option = RandomEnum.Of<Options>();
Console.WriteLine(option);
}
}
}
How to get current working directory using vba?
I've tested this:
When I open an Excel document D:\db\tmp\test1.xlsm
:
So CurDir()
has a system default and can be changed.
ActiveWorkbook.Path
does not change for the same saved Workbook.
For example, CurDir()
changes when you do "File/Save As" command, and select a random directory in the File/Directory selection dialog. Then click on Cancel to skip saving. But CurDir()
has already changed to the last selected directory.
Confused about Service vs Factory
I had this confusion for a while and I'm trying my best to provide a simple explanation here. Hope this will help!
angular .factory
and angular .service
both are used to initialize a service and work in the same way.
The only difference is, how you want to initialize your service.
Both are Singletons
var app = angular.module('app', []);
Factory
app.factory(<service name>
, <function with a return value>
)
If you would like to initialize your service from a function that you have with a return value, you have to use this factory
method.
e.g.
function myService() {
//return what you want
var service = {
myfunc: function (param) { /* do stuff */ }
}
return service;
}
app.factory('myService', myService);
When injecting this service (e.g. to your controller):
- Angular will call your given function (as
myService()
) to return the object
- Singleton - called only once, stored, and pass the same object.
Service
app.service(<service name>
, <constructor function>
)
If you would like to initialize your service from a constructor function (using this
keyword), you have to use this service
method.
e.g.
function myService() {
this.myfunc: function (param) { /* do stuff */ }
}
app.service('myService', myService);
When injecting this service (e.g. to your controller):
- Angular will
new
ing your given function (as new myService()
) to return the object
- Singleton - called only once, stored, and pass the same object.
NOTE: If you use
factory
with
<constructor function>
or
service
with
<function with a return value>
, it will not work.
Examples - DEMOs
correct way of comparing string jquery operator =
NO, when you are using only one "=" you are assigning the variable.
You must use "==" : You must use "===" :
if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
$("#code").text(data.DATA[0].ID);
}
You could use fonction like .toLowerCase()
to avoid case problem if you want
Class has no member named
Did you remember to include the closing brace in main?
#include <iostream>
#include "Attack.h"
using namespace std;
int main()
{
Attack attackObj;
attackObj.printShiz();
}
How to position a Bootstrap popover?
Simply add an attribute to your popover! See my JSFiddle if you're in a hurry.
We want to add an ID or a class to a particular popover so that we may customize it the way we want via CSS.
Please note that we don't want to customize all popovers! This is terrible idea.
Here is a simple example - display the popover like this:
_x000D_
_x000D_
// We add the id 'my-popover'_x000D_
$("#my-button").popover({_x000D_
html : true,_x000D_
placement: 'bottom'_x000D_
}).data('bs.popover').tip().attr('id', 'my-popover');
_x000D_
#my-popover {_x000D_
left: -169px!important;_x000D_
}_x000D_
#my-popover .arrow {_x000D_
left: 90%_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button id="my-button" data-toggle="popover">My Button</button>
_x000D_
_x000D_
_x000D_
SQL RANK() over PARTITION on joined tables
SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID
using sql count in a case statement
Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.
For example, here's a simple table Grades
:
| Letters |
|---------|
| A |
| A |
| B |
| C |
We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):
SELECT
COUNT(CASE WHEN Letter = 'A' THEN 1 END) AS [Count - End],
COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END) AS [Count - Else Zero],
SUM(CASE WHEN Letter = 'A' THEN 1 END) AS [Sum - End],
SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Sum - Else Null],
SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END) AS [Sum - Else Zero]
FROM Grades
And here are the results (unpivoted for readability):
| Description | Counts |
|-------------------|--------|
| Count - End | 2 |
| Count - Else Null | 2 |
| Count - Else Zero | 4 | *Note: Will include count of zero values
| Sum - End | 2 |
| Sum - Else Null | 2 |
| Sum - Else Zero | 2 |
Which lines up with the docs for Aggregate Functions in SQL
Docs for COUNT
:
COUNT(*)
- returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression)
- evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression)
- evaluates expression for each row in a group, and returns the number of unique, nonnull values.
Docs for SUM
:
ALL
- Applies the aggregate function to all values. ALL is the default.
DISTINCT
- Specifies that SUM return the sum of unique values.
How to use mouseover and mouseout in Angular 6
Adding to what was already said.
if you want to *ngFor
an element , and hide \ show elements in it, on hover, like you added in the comments, you should re-think the whole concept.
a more appropriate way to do it, does not involve angular at all.
I would go with pure CSS instead, using its native :hover
property.
something like:
App.Component.css
div span.only-show-on-hover {
visibility: hidden;
}
div:hover span.only-show-on-hover {
visibility: visible;
}
App.Component.html
<div *ngFor="let i of [1,2,3,4]" > hover me please.
<span class="only-show-on-hover">you only see me when hovering</span>
</div>
added a demo: https://stackblitz.com/edit/hello-angular-6-hvgx7n?file=src%2Fapp%2Fapp.component.html
Laravel-5 'LIKE' equivalent (Eloquent)
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
How to pass parameter to click event in Jquery
As DOC says, you can pass data to the handler as next:
// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
// access element's id where click occur
alert( event.target.id );
}
Offline Speech Recognition In Android (JellyBean)
It is apparently possible to manually install offline voice recognition by downloading the files directly and installing them in the right locations manually. I guess this is just a way to bypass Google hardware requirements.
However, personally I didn't have to reboot or anything, simply changing to UK and back again did it.
Form content type for a json HTTP POST?
I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.
According to the spec, a POST of json data should have the content-type:
application/json
Relevant portion of the HTML spec
6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and
"audio/basic".
17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content
type must be encoded as follows
Relevant portion of the JSON spec
- IANA Considerations
The MIME media type for JSON text is application/json.
Executing a batch script on Windows shutdown
I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts.
PS: I found action for startup and logout user, there is not for shutdown.
Using Regular Expressions to Extract a Value in Java
if you are reading from file then this can help you
try{
InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
//Ref:03
while ((line = br.readLine()) != null) {
if (line.matches("[A-Z],\\d,(\\d*,){2}(\\s*\\d*\\|\\d*:)+")) {
String[] splitRecord = line.split(",");
//do something
}
else{
br.close();
//error
return;
}
}
br.close();
}
}
catch (IOException ioExpception){
logger.logDebug("Exception " + ioExpception.getStackTrace());
}
Get Element value with minidom with Python
Here is a slightly modified answer of Henrik's for multiple nodes (ie. when getElementsByTagName returns more than one instance)
images = xml.getElementsByTagName("imageUrl")
for i in images:
print " ".join(t.nodeValue for t in i.childNodes if t.nodeType == t.TEXT_NODE)
How to start an Intent by passing some parameters to it?
In order to pass the parameters you create new intent and put a parameter map:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);
In order to get the parameters values inside the started activity, you must call the get[type]Extra()
on the same intent:
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"
If your parameters are ints you would use getIntExtra()
instead etc.
Now you can use your parameters like you normally would.
C# Generics and Type Checking
You could use overloads:
public static string BuildClause(List<string> l){...}
public static string BuildClause(List<int> l){...}
public static string BuildClause<T>(List<T> l){...}
Or you could inspect the type of the generic parameter:
Type listType = typeof(T);
if(listType == typeof(int)){...}
How to enumerate an enum
Three ways:
Enum.GetValues(type)
// Since .NET 1.1, not in Silverlight or .NET Compact Framework
type.GetEnumValues()
// Only on .NET 4 and above
type.GetFields().Where(x => x.IsLiteral).Select(x => x.GetValue(null))
// Works everywhere
I am not sure why GetEnumValues
was introduced on type instances. It isn't very readable at all for me.
Having a helper class like Enum<T>
is what is most readable and memorable for me:
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
public static IEnumerable<T> GetValues()
{
return (T[])Enum.GetValues(typeof(T));
}
public static IEnumerable<string> GetNames()
{
return Enum.GetNames(typeof(T));
}
}
Now you call:
Enum<Suit>.GetValues();
// Or
Enum.GetValues(typeof(Suit)); // Pretty consistent style
One can also use some sort of caching if performance matters, but I don't expect this to be an issue at all.
public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
// Lazily loaded
static T[] values;
static string[] names;
public static IEnumerable<T> GetValues()
{
return values ?? (values = (T[])Enum.GetValues(typeof(T)));
}
public static IEnumerable<string> GetNames()
{
return names ?? (names = Enum.GetNames(typeof(T)));
}
}
Check if current directory is a Git repository
if ! [[ $(pwd) = *.git/* || $(pwd) = *.git ]]; then
if type -P git >/dev/null; then
! git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
printf '\n%s\n\n' "GIT repository detected." && git status
}
fi
fi
Thank you ivan_pozdeev, Now I have a test if inside the .git directory the code will not run so no errors printed out or false exit status.
The "! [[ $(pwd) = .git/ || $(pwd) = *.git ]]" tests if you're not inside a .git repo then it will run the git command. The builtin type command is use to check if you have git installed or it is within your PATH. see help type
Print DIV content by JQuery
You can follow these steps :
- wrap the div you want to print into another div.
- set the wrapper div display status to none in css.
- keep the div you want to print display status as block, anyway it will be hidden as its parent is hidden.
- simply call
$('SelectorToPrint').printElement();
Looping through all rows in a table column, Excel-VBA
You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:
Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
cl.Value = "PHEV"
Next cl
The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.
Use this to find the location of any column in a table by its column name:
Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column
This returns the numeric position of a column in the table.
How to convert numpy arrays to standard TensorFlow format?
You can use tf.pack (tf.stack in TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray
into a Tensor
:
import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
tf.InteractiveSession()
evaluated_tensor = random_image_tensor.eval()
UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensor function.
How do I use extern to share variables between source files?
A very short solution I use to allow a header file to contain the extern reference or actual implementation of an object. The file that actually contains the object just does #define GLOBAL_FOO_IMPLEMENTATION
. Then when I add a new object to this file it shows up in that file also without me having to copy and paste the definition.
I use this pattern across multiple files. So in order to keep things as self contained as possible, I just reuse the single GLOBAL macro in each header. My header looks like this:
//file foo_globals.h
#pragma once
#include "foo.h" //contains definition of foo
#ifdef GLOBAL
#undef GLOBAL
#endif
#ifdef GLOBAL_FOO_IMPLEMENTATION
#define GLOBAL
#else
#define GLOBAL extern
#endif
GLOBAL Foo foo1;
GLOBAL Foo foo2;
//file main.cpp
#define GLOBAL_FOO_IMPLEMENTATION
#include "foo_globals.h"
//file uses_extern_foo.cpp
#include "foo_globals.h
How to convert integer to string in C?
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
JavaFX How to set scene background image
You can change style directly for scene using .root
class:
.root {
-fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}
Add this to CSS and load it as "Uluk Biy" described in his answer.
Only detect click event on pseudo-element
Actually, it is possible. You can check if the clicked position was outside of the element, since this will only happen if ::before
or ::after
was clicked.
This example only checks the element to the right but that should work in your case.
_x000D_
_x000D_
span = document.querySelector('span');_x000D_
_x000D_
span.addEventListener('click', function (e) {_x000D_
if (e.offsetX > span.offsetWidth) {_x000D_
span.className = 'c2';_x000D_
} else {_x000D_
span.className = 'c1';_x000D_
}_x000D_
});
_x000D_
div { margin: 20px; }_x000D_
span:after { content: 'AFTER'; position: absolute; }_x000D_
_x000D_
span.c1 { background: yellow; }_x000D_
span.c2:after { background: yellow; }
_x000D_
<div><span>ELEMENT</span></div>
_x000D_
_x000D_
_x000D_
JSFiddle
Is SMTP based on TCP or UDP?
In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.
As defined in RFC 821, RFC 2821, and RFC 5321:
SMTP is independent of the particular transmission subsystem and
requires only a reliable ordered data stream channel.
In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.
In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.
The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.
Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.