Can an AJAX response set a cookie?
According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
Quotation:
If the user agent supports HTTP State Management it should persist,
discard and send cookies (as received in the Set-Cookie response
header, and sent in the Cookie header) as applicable.
How do you declare string constants in C?
There's one more (at least) road to Rome:
static const char HELLO3[] = "Howdy";
(static
— optional — is to prevent it from conflicting with other files). I'd prefer this one over const char*
, because then you'll be able to use sizeof(HELLO3)
and therefore you don't have to postpone till runtime what you can do at compile time.
The define has an advantage of compile-time concatenation, though (think HELLO ", World!"
) and you can sizeof(HELLO)
as well.
But then you can also prefer const char*
and use it across multiple files, which would save you a morsel of memory.
In short — it depends.
How to lazy load images in ListView in Android
Picasso
Use Jake Wharton's Picasso Library.
(A Perfect ImageLoading Library form the developer of ActionBarSherlock)
A powerful image downloading and caching library for Android.
Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Many common pitfalls of image loading on Android are handled automatically by Picasso:
Handling ImageView recycling and download cancellation in an adapter.
Complex image transformations with minimal memory use.
Automatic memory and disk caching.
Picasso Jake Wharton's Library
Glide
Glide is a fast and efficient open source media management framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface.
Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs. Glide includes a flexible api that allows developers to plug in to almost any network stack. By default Glide uses a custom HttpUrlConnection based stack, but also includes utility libraries plug in to Google's Volley project or Square's OkHttp library instead.
Glide.with(this).load("http://goo.gl/h8qOq7").into(imageView);
Glide's primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but Glide is also effective for almost any case where you need to fetch, resize, and display a remote image.
Glide Image Loading Library
Fresco by Facebook
Fresco is a powerful system for displaying images in Android applications.
Fresco takes care of image loading and display, so you don't have to. It will load images from the network, local storage, or local resources, and display a placeholder until the image has arrived. It has two levels of cache; one in memory and another in internal storage.
Fresco Github
In Android 4.x and lower, Fresco puts images in a special region of Android memory. This lets your application run faster - and suffer the dreaded OutOfMemoryError much less often.
Fresco Documentation
htaccess redirect if URL contains a certain string
If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.
To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :
RewriteEngine on
RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]
How do I measure a time interval in C?
Using the time.h library, try something like this:
long start_time, end_time, elapsed;
start_time = clock();
// Do something
end_time = clock();
elapsed = (end_time - start_time) / CLOCKS_PER_SEC * 1000;
Long Press in JavaScript?
For me it's work with that code (with jQuery):
var int = null,
fired = false;
var longclickFilm = function($t) {
$body.css('background', 'red');
},
clickFilm = function($t) {
$t = $t.clone(false, false);
var $to = $('footer > div:first');
$to.find('.empty').remove();
$t.appendTo($to);
},
touchStartFilm = function(event) {
event.preventDefault();
fired = false;
int = setTimeout(function($t) {
longclickFilm($t);
fired = true;
}, 2000, $(this)); // 2 sec for long click ?
return false;
},
touchEndFilm = function(event) {
event.preventDefault();
clearTimeout(int);
if (fired) return false;
else clickFilm($(this));
return false;
};
$('ul#thelist .thumbBox')
.live('mousedown touchstart', touchStartFilm)
.live('mouseup touchend touchcancel', touchEndFilm);
Disable EditText blinking cursor
You can use following code for enabling and disabling edit text cursor by programmatically.
To Enable cursor
editText.requestFocus();
editText.setCursorVisible(true);
To Disable cursor
editText.setCursorVisible(false);
Using XML enable disable cursor
android:cursorVisible="false/true"
android:focusable="false/true"
To make edit_text Selectable to (copy/cut/paste/select/select all)
editText.setTextIsSelectable(true);
To focus on touch mode write following lines in XML
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="true"
programmatically
editText.requestFocusFromTouch();
To clear focus on touch mode
editText.clearFocus()
How to enable named/bind/DNS full logging?
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
How to select option in drop down protractorjs e2e tests
static selectDropdownValue(dropDownLocator,dropDownListLocator,dropDownValue){
let ListVal ='';
WebLibraryUtils.getElement('xpath',dropDownLocator).click()
WebLibraryUtils.getElements('xpath',dropDownListLocator).then(function(selectItem){
if(selectItem.length>0)
{
for( let i =0;i<=selectItem.length;i++)
{
if(selectItem[i]==dropDownValue)
{
console.log(selectItem[i])
selectItem[i].click();
}
}
}
})
}
No log4j2 configuration file found. Using default configuration: logging only errors to the console
I am getting this error because log4j2 file got deleted from my src folder
Simply add xml file under src folder
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
</Console>
<RollingFile name="RollingFile" filename="logs/B2CATA-hybrid.log"
filepattern="${logPath}/%d{yyyyMMddHHmmss}-fargo.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
<Policies>
<SizeBasedTriggeringPolicy size="100 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.pragiti." level="trace" />
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
What is an "index out of range" exception, and how do I fix it?
Why does this error occur?
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
How indexing arrays works
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
How other collections work
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
Excel "External table is not in the expected format."
My scope consists of template download and verifies the template when it's filled with data
So,
1) Download a template (.xlsx) file with the header row. the file is generated using openxml and it's working perfectly.
2) Upload the same file without any change from it's downloaded state. This will cause a connection error and fails (OLEDB connection is using for reading the excel sheet).
Here if the data is filled the program works as expected.
Anybody having an idea the issue is connected with the file we are creating it's in xml format if we open it and just save convert it in to excel format and it works well.
Any idea to download the excel with the preferred file type?
How to return JSon object
First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
Furthermore, classes conventionally are PascalCased
and not camelCased
.
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
Efficiently test if a port is open on Linux?
I wanted to check if a port is open on one of our linux test servers.
I was able to do that by trying to connect with telnet from my dev machine to the test server. On you dev machine try to run:
$ telnet test2.host.com 8080
Trying 05.066.137.184...
Connected to test2.host.com
In this example I want to check if port 8080 is open on host test2.host.com
How do I call a function twice or more times consecutively?
I would:
for _ in range(3):
do()
The _
is convention for a variable whose value you don't care about.
You might also see some people write:
[do() for _ in range(3)]
however that is slightly more expensive because it creates a list containing the return values of each invocation of do()
(even if it's None
), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.
Client to send SOAP request and receive response
Call SOAP webservice in c#
using (var client = new UpdatedOutlookServiceReferenceAPI.OutlookServiceSoapClient("OutlookServiceSoap"))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
var result = client.UploadAttachmentBase64(GUID, FinalFileName, fileURL);
if (result == true)
{
resultFlag = true;
}
else
{
resultFlag = false;
}
LogWriter.LogWrite1("resultFlag : " + resultFlag);
}
Linking a qtDesigner .ui file to python/pyqt?
You can convert your .ui files to an executable python file using the below command..
pyuic4 -x form1.ui > form1.py
Now you can straightaway execute the python file as
python3(whatever version) form1.py
You can import this file and you can use it.
CSS customized scroll bar in div
I think you have to use ::-wekbit-scrollbar
for all the scrollbars, and you can use:
<style>
.mydiv {
height:100px;
overflow:auto;
}
/* width */
.mydiv::-webkit-scrollbar {
width: 20px;
}
/* Track */
.mydiv::-webkit-scrollbar-track {
box-shadow: inset 0 0 5px grey;
border-radius: 10px;
}
/* Handle */
.mydiv::-webkit-scrollbar-thumb {
background: red;
border-radius: 10px;
}
/* Handle on hover */
.mydiv::-webkit-scrollbar-thumb:hover {
background: #b30000;
}
</style>
<body>
<div class="mydiv"> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> </div>
</body>
remove table row with specific id
ID attributes cannot start with a number and they should be unique. In any case, you can use :eq()
to select a specific row using a 0-based integer:
// Remove the third row
$("#test tr:eq(2)").remove();
Alternatively, rewrite your HTML so that it's valid:
<table id="test">
<tr id=test1><td>bla</td></tr>
<tr id=test2><td>bla</td></tr>
<tr id=test3><td>bla</td></tr>
<tr id=test4><td>bla</td></tr>
</table>
And remove it referencing just the id:
$("#test3").remove();
Interpreting segfault messages
Error 4 means "The cause was a user-mode read resulting in no page being found.". There's a tool that decodes it here.
Here's the definition from the kernel. Keep in mind that 4 means that bit 2 is set and no other bits are set. If you convert it to binary that becomes clear.
/*
* Page fault error code bits
* bit 0 == 0 means no page found, 1 means protection fault
* bit 1 == 0 means read, 1 means write
* bit 2 == 0 means kernel, 1 means user-mode
* bit 3 == 1 means use of reserved bit detected
* bit 4 == 1 means fault was an instruction fetch
*/
#define PF_PROT (1<<0)
#define PF_WRITE (1<<1)
#define PF_USER (1<<2)
#define PF_RSVD (1<<3)
#define PF_INSTR (1<<4)
Now then, "ip 00007f9bebcca90d" means the instruction pointer was at 0x00007f9bebcca90d when the segfault happened.
"libQtWebKit.so.4.5.2[7f9beb83a000+f6f000]" tells you:
- The object the crash was in: "libQtWebKit.so.4.5.2"
- The base address of that object "7f9beb83a000"
- How big that object is: "f6f000"
If you take the base address and subtract it from the ip, you get the offset into that object:
0x00007f9bebcca90d - 0x7f9beb83a000 = 0x49090D
Then you can run addr2line on it:
addr2line -e /usr/lib64/qt45/lib/libQtWebKit.so.4.5.2 -fCi 0x49090D
??
??:0
In my case it wasn't successful, either the copy I installed isn't identical to yours, or it's stripped.
Number of visitors on a specific page
As Blexy already answered, go to "Behavior > Site Content > All Pages".
Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:
Printing Batch file results to a text file
Step 1: Simply put all the required code in a "MAIN.BAT" file.
Step 2: Create another bat file, say MainCaller.bat, and just copy/paste these 3 lines of code:
REM THE MAIN FILE WILL BE CALLED FROM HERE..........
CD "File_Path_Where_Main.bat_is_located"
MAIN.BAT > log.txt
Step 3: Just double click "MainCaller.bat".
All the output will be logged into the text file named "log".
Running two projects at once in Visual Studio
Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.
This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).
How to terminate script execution when debugging in Google Chrome?
There are many appropiate solution to this problem as mentioned above in this post, but i have found a small hack that can be inserrted in the script or pasted in the Chromes console (debugger) to achieve it:
jQuery(window).keydown(function(e) { if (e.keyCode == 123) debugger; });
This will cause execution to be paused when you hit F12
.
Visual Studio breakpoints not being hit
If anyone is using Visual Studio 2017 and IIS and is trying to debug a web site project, the following worked for me:
- Attach the web site project to IIS.
- Add it to the solution with File -> Add -> Existing Web Site... and select the project from the
inetpub/wwwroot
directory.
- Right-click on the web site project in the solution explorer and select Property Pages -> Start Options
- Click on Specific Page and select the startup page (For service use Service.svc, for web site use Default.aspx or the custom name for the page you selected).
- Click on Use custom server and write
http(s)://localhost/(web site name as appears in IIS)
for example: http://localhost/MyWebSite
That's it! Don't forget to make sure the web site is running on the IIS and that the web site you wish to debug is selected as the startup project (Right-click -> Set as StartUp Project).
Original post: How to Debug Your ASP.NET Projects Running Under IIS
How to use the pass statement?
Honestly, I think the official Python docs describe it quite well and provide some examples:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
... pass
...
Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:
>>> def initlog(*args):
... pass # Remember to implement this!
...
how to execute php code within javascript
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">
.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head>
tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Grouping functions (tapply, by, aggregate) and the *apply family
R has many *apply functions which are ably described in the help files (e.g. ?apply
). There are enough of them, though, that beginning useRs may have difficulty deciding which one is appropriate for their situation or even remembering them all. They may have a general sense that "I should be using an *apply function here", but it can be tough to keep them all straight at first.
Despite the fact (noted in other answers) that much of the functionality of the *apply family is covered by the extremely popular plyr
package, the base functions remain useful and worth knowing.
This answer is intended to act as a sort of signpost for new useRs to help direct them to the correct *apply function for their particular problem. Note, this is not intended to simply regurgitate or replace the R documentation! The hope is that this answer helps you to decide which *apply function suits your situation and then it is up to you to research it further. With one exception, performance differences will not be addressed.
apply - When you want to apply a function to the rows or columns
of a matrix (and higher-dimensional analogues); not generally advisable for data frames as it will coerce to a matrix first.
# Two dimensional matrix
M <- matrix(seq(1,16), 4, 4)
# apply min to rows
apply(M, 1, min)
[1] 1 2 3 4
# apply max to columns
apply(M, 2, max)
[1] 4 8 12 16
# 3 dimensional array
M <- array( seq(32), dim = c(4,4,2))
# Apply sum across each M[*, , ] - i.e Sum across 2nd and 3rd dimension
apply(M, 1, sum)
# Result is one-dimensional
[1] 120 128 136 144
# Apply sum across each M[*, *, ] - i.e Sum across 3rd dimension
apply(M, c(1,2), sum)
# Result is two-dimensional
[,1] [,2] [,3] [,4]
[1,] 18 26 34 42
[2,] 20 28 36 44
[3,] 22 30 38 46
[4,] 24 32 40 48
If you want row/column means or sums for a 2D matrix, be sure to
investigate the highly optimized, lightning-quick colMeans
,
rowMeans
, colSums
, rowSums
.
lapply - When you want to apply a function to each element of a
list in turn and get a list back.
This is the workhorse of many of the other *apply functions. Peel
back their code and you will often find lapply
underneath.
x <- list(a = 1, b = 1:3, c = 10:100)
lapply(x, FUN = length)
$a
[1] 1
$b
[1] 3
$c
[1] 91
lapply(x, FUN = sum)
$a
[1] 1
$b
[1] 6
$c
[1] 5005
sapply - When you want to apply a function to each element of a
list in turn, but you want a vector back, rather than a list.
If you find yourself typing unlist(lapply(...))
, stop and consider
sapply
.
x <- list(a = 1, b = 1:3, c = 10:100)
# Compare with above; a named vector, not a list
sapply(x, FUN = length)
a b c
1 3 91
sapply(x, FUN = sum)
a b c
1 6 5005
In more advanced uses of sapply
it will attempt to coerce the
result to a multi-dimensional array, if appropriate. For example, if our function returns vectors of the same length, sapply
will use them as columns of a matrix:
sapply(1:5,function(x) rnorm(3,x))
If our function returns a 2 dimensional matrix, sapply
will do essentially the same thing, treating each returned matrix as a single long vector:
sapply(1:5,function(x) matrix(x,2,2))
Unless we specify simplify = "array"
, in which case it will use the individual matrices to build a multi-dimensional array:
sapply(1:5,function(x) matrix(x,2,2), simplify = "array")
Each of these behaviors is of course contingent on our function returning vectors or matrices of the same length or dimension.
vapply - When you want to use sapply
but perhaps need to
squeeze some more speed out of your code.
For vapply
, you basically give R an example of what sort of thing
your function will return, which can save some time coercing returned
values to fit in a single atomic vector.
x <- list(a = 1, b = 1:3, c = 10:100)
#Note that since the advantage here is mainly speed, this
# example is only for illustration. We're telling R that
# everything returned by length() should be an integer of
# length 1.
vapply(x, FUN = length, FUN.VALUE = 0L)
a b c
1 3 91
mapply - For when you have several data structures (e.g.
vectors, lists) and you want to apply a function to the 1st elements
of each, and then the 2nd elements of each, etc., coercing the result
to a vector/array as in sapply
.
This is multivariate in the sense that your function must accept
multiple arguments.
#Sums the 1st elements, the 2nd elements, etc.
mapply(sum, 1:5, 1:5, 1:5)
[1] 3 6 9 12 15
#To do rep(1,4), rep(2,3), etc.
mapply(rep, 1:4, 4:1)
[[1]]
[1] 1 1 1 1
[[2]]
[1] 2 2 2
[[3]]
[1] 3 3
[[4]]
[1] 4
Map - A wrapper to mapply
with SIMPLIFY = FALSE
, so it is guaranteed to return a list.
Map(sum, 1:5, 1:5, 1:5)
[[1]]
[1] 3
[[2]]
[1] 6
[[3]]
[1] 9
[[4]]
[1] 12
[[5]]
[1] 15
rapply - For when you want to apply a function to each element of a nested list structure, recursively.
To give you some idea of how uncommon rapply
is, I forgot about it when first posting this answer! Obviously, I'm sure many people use it, but YMMV. rapply
is best illustrated with a user-defined function to apply:
# Append ! to string, otherwise increment
myFun <- function(x){
if(is.character(x)){
return(paste(x,"!",sep=""))
}
else{
return(x + 1)
}
}
#A nested list structure
l <- list(a = list(a1 = "Boo", b1 = 2, c1 = "Eeek"),
b = 3, c = "Yikes",
d = list(a2 = 1, b2 = list(a3 = "Hey", b3 = 5)))
# Result is named vector, coerced to character
rapply(l, myFun)
# Result is a nested list like l, with values altered
rapply(l, myFun, how="replace")
tapply - For when you want to apply a function to subsets of a
vector and the subsets are defined by some other vector, usually a
factor.
The black sheep of the *apply family, of sorts. The help file's use of
the phrase "ragged array" can be a bit confusing, but it is actually
quite simple.
A vector:
x <- 1:20
A factor (of the same length!) defining groups:
y <- factor(rep(letters[1:5], each = 4))
Add up the values in x
within each subgroup defined by y
:
tapply(x, y, sum)
a b c d e
10 26 42 58 74
More complex examples can be handled where the subgroups are defined
by the unique combinations of a list of several factors. tapply
is
similar in spirit to the split-apply-combine functions that are
common in R (aggregate
, by
, ave
, ddply
, etc.) Hence its
black sheep status.
<strong> vs. font-weight:bold & <em> vs. font-style:italic
The <em>
element - from W3C (HTML5 reference)
YES! There is a clear difference.
The <em>
element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em>
elements.
<strong> = important content
<em> = stress emphasis of its contents
The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.
Note!
The <em>
element also isnt intended to convey importance; for that
purpose, the <strong>
element is more appropriate.
The <em>
element isn't a generic "italics" element. Sometimes, text
is intended to stand out from the rest of the paragraph, as if it was
in a different mood or voice. For this, the i
element is more
appropriate.
Reference (examples): See W3C Reference
How to hide collapsible Bootstrap 4 navbar on click
You can add the collapse
component to the links like this..
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#home" data-toggle="collapse" data-target=".navbar-collapse.show">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#pricing" data-toggle="collapse" data-target=".navbar-collapse.show">Pricing</a>
</li>
</ul>
BS3 demo using 'data-toggle' method
Or, (perhaps a better way) use jQuery like this..
$('.navbar-nav>li>a').on('click', function(){
$('.navbar-collapse').collapse('hide');
});
BS3 demo using jQuery method
Update 2019 - Bootstrap 4
The navbar has changed, but the "close after click" method is still the same:
BS4 demo jQuery method
BS4 demo data-toggle
method
Update 2021 - Bootstrap 5 (beta)
Use javascript to add a click event listener on the menu items to close the Collapse navbar..
const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
l.addEventListener('click', () => { bsCollapse.toggle() })
})
BS5 demo javascript method
Or, Use the data-bs-toggle
and data-bs-target
data attributes in the markup on each link to toggle the Collapse navbar...
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto">
<li class="nav-item active">
<a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Disabled</a>
</li>
</ul>
<form class="d-flex my-2 my-lg-0">
<input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</div>
</nav>
BS5 demo data-attributes method
How can I pass arguments to anonymous functions in JavaScript?
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).
You could do this however:
<input type="button" value="Click me" id="myButton"/>
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
var myDelegate = function(message) {
alert(message);
}
myButton.onclick = function() {
myDelegate(myMessage);
};
</script>
How to add checkboxes to JTABLE swing
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function
I solved in this way:
I logged in with root username
mysql -u root -p -h localhost
I created a new user with
CREATE USER 'francesco'@'localhost' IDENTIFIED BY 'some_pass';
then I created the database
CREATE DATABASE shop;
I granted privileges for new user for this database
GRANT ALL PRIVILEGES ON shop.* TO 'francesco'@'localhost';
Then I logged out root and logged in new user
quit;
mysql -u francesco -p -h localhost
I rebuilt my database using a script
source shop.sql;
And that's it.. Now from php works without problems with the call
$conn = new mysqli("localhost", "francesco", "some_pass", "shop");
Thanks to all for your time :)
Javascript use variable as object name
Global:
myObject = { value: 0 };
anObjectName = "myObject";
this[anObjectName].value++;
console.log(this[anObjectName]);
Global: v2
var anObjectName = "myObject";
this[anObjectName] = "myvalue"
console.log(myObject)
Local: v1
(function() {
var scope = this;
if (scope != arguments.callee) {
arguments.callee.call(arguments.callee);
return false;
}
scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;
console.log(scope.myObject.value);
})();
Local: v2
(function() {
var scope = this;
scope.myObject = { value: 0 };
scope.anObjectName = "myObject";
scope[scope.anObjectName].value++;
console.log(scope.myObject.value);
}).call({});
Python function as a function argument?
Here's another way using *args
(and also optionally), **kwargs
:
def a(x, y):
print x, y
def b(other, function, *args, **kwargs):
function(*args, **kwargs)
print other
b('world', a, 'hello', 'dude')
Output
hello dude
world
Note that function
, *args
, **kwargs
have to be in that order and have to be the last arguments to the function calling the function.
How can I force gradle to redownload dependencies?
In my case none of the above worked, what I did was:
- In
build.gradle
, commenting the dependencies related to the unresolved imports I had
- Clicking "Sync Now"
- Uncommenting what I just commented
- Clicking "Sync Now" again
Then my imports were properly resolved again.
Update TextView Every Second
If you want to show time on textview then better use Chronometer or TextClock
Using Chronometer:This was added in API 1. It has lot of option to customize it.
Your xml
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
Your activity
Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.
Your xml
<TextClock
android:id="@+id/textClock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:format12Hour="hh:mm:ss a"
android:gravity="center_horizontal"
android:textColor="#d41709"
android:textSize="44sp"
android:textStyle="bold" />
Thats it, you are done.
You can use any of these two widgets. This will make your life easy.
How to override maven property in command line?
See Introduction to the POM
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
MySQL Data Source not appearing in Visual Studio
I have faced the same problem and i have installed mysql-connector-net-8.0.11. But in visual studio is not showing the db connector for mysql. Then I was installed the mysql-for-visualstudio-1.2.8 and run the visual studio. Its working fine.
Thank you!
Pandas: rolling mean by time interval
visualize the rolling averages to see if it makes sense. I don't understand why sum was used when the rolling average was requested.
df=pd.read_csv('poll.csv',parse_dates=['enddate'],dtype={'favorable':np.float,'unfavorable':np.float,'other':np.float})
df.set_index('enddate')
df=df.fillna(0)
fig, axs = plt.subplots(figsize=(5,10))
df.plot(x='enddate', ax=axs)
plt.show()
df.rolling(window=3,min_periods=3).mean().plot()
plt.show()
print("The larger the window coefficient the smoother the line will appear")
print('The min_periods is the minimum number of observations in the window required to have a value')
df.rolling(window=6,min_periods=3).mean().plot()
plt.show()
CASE IN statement with multiple values
You can return the same value from several matches:
SELECT
CASE c.Number
WHEN '1121231' THEN 1
WHEN '31242323' THEN 1
WHEN '234523' THEN 2
WHEN '2342423' THEN 2
END AS Test
FROM tblClient c
This will probably result in the same execution plan as Martins suggestion, so it's more a matter of how you want to write it.
Setting "checked" for a checkbox with jQuery
Here's the complete answer
using jQuery
I test it and it works 100% :D
// when the button (select_unit_button) is clicked it returns all the checed checkboxes values
$("#select_unit_button").on("click", function(e){
var arr = [];
$(':checkbox:checked').each(function(i){
arr[i] = $(this).val(); // u can get id or anything else
});
//console.log(arr); // u can test it using this in google chrome
});
Load JSON text into class object in c#
First create a class to represent your json data.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Or Use JavaScriptSerializer
to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
Assuming you want to convert it to a Customer
classe's instance. Your class should looks similar to the JSON
structure (Properties)
Redirect non-www to www in .htaccess
If possible, add this to the main Apache configuration file. It is a lighter-weight solution, less processing required.
<VirtualHost 64.65.66.67>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost 64.65.66.67>
ServerAdmin [email protected]
ServerName www.example.com
DocumentRoot /var/www/example
.
.
. etc
So, the separate VirtualHost
for "example.com" captures those requests and then permanently redirects them to your main VirtualHost
. So there's no REGEX parsing with every request, and your client browsers will cache the redirect so they'll never (or rarely) request the "wrong" url again, saving you on server load.
Note, the trailing slash in Redirect permanent / http://www.example.com/
.
Without it, a redirect from example.com/asdf
would redirect to http://www.example.comasdf
instead of http://www.example.com/asdf
.
Ansible: Store command's stdout in new variable?
A slight modification beyond @udondan's answer. I like to reuse the registered variable names with the set_fact
to help keep the clutter to a minimum.
So if I were to register using the variable, psk
, I'd use that same variable name with creating the set_fact
.
Example
- name: generate PSK
shell: openssl rand -base64 48
register: psk
delegate_to: 127.0.0.1
run_once: true
- set_fact:
psk={{ psk.stdout }}
- debug: var=psk
run_once: true
Then when I run it:
$ ansible-playbook -i inventory setup_ipsec.yml
PLAY [all] *************************************************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************************
ok: [hostc.mydom.com]
ok: [hostb.mydom.com]
ok: [hosta.mydom.com]
TASK [libreswan : generate PSK] ****************************************************************************************************************************************************
changed: [hosta.mydom.com -> 127.0.0.1]
TASK [libreswan : set_fact] ********************************************************************************************************************************************************
ok: [hosta.mydom.com]
ok: [hostb.mydom.com]
ok: [hostc.mydom.com]
TASK [libreswan : debug] ***********************************************************************************************************************************************************
ok: [hosta.mydom.com] => {
"psk": "6Tx/4CPBa1xmQ9A6yKi7ifONgoYAXfbo50WXPc1kGcird7u/pVso/vQtz+WdBIvo"
}
PLAY RECAP *************************************************************************************************************************************************************************
hosta.mydom.com : ok=4 changed=1 unreachable=0 failed=0
hostb.mydom.com : ok=2 changed=0 unreachable=0 failed=0
hostc.mydom.com : ok=2 changed=0 unreachable=0 failed=0
Sample random rows in dataframe
EDIT: This answer is now outdated, see the updated version.
In my R package I have enhanced sample
so that it now behaves as expected also for data frames:
library(devtools); install_github('kimisc', 'krlmlr')
library(kimisc)
example(sample.data.frame)
smpl..> set.seed(42)
smpl..> sample(data.frame(a=c(1,2,3), b=c(4,5,6),
row.names=c('a', 'b', 'c')), 10, replace=TRUE)
a b
c 3 6
c.1 3 6
a 1 4
c.2 3 6
b 2 5
b.1 2 5
c.3 3 6
a.1 1 4
b.2 2 5
c.4 3 6
This is achieved by making sample
an S3 generic method and providing the necessary (trivial) functionality in a function. A call to setMethod
fixes everything. The original implementation still can be accessed through base::sample
.
Convert Date/Time for given Timezone - java
I have try this code
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss Z");
Date datetime = new Date();
System.out.println("date "+sdf.format(datetime));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT "+ sdf.format(datetime));
sdf.setTimeZone(TimeZone.getTimeZone("GMT+13"));
System.out.println("GMT+13 "+ sdf.format(datetime));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("utc "+sdf.format(datetime));
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));
String newZealandTime = formatter.format(calendar.getTime());
System.out.println("using calendar "+newZealandTime);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and getting this result
date 06-10-2011 10:40:05 +0530
GMT 06-10-2011 05:10:05 +0000 // here getting 5:10:05
GMT+13 06-10-2011 06:10:05 +1300 // here getting 6:10:05
utc 06-10-2011 05:10:05 +0000
using calendar 06 Oct 2011 18:10:05 GMT+13:00
how to delete all cookies of my website in php
$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
setcookie( $key, $value, $past, '/' );
}
Even better is however to remember (or store it somewhere) which cookies are set with your application on a domain and delete all those directly.
That way you can be sure to delete all values correctly.
Multiple modals overlay
Unfortunately I do not have the reputation to comment, but it should be noted that the accepted solution with the hardcoded baseline of a 1040 z-index seems to be superior to the zIndex calculation that tries to find the maximum zIndex being rendered on the page.
It appears that certain extensions/plugins rely on top level DOM content which makes the .Max calculation such an obscenely large number, that it can't increment the zIndex any further. This results in a modal where the overlay appears over the modal incorrectly (if you use Firebug/Google Inspector tools you'll see a zIndex on the order of 2^n - 1)
I haven't been able to isolate what the specific reason the various forms of Math.Max for z-Index leads to this scenario, but it can happen, and it will appear unique to a few users. (My general tests on browserstack had this code working perfectly).
Hope this helps someone.
Can JavaScript connect with MySQL?
YES? Have a look a meteor. Links:
http://meteor.com/screencast and http://net.tutsplus.com/tutorials/javascript-ajax/whats-this-meteor-thing/
I don't understand how it is done. But Nettuts+ put this thing in the javascript-ajax section, maybe magic happens.
It also shows some way to connect and insert to MongoDB with JS, like this:
Products.insert({Name : "Hammer", Price : 4.50, InStock : true});
Products.insert({Name : "Wrench", Price : 2.70, InStock : true});
Products.insert({Name : "Screw Driver", Price : 3.00, InStock : false});
Products.insert({Name : "Drill", Price : 5.25, InStock : true});
How can I sort an ArrayList of Strings in Java?
You can use TreeSet
that automatically order list values:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet <String>tree = new TreeSet<String>();
tree.add("aaa");
tree.add("acbbb");
tree.add("aab");
tree.add("c");
tree.add("a");
Iterator iterator;
iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
}
}
I lastly add 'a' but last element must be 'c'.
Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"
Your not applying Date formator. rather you are just parsing the date. to get output in this format
yyyy-MM-dd HH:mm:ss.SSSSSS
we have to use format() method here is full example:-
Here is full example:-
it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS
and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");
System.out.println(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(temp);
System.out.println(strDateOutput);
}
}
Media Queries: How to target desktop, tablet, and mobile?
It's not a matter of pixels count, it's a matter of actual size (in mm or inches) of characters on the screen, which depends on pixels density.
Hence "min-width:" and "max-width:" are useless.
A full explanation of this issue is here:
what exactly is device pixel ratio?
"@media" queries take into account the pixels count and the device pixel ratio, resulting in a "virtual resolution" which is what you have to actually take into account while designing your page: if your font is 10px fixed-width and the "virtual horizontal resolution" is 300 px, 30 characters will be needed to fill a line.
Propagation Delay vs Transmission delay
Because they're measuring different things.
Propagation delay is how long it takes one bit to travel from one end of the "wire" to the other (it's proportional to the length of the wire, crudely).
Transmission delay is how long it takes to get all the bits into the wire in the first place (it's packet_length/data_rate).
Accessing a resource via codebehind in WPF
If you want to access a resource from some other class (i.g. not a xaml codebehind), you can use
Application.Current.Resources["resourceName"];
from System.Windows
namespace.
GET URL parameter in PHP
The accepted answer is good. But if you have a scenario like this:
http://www.mydomain.me/index.php?state=California.php#Berkeley
You can treat the named anchor as a query string like this:
http://www.mydomain.me/index.php?state=California.php&city=Berkeley
Then, access it like this:
$Url = $_GET['state']."#".$_GET['city'];
In PANDAS, how to get the index of a known value?
I think this may help you , both index and columns of the values.
value you are looking for is not duplicated:
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()
you can get its index and column
duplicated:
matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]:
f h
q 1 1.0
g 1 NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]
you will get a list
ASP.NET Identity DbContext confusion
There is a lot of confusion about IdentityDbContext, a quick search in Stackoverflow and you'll find these questions:
"
Why is Asp.Net Identity IdentityDbContext a Black-Box?
How can I change the table names when using Visual Studio 2013 AspNet Identity?
Merge MyDbContext with IdentityDbContext"
To answer to all of these questions we need to understand that IdentityDbContext is just a class inherited from DbContext.
Let's take a look at IdentityDbContext source:
/// <summary>
/// Base class for the Entity Framework database context used for identity.
/// </summary>
/// <typeparam name="TUser">The type of user objects.</typeparam>
/// <typeparam name="TRole">The type of role objects.</typeparam>
/// <typeparam name="TKey">The type of the primary key for users and roles.</typeparam>
/// <typeparam name="TUserClaim">The type of the user claim object.</typeparam>
/// <typeparam name="TUserRole">The type of the user role object.</typeparam>
/// <typeparam name="TUserLogin">The type of the user login object.</typeparam>
/// <typeparam name="TRoleClaim">The type of the role claim object.</typeparam>
/// <typeparam name="TUserToken">The type of the user token object.</typeparam>
public abstract class IdentityDbContext<TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken> : DbContext
where TUser : IdentityUser<TKey, TUserClaim, TUserRole, TUserLogin>
where TRole : IdentityRole<TKey, TUserRole, TRoleClaim>
where TKey : IEquatable<TKey>
where TUserClaim : IdentityUserClaim<TKey>
where TUserRole : IdentityUserRole<TKey>
where TUserLogin : IdentityUserLogin<TKey>
where TRoleClaim : IdentityRoleClaim<TKey>
where TUserToken : IdentityUserToken<TKey>
{
/// <summary>
/// Initializes a new instance of <see cref="IdentityDbContext"/>.
/// </summary>
/// <param name="options">The options to be used by a <see cref="DbContext"/>.</param>
public IdentityDbContext(DbContextOptions options) : base(options)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="IdentityDbContext" /> class.
/// </summary>
protected IdentityDbContext()
{ }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of Users.
/// </summary>
public DbSet<TUser> Users { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User claims.
/// </summary>
public DbSet<TUserClaim> UserClaims { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User logins.
/// </summary>
public DbSet<TUserLogin> UserLogins { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User roles.
/// </summary>
public DbSet<TUserRole> UserRoles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User tokens.
/// </summary>
public DbSet<TUserToken> UserTokens { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of roles.
/// </summary>
public DbSet<TRole> Roles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of role claims.
/// </summary>
public DbSet<TRoleClaim> RoleClaims { get; set; }
/// <summary>
/// Configures the schema needed for the identity framework.
/// </summary>
/// <param name="builder">
/// The builder being used to construct the model for this context.
/// </param>
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>(b =>
{
b.HasKey(u => u.Id);
b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique();
b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex");
b.ToTable("AspNetUsers");
b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.UserName).HasMaxLength(256);
b.Property(u => u.NormalizedUserName).HasMaxLength(256);
b.Property(u => u.Email).HasMaxLength(256);
b.Property(u => u.NormalizedEmail).HasMaxLength(256);
b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
});
builder.Entity<TRole>(b =>
{
b.HasKey(r => r.Id);
b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.Name).HasMaxLength(256);
b.Property(u => u.NormalizedName).HasMaxLength(256);
b.HasMany(r => r.Users).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
});
builder.Entity<TUserClaim>(b =>
{
b.HasKey(uc => uc.Id);
b.ToTable("AspNetUserClaims");
});
builder.Entity<TRoleClaim>(b =>
{
b.HasKey(rc => rc.Id);
b.ToTable("AspNetRoleClaims");
});
builder.Entity<TUserRole>(b =>
{
b.HasKey(r => new { r.UserId, r.RoleId });
b.ToTable("AspNetUserRoles");
});
builder.Entity<TUserLogin>(b =>
{
b.HasKey(l => new { l.LoginProvider, l.ProviderKey });
b.ToTable("AspNetUserLogins");
});
builder.Entity<TUserToken>(b =>
{
b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name });
b.ToTable("AspNetUserTokens");
});
}
}
Based on the source code if we want to merge IdentityDbContext with our DbContext we have two options:
First Option:
Create a DbContext which inherits from IdentityDbContext and have access to the classes.
public class ApplicationDbContext
: IdentityDbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// Add additional items here as needed
}
Extra Notes:
1) We can also change asp.net Identity default table names with the following solution:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(): base("DefaultConnection")
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("user");
modelBuilder.Entity<ApplicationUser>().ToTable("user");
modelBuilder.Entity<IdentityRole>().ToTable("role");
modelBuilder.Entity<IdentityUserRole>().ToTable("userrole");
modelBuilder.Entity<IdentityUserClaim>().ToTable("userclaim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("userlogin");
}
}
2) Furthermore we can extend each class and add any property to classes like 'IdentityUser', 'IdentityRole', ...
public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
public ApplicationRole()
{
this.Id = Guid.NewGuid().ToString();
}
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
// Add any custom Role properties/code here
}
// Must be expressed in terms of our custom types:
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole,
string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// Add additional items here as needed
}
To save time we can use AspNet Identity 2.0 Extensible Project Template to extend all the classes.
Second Option:(Not recommended)
We actually don't have to inherit from IdentityDbContext if we write all the code ourselves.
So basically we can just inherit from DbContext and implement our customized version of "OnModelCreating(ModelBuilder builder)" from the IdentityDbContext source code
XAMPP installation on Win 8.1 with UAC Warning
I don't know if you are still having this problem, but I had the same problem and had a different fix than what was listed in the other answer. I did install XAMPP under C:\xampp\, and my user is an admin, but there was also something else.
I had to manually go give my user full access to the C:\Users\XAMPP\ directory. By default (at least on my machine) Windows did not give my admin user rights to this new user's directory, but this is where XAMPP stores all of it's config files. Once I gave myself full access to this, everything worked perfectly.
Hope this helps!
UPDATE!
In retrospect, I think that I must have accidentally typed in "C:\Users\XAMPP\" as the install folder during the installation process. So I think the most important thing is to make sure that the user you are actually signed into Windows as when you start XAMPP has full access to the folder that it was actually installed to.
Spring Boot Remove Whitelabel Error Page
You can remove it completely by specifying:
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
...
@Configuration
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public static MainApp { ... }
However, do note that doing so will probably cause servlet container's whitelabel pages to show up instead :)
EDIT: Another way to do this is via application.yaml. Just put in the value:
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
Documentation
For Spring Boot < 2.0, the class is located in package org.springframework.boot.autoconfigure.web
.
Create a simple 10 second countdown
A solution using Promises, includes both progress bar & text countdown.
_x000D_
_x000D_
ProgressCountdown(10, 'pageBeginCountdown', 'pageBeginCountdownText').then(value => alert(`Page has started: ${value}.`));_x000D_
_x000D_
function ProgressCountdown(timeleft, bar, text) {_x000D_
return new Promise((resolve, reject) => {_x000D_
var countdownTimer = setInterval(() => {_x000D_
timeleft--;_x000D_
_x000D_
document.getElementById(bar).value = timeleft;_x000D_
document.getElementById(text).textContent = timeleft;_x000D_
_x000D_
if (timeleft <= 0) {_x000D_
clearInterval(countdownTimer);_x000D_
resolve(true);_x000D_
}_x000D_
}, 1000);_x000D_
});_x000D_
}
_x000D_
<div class="row begin-countdown">_x000D_
<div class="col-md-12 text-center">_x000D_
<progress value="10" max="10" id="pageBeginCountdown"></progress>_x000D_
<p> Begining in <span id="pageBeginCountdownText">10 </span> seconds</p>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Resolve host name to an ip address
This is hard to answer without more detail about the network architecture. Some things to investigate are:
- Is it possible that client and/or server is behind a NAT device, a firewall, or similar?
- Is any of the IP addresses involved a "local" address, like 192.168.x.y or 10.x.y.z?
- What are the host names, are they "real" DNS:able names or something more local and/or Windows-specific?
- How does the client look up the server? There must be a place in code or config data that holds the host name, simply try using the IP there instead if you want to avoid the lookup.
Getting value of select (dropdown) before change
_x000D_
_x000D_
var last_value;
var current_value;
$(document).on("click","select",function(){
last_value = $(this).val();
}).on("change","select",function(){
current_value = $(this).val();
console.log('last value - '+last_value);
console.log('current value - '+current_value);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
_x000D_
_x000D_
_x000D_
SQL: ... WHERE X IN (SELECT Y FROM ...)
If you want to know which is more effective, you should try looking at the estimated query plans, or the actual query plans after execution. It'll tell you the costs of the queries (I find CPU and IO cost to be interesting). I wouldn't be surprised much if there's little to no difference, but you never know. I've seen certain queries use multiple cores on our database server, while a rewritten version of that same query would only use one core (needless to say, the query that used all 4 cores was a good 3 times faster). Never really quite put my finger on why that is, but if you're working with large result sets, such differences can occur without your knowing about it.
How do I pipe a subprocess call to a text file?
If you want to write the output to a file you can use the stdout-argument of subprocess.call
.
It takes None
, subprocess.PIPE
, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.
You need to open a file with something like open
and pass the object or file descriptor integer to call
:
f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=f)
I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.
As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT
. Any of the above mentioned values works as well, you can redirect to different places.
jQuery: how to find first visible input/select/textarea excluding buttons?
You may try below code...
_x000D_
_x000D_
$(document).ready(function(){_x000D_
$('form').find('input[type=text],textarea,select').filter(':visible:first').focus();_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>_x000D_
<form>_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
_x000D_
<input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_
Prevent a webpage from navigating away using JavaScript
If you are catching a browser back/forward button and don't want to navigate away, you can use:
window.addEventListener('popstate', function() {
if (window.location.origin !== 'http://example.com') {
// Do something if not your domain
} else if (window.location.href === 'http://example.com/sign-in/step-1') {
window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
} else if (window.location.href === 'http://example.com/sign-in/step-2') {
window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
} else {
// Let it do its thing
}
});
Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.
run a python script in terminal without the python command
You need to use a hashbang. Add it to the first line of your python script.
#! <full path of python interpreter>
Then change the file permissions, and add the executing permission.
chmod +x <filename>
And finally execute it using
./<filename>
If its in the current directory,
How to get the HTML's input element of "file" type to only accept pdf files?
To get the HTML file
input form element to only accept PDFs, you can use the accept
attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:
<input name="file1" type="file" accept="application/pdf">
You can string together multiple mime types with a comma.
The following string will accept JPG, PNG, GIF, PDF, and EPS files:
<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps">
In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.
And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.
A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.
How to Select a substring in Oracle SQL up to a specific character?
Using a combination of SUBSTR, INSTR, and NVL (for strings without an underscore) will return what you want:
SELECT NVL(SUBSTR('ABC_blah', 0, INSTR('ABC_blah', '_')-1), 'ABC_blah') AS output
FROM DUAL
Result:
output
------
ABC
Use:
SELECT NVL(SUBSTR(t.column, 0, INSTR(t.column, '_')-1), t.column) AS output
FROM YOUR_TABLE t
Reference:
Addendum
If using Oracle10g+, you can use regex via REGEXP_SUBSTR.
Best way to strip punctuation from a string
I haven't seen this answer yet. Just use a regex; it removes all characters besides word characters (\w
) and number characters (\d
), followed by a whitespace character (\s
):
import re
s = "string. With. Punctuation?" # Sample string
out = re.sub(ur'[^\w\d\s]+', '', s)
Get Absolute Position of element within the window in wpf
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;
Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"
Why don't you just make it easy and simple. If I need to know the number of days between today and say, March 10th, 2015, I can just enter the simple formula.
Lets say the static date is March 10th, 2015, and is in cell O5.
The formula to determine the number of days between today and O5 would be, =O5-Today()
Nothing fancy or DATEDIF stuff. Obviously, the cell where you type this formula in must have a data type of 'number'. Just type your date in normally in the reference cell, in this case O5.
"git rm --cached x" vs "git reset head --? x"?
Perhaps an example will help:
git rm --cached asd
git commit -m "the file asd is gone from the repository"
versus
git reset HEAD -- asd
git commit -m "the file asd remains in the repository"
Note that if you haven't changed anything else, the second commit won't actually do anything.
Convert blob URL to normal URL
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.
Check if string is upper, lower, or mixed case in Python
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
403 Forbidden error when making an ajax Post request in Django framework
For the lazy guys:
First download cookie: http://plugins.jquery.com/cookie/
Add it to your html:
<script src="{% static 'designer/js/jquery.cookie.js' %}"></script>
Now you can create a working POST request:
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax(save_url, {
type : 'POST',
contentType : 'application/json',
data : JSON.stringify(canvas),
success: function () {
alert("Saved!");
}
})
SQL Server: Difference between PARTITION BY and GROUP BY
Small observation. Automation mechanism to dynamically generate SQL using the 'partition by' it is much simpler to implement in relation to the 'group by'. In the case of 'group by', We must take care of the content of 'select' column.
Sorry for My English.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Efficient way to insert a number into a sorted array of numbers?
Just as a single data point, for kicks I tested this out inserting 1000 random elements into an array of 100,000 pre-sorted numbers using the two methods using Chrome on Windows 7:
First Method:
~54 milliseconds
Second Method:
~57 seconds
So, at least on this setup, the native method doesn't make up for it. This is true even for small data sets, inserting 100 elements into an array of 1000:
First Method:
1 milliseconds
Second Method:
34 milliseconds
Create a pointer to two-dimensional array
The basic syntax of initializing pointer that points to multidimentional array is
type (*pointer)[1st dimension size][2nd dimension size][..] = &array_name
The the basic syntax for calling it is
(*pointer_name)[1st index][2nd index][...]
Here is a example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// The multidimentional array...
char balance[5][100] = {
"Subham",
"Messi"
};
char (*p)[5][100] = &balance; // Pointer initialization...
printf("%s\n",(*p)[0]); // Calling...
printf("%s\n",(*p)[1]); // Calling...
return 0;
}
Output is:
Subham
Messi
It worked...
How to delete all instances of a character in a string in python?
replace()
method will work for this. Here is the code that will help to remove character from string. lets say
j_word = 'Stringtoremove'
word = 'String'
for letter in word:
if j_word.find(letter) == -1:
continue
else:
# remove matched character
j_word = j_word.replace(letter, '', 1)
#Output
j_word = "toremove"
How do I set the value property in AngularJS' ng-options?
This was best suited for all scenarios according to me:
<select ng-model="mySelection.value">
<option ng-repeat="r in myList" value="{{r.Id}}" ng-selected="mySelection.value == r.Id">{{r.Name}}
</option>
</select>
where you can use your model to bind the data. You will get the value as the object will contain and the default selection based on your scenario.
Is there a function to round a float in C or do I need to write my own?
To print a rounded value, @Matt J well answers the question.
float x = 45.592346543;
printf("%0.1f\n", x); // 45.6
As most floating point (FP) is binary based, exact rounding to one decimal place is not possible when the mathematically correct answer is x.1, x.2, ...
.
To convert the FP number to the nearest 0.1
is another matter.
Overflow: Approaches that first scale by 10 (or 100, 1000, etc) may overflow for large x
.
float round_tenth1(float x) {
x = x * 10.0f;
...
}
Double rounding: Adding 0.5f and then using floorf(x*10.0f + 0.5f)/10.0
returns the wrong result when the intermediate sum x*10.0f + 0.5f
rounds up to a new integer.
// Fails to round 838860.4375 correctly, comes up with 838860.5
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
if (x < 0.0) {
return ceilf(x*10.0f + 0.5f)/10.0f;
}
return floorf(x*10.0f + 0.5f)/10.0f;
}
Casting to int
has the obvious problem when float x
is much greater than INT_MAX
.
Using roundf()
and family, available in <math.h>
is the best approach.
float round_tenthA(float x) {
double x10 = 10.0 * x;
return (float) (round(x10)/10.0);
}
To avoid using double
, simply test if the number needs rounding.
float round_tenthB(float x) {
const float limit = 1.0/FLT_EPSILON;
if (fabsf(x) < limit) {
return roundf(x*10.0f)/10.0f;
}
return x;
}
How to share data between different threads In C# using AOP?
Look at the following example code:
public class MyWorker
{
public SharedData state;
public void DoWork(SharedData someData)
{
this.state = someData;
while (true) ;
}
}
public class SharedData {
X myX;
public getX() { etc
public setX(anX) { etc
}
public class Program
{
public static void Main()
{
SharedData data = new SharedDate()
MyWorker work1 = new MyWorker(data);
MyWorker work2 = new MyWorker(data);
Thread thread = new Thread(new ThreadStart(work1.DoWork));
thread.Start();
Thread thread2 = new Thread(new ThreadStart(work2.DoWork));
thread2.Start();
}
}
In this case, the thread class MyWorker
has a variable state
. We initialise it with the same object. Now you can see that the two workers access the same SharedData object. Changes made by one worker are visible to the other.
You have quite a few remaining issues. How does worker 2 know when changes have been made by worker 1 and vice-versa? How do you prevent conflicting changes? Maybe read: this tutorial.
How do I iterate over an NSArray?
Add each
method in your NSArray category
, you gonna need it a lot
Code taken from ObjectiveSugar
- (void)each:(void (^)(id object))block {
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
block(obj);
}];
}
WPF: Create a dialog / prompt
Great answer of Josh, all credit to him, I slightly modified it to this however:
MyDialog Xaml
<StackPanel Margin="5,5,5,5">
<TextBlock Name="TitleTextBox" Margin="0,0,0,10" />
<TextBox Name="InputTextBox" Padding="3,3,3,3" />
<Grid Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Name="BtnOk" Content="OK" Grid.Column="0" Margin="0,0,5,0" Padding="8" Click="BtnOk_Click" />
<Button Name="BtnCancel" Content="Cancel" Grid.Column="1" Margin="5,0,0,0" Padding="8" Click="BtnCancel_Click" />
</Grid>
</StackPanel>
MyDialog Code Behind
public MyDialog()
{
InitializeComponent();
}
public MyDialog(string title,string input)
{
InitializeComponent();
TitleText = title;
InputText = input;
}
public string TitleText
{
get { return TitleTextBox.Text; }
set { TitleTextBox.Text = value; }
}
public string InputText
{
get { return InputTextBox.Text; }
set { InputTextBox.Text = value; }
}
public bool Canceled { get; set; }
private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
{
Canceled = true;
Close();
}
private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e)
{
Canceled = false;
Close();
}
And call it somewhere else
var dialog = new MyDialog("test", "hello");
dialog.Show();
dialog.Closing += (sender,e) =>
{
var d = sender as MyDialog;
if(!d.Canceled)
MessageBox.Show(d.InputText);
}
getElementById returns null?
There could be many reason why document.getElementById
doesn't work
You have an invalid ID
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
(resource: What are valid values for the id attribute in HTML?)
you used some id that you already used as <meta>
name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at
(resource: http://www.phpied.com/getelementbyid-description-in-ie/)
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument
before looking for the element
(resource: Calling a specific id inside a frame)
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case document.getElementById
should return at least the first element
Update Git submodule to latest commit on origin
Plain and simple, to fetch the submodules:
git submodule update --init --recursive
And now proceed updating them to the latest master branch (for example):
git submodule foreach git pull origin master
Can anonymous class implement interface?
The answer to the question specifically asked is no. But have you been looking at mocking frameworks? I use MOQ but there's millions of them out there and they allow you to implement/stub (partially or fully) interfaces in-line. Eg.
public void ThisWillWork()
{
var source = new DummySource[0];
var mock = new Mock<DummyInterface>();
mock.SetupProperty(m => m.A, source.Select(s => s.A));
mock.SetupProperty(m => m.B, source.Select(s => s.C + "_" + s.D));
DoSomethingWithDummyInterface(mock.Object);
}
How to inflate one view with a layout
It's helpful to add to this, even though it's an old post, that if the child view that is being inflated from xml is to be added to a viewgroup layout, you need to call inflate with a clue of what type of viewgroup it is going to be added to. Like:
View child = getLayoutInflater().inflate(R.layout.child, item, false);
The inflate method is quite overloaded and describes this part of the usage in the docs. I had a problem where a single view inflated from xml wasn't aligning in the parent properly until I made this type of change.
alert() not working in Chrome
Here is a snippet that does not need ajQuery and will enable alerts in a disabled iframe (like on codepen)
for (var i = 0; i < document.getElementsByTagName('iframe').length; i++) {
document.getElementsByTagName('iframe')[i].setAttribute('sandbox','allow-modals');
}
Here is a codepen demo working with an alert() after this fix as well: http://codepen.io/nicholasabrams/pen/vNpoBr?editors=001
moving committed (but not pushed) changes to a new branch after pull
Checkout fresh copy of you sources
git clone ........
Make branch from desired position
git checkout {position}
git checkout -b {branch-name}
Add remote repository
git remote add shared ../{original sources location}.git
Get remote sources
git fetch shared
Checkout desired branch
git checkout {branch-name}
Merge sources
git merge shared/{original branch from shared repository}
MySQL my.ini location
Open your run console
type: services.msc
look for: mysql
right click
properties
where is written "path to executable", click and move the cursor to the right until you see the directory of my.ini, it's written "defaults-file-".
to reach it manually on your explore folders you have to enable the visualization of hidden elements (explore folder>top menu>visualize>visualize hidden elements)
as explained by this video
https://www.youtube.com/watch?v=SvCAa2XuQhg
Delete all files in directory (but not directory) - one liner solution
Another Java 8 Stream solution to delete all the content of a folder, sub directories included, but not the folder itself.
Usage:
Path folder = Paths.get("/tmp/folder");
CleanFolder.clean(folder);
and the code:
public interface CleanFolder {
static void clean(Path folder) throws IOException {
Function<Path, Stream<Path>> walk = p -> {
try { return Files.walk(p);
} catch (IOException e) {
return Stream.empty();
}};
Consumer<Path> delete = p -> {
try {
Files.delete(p);
} catch (IOException e) {
}
};
Files.list(folder)
.flatMap(walk)
.sorted(Comparator.reverseOrder())
.forEach(delete);
}
}
The problem with every stream solution involving Files.walk or Files.delete is that these methods throws IOException which are a pain to handle in streams.
I tried to create a solution which is more concise as possible.
LINQ: "contains" and a Lambda query
var depthead = (from s in db.M_Users
join m in db.M_User_Types on s.F_User_Type equals m.UserType_Id
where m.UserType_Name.ToUpper().Trim().Contains("DEPARTMENT HEAD")
select new {s.FullName,s.F_User_Type,s.userId,s.UserCode }
).OrderBy(d => d.userId).ToList();
Model.AvailableDeptHead.Add(new SelectListItem { Text = "Select", Value = "0" });
for (int i = 0; i < depthead.Count; i++)
Model.AvailableDeptHead.Add(new SelectListItem { Text = depthead[i].UserCode + " - " + depthead[i].FullName, Value = Convert.ToString(depthead[i].userId) });
Why does PEP-8 specify a maximum line length of 79 characters?
Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.
adb command not found in linux environment
I had this problem when I was trying to connect my phone and trying to use adb. I did the following
export PATH=$PATH{}:/path/to/android-sdk/tools:/path/to/android/platform-tools
apt-get install ia32-libs
Connected my phone in USB debug mode and In the terminal type lsusb to get a list of all usb devices. Noted the 9 character (xxxx:xxxx) ID to the left of my phone.
sudo gedit /etc/udev/rules.d/99-android.rules
Add [
SUBSYSTEM=="usb", ATTRS{idVendor}=="####:####", SYMLINK+="android_adb", MODE="0666" GROUP="plugdev"
TEST=="/var/run/ConsoleKit/database", \
RUN+="udev-acl --action=$env{action} --device=$env{DEVNAME}"
] (whatever is in [...] )to the file and replace "####:####" with the number from step 3cop
sudo service udev restart
Restarted my System
open terminal browse to adb directory and run ./adb devices
And it shows my phone hence adb starts working without error.
I hope it helps others
How can I initialise a static Map?
Here is the code by AbacusUtil
Map<Integer, String> map = N.asMap(1, "one", 2, "two");
// Or for Immutable map
ImmutableMap<Integer, String> = ImmutableMap.of(1, "one", 2, "two");
Declaration: I'm the developer of AbacusUtil.
How to build a Horizontal ListView with RecyclerView?
If you wish to use the Horizontal Recycler View to act as a ViewPager then it's possible now with the help of LinearSnapHelper
which is added in Support Library version 24.2.0.
Firstly Add RecyclerView to your Activity/Fragment
<android.support.v7.widget.RecyclerView
android:layout_below="@+id/sign_in_button"
android:layout_width="match_parent"
android:orientation="horizontal"
android:id="@+id/blog_list"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
In my case I have used a CardView
inside the RecyclerView
blog_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="15dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/imageBlogPost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:paddingBottom="15dp"
android:src="@drawable/common_google_signin_btn_text_light_normal" />
<TextView
android:id="@+id/TitleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="Post Title Here"
android:textSize="16sp" />
<TextView
android:id="@+id/descriptionTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post Description Here"
android:paddingBottom="15dp"
android:textSize="14sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
In your Activity/Fragment
private RecyclerView mBlogList;
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
mBlogList = (RecyclerView) findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(layoutManager);
LinearSnapHelper snapHelper = new LinearSnapHelper() {
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager lm, int velocityX, int velocityY) {
View centerView = findSnapView(lm);
if (centerView == null)
return RecyclerView.NO_POSITION;
int position = lm.getPosition(centerView);
int targetPosition = -1;
if (lm.canScrollHorizontally()) {
if (velocityX < 0) {
targetPosition = position - 1;
} else {
targetPosition = position + 1;
}
}
if (lm.canScrollVertically()) {
if (velocityY < 0) {
targetPosition = position - 1;
} else {
targetPosition = position + 1;
}
}
final int firstItem = 0;
final int lastItem = lm.getItemCount() - 1;
targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
return targetPosition;
}
};
snapHelper.attachToRecyclerView(mBlogList);
Last Step is to set adapter to RecyclerView
mBlogList.setAdapter(firebaseRecyclerAdapter);
Which Python memory profiler is recommended?
guppy3 is quite simple to use. At some point in your code, you have to write the following:
from guppy import hpy
h = hpy()
print(h.heap())
This gives you some output like this:
Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 35144 27 2140412 26 2140412 26 str
1 38397 29 1309020 16 3449432 42 tuple
2 530 0 739856 9 4189288 50 dict (no owner)
You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.
There is a graphical browser as well, written in Tk.
For Python 2.x, use Heapy.
How to access the php.ini file in godaddy shared hosting linux
Follow below if you use godaddy shared hosting..
its very simple:
we need to access root folder of the server via ftp, create a "php5.ini" named file under public_html folder... and then add 3 stupid lines... also "php5" because I'm using php5.4 for 1 of my client. you can check your version via control panel and search php version. Adding a new file with php5.ini will not hamper anything on server end, but it will only overwrite whatever we are commanding it to do.
steps are simple:
go to file manager..
click on public_html..
a new window will appear..
Click on "+"sign and create a new file in the name: "php5.ini" ... click ok/save. Now right click on that newly created php5.ini file and click on edit... a new window will appear... copy paste these below lines & click on save and close the window.
memory_limit = 128M
upload_max_filesize = 60M
max_input_vars = 5000
React: why child component doesn't update when prop changes
I was encountering the same problem.
I had a Tooltip
component that was receiving showTooltip
prop, that I was updating on Parent
component based on an if
condition, it was getting updated in Parent
component but Tooltip
component was not rendering.
const Parent = () => {
let showTooltip = false;
if(....){ showTooltip = true; }
return(
<Tooltip showTooltip={showTooltip}></Tooltip>
)
}
The mistake I was doing is to declare showTooltip
as a let.
I realized what I was doing wrong I was violating the principles of how rendering works, Replacing it with hooks did the job.
const [showTooltip, setShowTooltip] = React.useState<boolean>(false);
Validate that end date is greater than start date with jQuery
Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(params).val());
}
return isNaN(value) && isNaN($(params).val())
|| (Number(value) > Number($(params).val()));
},'Must be greater than {0}.');
To use it:
$("#EndDate").rules('add', { greaterThan: "#StartDate" });
or
$("form").validate({
rules: {
EndDate: { greaterThan: "#StartDate" }
}
});
Python: List vs Dict for look up table
A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part.
EDIT: for your new question, YES, a set would be better. Just create 2 sets, one for sequences ended in 1 and other for the sequences ended in 89. I have sucessfully solved this problem using sets.
How to open a workbook specifying its path
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
What are allowed characters in cookies?
Newer rfc6265 published in April 2011:
cookie-header = "Cookie:" OWS cookie-string OWS
cookie-string = cookie-pair *( ";" SP cookie-pair )
cookie-pair = cookie-name "=" cookie-value
cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
; US-ASCII characters excluding CTLs,
; whitespace DQUOTE, comma, semicolon,
; and backslash
If you look to @bobince answer you see that newer restrictions are more strict.
Regexp Java for password validation
Thanks for all answers, based on all them but extending sphecial characters:
@SuppressWarnings({"regexp", "RegExpUnexpectedAnchor", "RegExpRedundantEscape"})
String PASSWORD_SPECIAL_CHARS = "@#$%^`<>&+=\"!ºª·#~%&'¿¡€,:;*/+-.=_\\[\\]\\(\\)\\|\\_\\?\\\\";
int PASSWORD_MIN_SIZE = 8;
String PASSWORD_REGEXP = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[" + PASSWORD_SPECIAL_CHARS + "])(?=\\S+$).{"+PASSWORD_MIN_SIZE+",}$";
Unit tested:
What does '--set-upstream' do?
When you push to a remote and you use the --set-upstream
flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.
Adding a remote tracking branch means that git then knows what you want to do when you git fetch
, git pull
or git push
in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.
You could achieve the same thing with git branch --set-upstream-to
or git checkout --track
. See the git help pages on tracking branches for more information.
Fill DataTable from SQL Server database
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.
What determines the monitor my app runs on?
Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.
So I am not sure there is a way to tell every program where to open. Hope that helps some.
Convert base64 png data to javascript file objects
Way 1: only works for dataURL, not for other types of url.
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
console.log(file);
})
Both works in Chrome and Firefox.
How do I increase modal width in Angular UI Bootstrap?
When we open a modal it accept size as a paramenter:
Possible values for it size: sm, md, lg
$scope.openModal = function (size) {
var modal = $modal.open({
size: size,
templateUrl: "/app/user/welcome.html",
......
});
}
HTML:
<button type="button"
class="btn btn-default"
ng-click="openModal('sm')">Small Modal</button>
<button type="button"
class="btn btn-default"
ng-click="openModal('md')">Medium Modal</button>
<button type="button"
class="btn btn-default"
ng-click="openModal('lg')">Large Modal</button>
If you want any specific size, add style on model HTML:
<style>.modal-dialog {width: 500px;} </style>
How to check the input is an integer or not in Java?
You can try this way
String input = "";
try {
int x = Integer.parseInt(input);
// You can use this method to convert String to int, But if input
//is not an int value then this will throws NumberFormatException.
System.out.println("Valid input");
}catch(NumberFormatException e) {
System.out.println("input is not an int value");
// Here catch NumberFormatException
// So input is not a int.
}
Batch Script to Run as Administrator
Create a shortcut and set the shortcut to always run as administrator.
How-To Geek forum Make a batch file to run cmd as administrator solution:
Make a batch file in an editor and nameit.bat then create a shortcut to it. Nameit.bat - shortcut. then right click on Nameit.bat - shortcut ->Properties->Shortcut tab -> Advanced and click Run as administrator. Execute it from the shortcut.
Excel SUMIF between dates
this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...
=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))
assigning column names to a pandas series
You can also use the .to_frame()
method.
If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name
argument of .to_frame()
will name the column.
x = x.to_frame('count')
If you want them both as columns, you can reset the index:
x = x.to_frame('count').reset_index()
Where and why do I have to put the "template" and "typename" keywords?
typedef typename Tail::inUnion<U> dummy;
However, I'm not sure you're implementation of inUnion is correct. If I understand correctly, this class is not supposed to be instantiated, therefore the "fail" tab will never avtually fails. Maybe it would be better to indicates whether the type is in the union or not with a simple boolean value.
template <typename T, typename TypeList> struct Contains;
template <typename T, typename Head, typename Tail>
struct Contains<T, UnionNode<Head, Tail> >
{
enum { result = Contains<T, Tail>::result };
};
template <typename T, typename Tail>
struct Contains<T, UnionNode<T, Tail> >
{
enum { result = true };
};
template <typename T>
struct Contains<T, void>
{
enum { result = false };
};
PS: Have a look at Boost::Variant
PS2: Have a look at typelists, notably in Andrei Alexandrescu's book: Modern C++ Design
creating custom tableview cells in swift
It is Purely swift notation an working for me
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cellIdentifier:String = "CustomFields"
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
if (cell == nil)
{
var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil)
cell = nib[0] as? CustomCell
}
return cell!
}
Check if SQL Connection is Open or Closed
Check if a MySQL connection is open
ConnectionState state = connection.State;
if (state == ConnectionState.Open)
{
return true;
}
else
{
connection.Open();
return true;
}
Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception
Two options (at least):
- Add the commons-logging jar to your file by copying it into a local folder.
Note: linking the jar can lead to problems with the server and maybe the reason why it's added to the build path but not solving the server startup problem.
So don't point the jar to an external folder.
OR...
- If you really don't want to add it locally because you're sharing the jar between projects, then...
If you're using a tc server instance, then you need to add the jar as an external jar to the server instance run configurations.
go to run as, run configurations..., {your tc server instance}, and then the Class Path tab.
Then add the commons-logging jar.
CSS centred header image
you don't need to set the width of header in css, just put the background image as center using this code:
background: url("images/logo.png") no-repeat top center;
or you can just use img
tag and put align="center"
in the div
Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes
- How do I convert my results to only hours and minutes
- The accepted answer only returns
days + hours
. Minutes are not included.
- To provide a column that has hours and minutes, as
hh:mm
or x hours y minutes
, would require additional calculations and string formatting.
- This answer shows how to get either total hours or total minutes as a float, using
timedelta
math, and is faster than using .astype('timedelta64[h]')
- Pandas Time Deltas User Guide
- Pandas Time series / date functionality User Guide
- python
timedelta
objects: See supported operations.
- The following sample data is already a
datetime64[ns] dtype
. It is required that all relevant columns are converted using pandas.to_datetime()
.
import pandas as pd
# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}
# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)
# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date) # also works
df['time_delta'] = (df.from_date - df.to_date)
# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)
# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)
# display(df)
to_date from_date time_delta tot_hour_diff tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000 58.636061 3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000 3.684528 221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000 8.714933 522.896000
Other methods
- An item of note from the podcast in Other Resources,
.total_seconds()
was added and merged when the core developer was on vacation, and would not have been approved.
- This is also why there aren't other
.total_xx
methods.
# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0 211089.82
1 13264.30
2 31373.76
dtype: float64
# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0 2
1 0
2 0
dtype: int64
# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0 38289
1 13264
2 31373
dtype: int64
Other Resources
%%timeit
test
import pandas as pd
# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)
%%timeit
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
43.1 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
(df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
59.8 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Changing .gitconfig location on Windows
For me it worked very simple:
- Copy ".gitconfig" from old directory: to %USERPROFILE% (standard in "c:\users\username")
- Right click on start-icons of GITGUI and GITBASH and change "run in": "%HOMEDRIVE%%HOMEPATH%" to "%USERPROFILE%". Of cource you can use any other directory instead of "%USERPROFILE%".
screen shot before
screen shot after
Visual studio equivalent of java System.out
You can use Console.WriteLine()
to write out any native type. To see the output you must write console application (like in Java), then the output will be displayed in the Command Prompt, or if you are developing a windows GUI application, in Visual Studio you must turn on "Output" panel (under View) to see the commands output.
How to convert ASCII code (0-255) to its corresponding character?
for (int i = 0; i < 256; i++) {
System.out.println(i + " -> " + (char) i);
}
char lowercase = 'f';
int offset = (int) 'a' - (int) 'A';
char uppercase = (char) ((int) lowercase - offset);
System.out.println("The uppercase letter is " + uppercase);
String numberString = JOptionPane.showInputDialog(null,
"Enter an ASCII code:",
"ASCII conversion", JOptionPane.QUESTION_MESSAGE);
int code = (int) numberString.charAt(0);
System.out.println("The character for ASCII code "
+ code + " is " + (char) code);
How to change menu item text dynamically in Android
It seems to me that you want to change the contents of menu inside a local method, and this method is called at any time, whenever an event is occurred, or in the activity UI thread.
Why don't you take the instance of Menu in the global variable in onPrepareOptionsMenu when this is overridden and use in this method of yours. Be sure that this method is called whenever an event is occurred (like button click), or in the activity UI thread, handler or async-task post-execute.
You should know in advance the index of this menu item you want to change. After clearing the menu, you need to inflate the menu XML and update your item's name or icon.
Regex - Should hyphens be escaped?
Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z]
or [0-9-]
), OR escape it (e.g. [a-z\-0-9]
) in order to add "hyphen" to your class.
It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.
(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]
) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)
Great question!
how to set the default value to the drop down list control?
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);
And in your cancel method:
lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");
And in your update method:
lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;
How to compare arrays in C#?
You can use the Enumerable.SequenceEqual() in the System.Linq to compare the contents in the array
bool isEqual = Enumerable.SequenceEqual(target1, target2);
How do I make text bold in HTML?
It’s just <b>
instead of <bold>
:
Some <b>text</b> that I want bolded.
Note that <b>
just changes the appearance of the text. If you want to render it bold because you want to express a strong emphasis, you should better use the <strong>
element.
HTML embedded PDF iframe
If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:
<object data="your_url_to_pdf" type="application/pdf">
<iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>
OpenCV with Network Cameras
OpenCV can be compiled with FFMPEG support. From ./configure --help:
--with-ffmpeg use ffmpeg libraries (see LICENSE) [automatic]
You can then use cvCreateFileCapture_FFMPEG to create a CvCapture with e.g. the URL of the camera's MJPG stream.
I use this to grab frames from an AXIS camera:
CvCapture *capture =
cvCreateFileCapture_FFMPEG("http://axis-cam/mjpg/video.mjpg?resolution=640x480&req_fps=10&.mjpg");
How to change Android usb connect mode to charge only?
I have been searching for this for ages on my CM 11 android phone, running kitkat.
Well.. finally I found it. It's hidden in a totally unintuitive location:
- Go to settings
- Go to storage
- Open the menu and choose USB computer connection
Here you can choose between Media Device (MTP), Camera (PTP) and Mass storage (UMS). Turn them all off to get it to charge only.
Sadly, if the option is not there, it is not supported by the phone. This seems to be the case for my HTC One (M7).
How can I split a string into segments of n characters?
_x000D_
_x000D_
var str = 'abcdefghijkl';_x000D_
console.log(str.match(/.{1,3}/g));
_x000D_
_x000D_
_x000D_
Note: Use {1,3}
instead of just {3}
to include the remainder for string lengths that aren't a multiple of 3, e.g:
_x000D_
_x000D_
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
_x000D_
_x000D_
_x000D_
A couple more subtleties:
- If your string may contain newlines (which you want to count as a character rather than splitting the string), then the
.
won't capture those. Use /[\s\S]{1,3}/
instead. (Thanks @Mike).
- If your string is empty, then
match()
will return null
when you may be expecting an empty array. Protect against this by appending || []
.
So you may end up with:
_x000D_
_x000D_
var str = 'abcdef \t\r\nghijkl';_x000D_
var parts = str.match(/[\s\S]{1,3}/g) || [];_x000D_
console.log(parts);_x000D_
_x000D_
console.log(''.match(/[\s\S]{1,3}/g) || []);
_x000D_
_x000D_
_x000D_
Ubuntu: OpenJDK 8 - Unable to locate package
I was having the same issue and tried all of the solutions on this page but none of them did the trick.
What finally worked was adding the universe
repo to my repo list. To do that run the following command
sudo add-apt-repository universe
After running the above command I was able to run
sudo apt install openjdk-8-jre
without an issue and the package was installed.
Hope this helps someone.