I use the following script to update the default alternative after install jdk.
#!/bin/bash
export JAVA_BIN_DIR=/usr/java/default/bin # replace with your installed directory
cd ${JAVA_BIN_DIR}
a=(java javac javadoc javah javap javaws)
for exe in ${a[@]}; do
sudo update-alternatives --install "/usr/bin/${exe}" "${exe}" "${JAVA_BIN_DIR}/${exe}" 1
sudo update-alternatives --set ${exe} ${JAVA_BIN_DIR}/${exe}
done
The header <math.h>
is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath>
is the C++ version of that header. It defines essentially the same stuff in namespace std
. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h>
doesn't exist.
Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std
. Or there's some macro magic for parsing the same header with or without namespace std
wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath>
be a one-liner including some other header with a .h
extension. Or some would map all includes matching <cblah>
to <blah.h>
(which, through macro magic, becomes the C++ header when __cplusplus
is defined, and otherwise becomes the C header) or <cblah.h>
or whatever.
That's the reason why on some platforms including things like <cmath.h>
, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.
I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath>
maps to <cmath.h>
with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.
Note, however, that this code still ought not to compile:
#include <cmath>
double f(double d)
{
return abs(d);
}
There shouldn't be an abs()
in the global namespace (it's std::abs()
). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.
Abstraction delineates a context-specific, simplified representation of something; it ignores contextually-irrelevant details and includes contextually-important details.
Encapsulation restricts outside access to something's parts and bundles that thing's state with the procedures that use the state.
Take people, for instance. In the context of surgery a useful abstraction ignores a person's religious beliefs and includes the person's body. Further, people encapsulate their memories with the thought processes that use those memories. An abstraction need not have encapsulation; for instance, a painting of a person neither hides its parts nor bundles procedures with its state. And, encapsulation need not have an associated abstraction; for instance, real people (not abstract ones) encapsulate their organs with their metabolism.
Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])
Select from a View or from a table will not make too much sense.
Of course if the View does not have unnecessary joins, fields, etc. You can check the execution plan of your queries, joins and indexes used to improve the View performance.
You can even create index on views for faster search requirements. http://technet.microsoft.com/en-us/library/cc917715.aspx
But if you are searching like '%...%' than the sql engine will not benefit from an index on text column. If you can force your users to make searches like '...%' than that will be fast
referred to answer on asp forums : https://forums.asp.net/t/1697933.aspx?Which+is+faster+when+using+SELECT+query+VIEW+or+Table+
I have found a solution for the same question on this site
from tkinter import Tk
from tkinter.ttk import Label
root = Tk()
Label(root, text="Hello world").pack()
# Apparently a common hack to get the window size. Temporarily hide the
# window to avoid update_idletasks() drawing the window in the wrong
# position.
root.withdraw()
root.update_idletasks() # Update "requested size" from geometry manager
x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
root.geometry("+%d+%d" % (x, y))
# This seems to draw the window frame immediately, so only call deiconify()
# after setting correct window position
root.deiconify()
root.mainloop()
sure, I changed it correspondingly to my purposes, it works.
I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.
Use String.valueOf():
int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(String.valueOf(sdRate)); //no more errors
One property need to set for pycharm.
import matplotlib.pyplot as plt
plt.interactive(False) #need to set to False
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
plt.show()
Another way to collect uniq columns with sql:
Model.group(:rating).pluck(:rating)
I think your best bet if you want both text field and label to hide simultaneously is assign each with a class and hide them like this:
jQuery(".labelClass, .inputClass").hide();
http://llvm.org/docs/FAQ.html#translatecxx
It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.
Usage sytax from the command line is as follows for version 9.0.1:
clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c CPPtoC.bc -o CPPtoC.c
For older versions (unsure of transition version), use the following syntax:
llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c CPPtoC.bc -o CPPtoC.c
Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.
Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.
EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.
Swift 5 Answer
I found this thread because I needed a Swift version of this question. As nobody has answered with the solution, here's mine:
extension UIColor {
var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (red, green, blue, alpha)
}
func isSimilar(to colorB: UIColor) -> Bool {
let rgbA = self.rgba
let rgbB = colorB.rgba
let diffRed = abs(CGFloat(rgbA.red) - CGFloat(rgbB.red))
let diffGreen = abs(rgbA.green - rgbB.green)
let diffBlue = abs(rgbA.blue - rgbB.blue)
let pctRed = diffRed
let pctGreen = diffGreen
let pctBlue = diffBlue
let pct = (pctRed + pctGreen + pctBlue) / 3 * 100
return pct < 10 ? true : false
}
}
Usage:
let black: UIColor = UIColor.black
let white: UIColor = UIColor.white
let similar: Bool = black.isSimilar(to: white)
I set less than 10% difference to return similar colours, but you can customise this yourself.
You are not supposed to use floats in React Native. React Native leverages the flexbox to handle all that stuff.
In your case, you will probably want the container to have an attribute
justifyContent: 'flex-end'
And about the text taking the whole space, again, you need to take a look at your container.
Here is a link to really great guide on flexbox: A Complete Guide to Flexbox
If you still can not unmount or remount your device after stopping all services and processes with open files, then there may be a swap file or swap partition keeping your device busy. This will not show up with fuser
or lsof
. Turn off swapping with:
sudo swapoff -a
You could check beforehand and show a summary of any swap partitions or swap files with:
swapon -s
or:
cat /proc/swaps
As an alternative to using the command sudo swapoff -a
, you might also be able to disable the swap by stopping a service or systemd unit. For example:
sudo systemctl stop dphys-swapfile
or:
sudo systemctl stop var-swap.swap
In my case, turning off swap was necessary, in addition to stopping any services and processes with files open for writing, so that I could remount my root partition as read only in order to run fsck
on my root partition without rebooting. This was necessary on a Raspberry Pi running Raspbian Jessie.
from enum import Enum
class StringConsts(str,Enum):
ONE='one'
TWO='two'
print(f'Truth is {StringConsts.ONE=="one"}') #Truth is True
StringConsts.ONE="one" #Error: Cannot reassign
This mixin of Enum and str gives you the power of not having to reimplement setattr (through Enum) and comparison to other str objects (through str).
This might deprecate http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991 completely.
To define deadlock, first I would define process.
Process : As we know process is nothing but a program
in execution.
Resource : To execute a program process needs some resources. Resource categories may include memory, printers, CPUs, open files, tape drives, CD-ROMS, etc.
Deadlock : Deadlock is a situation or condition when two or more processes are holding some resources and trying to acquire some more resources, and they can not release the resources until they finish there execution.
Deadlock condition or situation
In the above diagram there are two process P1 and p2 and there are two resources R1 and R2.
Resource R1 is allocated to process P1 and resource R2 is allocated to process p2. To complete execution of process P1 needs resource R2, so P1 request for R2, but R2 is already allocated to P2.
In the same way Process P2 to complete its execution needs R1, but R1 is already allocated to P1.
both the processes can not release their resource until and unless they complete their execution. So both are waiting for another resources and they will wait forever. So this is a DEADLOCK Condition.
In order for deadlock to occur, four conditions must be true.
and all these condition are satisfied in above diagram.
According to this site, this is supported in the playbackRate
and defaultPlaybackRate
attributes, accessible via the DOM. Example:
/* play video twice as fast */
document.querySelector('video').defaultPlaybackRate = 2.0;
document.querySelector('video').play();
/* now play three times as fast just for the heck of it */
document.querySelector('video').playbackRate = 3.0;
The above works on Chrome 43+, Firefox 20+, IE 9+, Edge 12+.
I normally set paths in
~/.bashrc
However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7
and it was sufficient for me.
you can also define multiple java_home's and have only one of them active (rest commented).
suppose in your bashrc file, you have
export JAVA_HOME=......jdk1.7
#export JAVA_HOME=......jdk1.8
notice 1.8 is commented. Once you do
source ~/.bashrc
jdk1.7 will be in path.
you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.
Sure, just do
```{r someVar, echo=FALSE}
someVariable
```
to show some (previously computed) variable someVariable
. Or run code that prints etc pp.
So for plotting, I have eg
### Impact of choice of ....
```{r somePlot, echo=FALSE}
plotResults(Res, Grid, "some text", "some more text")
```
where the plotting function plotResults
is from a local package.
I think the "best answer" above, albeit programmatically accurate, does not actually answer the question posed. the question asks how to change the pointer in the mouseover event. I see posts about how one may have an error somewhere is not answering the question. In the accepted answer, the mouseover event is blank (onmouseover=""
) and the style option, instead, is included. Baffling why this was done.
There may be nothing wrong with the inquirer's link. consider the following html:
<a id=test_link onclick="alert('kinda neat);">Click ME!</a>
When a user mouse's over this link, the pointer will not change to a hand...instead, the pointer will behave like it's hovering over normal text. One might not want this...and so, the mouse pointer needs to be told to change.
the answer being sought for is this (which was posted by another):
<a id=test_link onclick="alert('Nice!');"
onmouseover="this.style.cursor='pointer';">Click ME!</a>
However, this is ... a nightmare if you have lots of these, or use this kind of thing all over the place and decide to make some kind of a change or run into a bug. better to make a CSS class for it:
a.lendhand {
cursor: pointer;
}
then:
<a class=lendhand onclick="alert('hand is lent!');">Click ME!</a>
there are many other ways which would be, arguably, better than this method. DIVs, BUTTONs, IMGs, etc might prove more useful. I see no harm in using <a>...</a>
, though.
jarett.
Check out this fiddle:
http://jsfiddle.net/G6N5T/1574/
.wrap {_x000D_
width: 100%;_x000D_
overflow:auto;_x000D_
}_x000D_
_x000D_
.fleft {_x000D_
float:left; _x000D_
width: 33%;_x000D_
background:lightblue;_x000D_
height: 400px;_x000D_
}_x000D_
_x000D_
.fcenter{_x000D_
float:left;_x000D_
width: 33%;_x000D_
background:lightgreen;_x000D_
height:400px;_x000D_
margin-left:0.25%;_x000D_
}_x000D_
_x000D_
.fright {_x000D_
float: right;_x000D_
background:pink;_x000D_
height: 400px;_x000D_
width: 33.5%;_x000D_
_x000D_
}
_x000D_
<div class="wrap">_x000D_
<!--Updated on 10/8/2016; fixed center alignment percentage-->_x000D_
<div class="fleft">Left</div>_x000D_
<div class="fcenter">Center</div>_x000D_
<div class="fright">Right</div>_x000D_
</div>
_x000D_
This uses the CSS float
property for left, right, and center alignments of div
s on a page.
Function to return stream that contain zip file
public static Stream ZipGenerator(List<string> files)
{
ZipArchiveEntry fileInArchive;
Stream entryStream;
int i = 0;
List<byte[]> byteArray = new List<byte[]>();
foreach (var file in files)
{
byteArray.Add(File.ReadAllBytes(file));
}
var outStream = new MemoryStream();
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
fileInArchive=(archive.CreateEntry(Path.GetFileName(file), CompressionLevel.Optimal));
using (entryStream = fileInArchive.Open())
{
using (var fileToCompressStream = new MemoryStream(byteArray[i]))
{
fileToCompressStream.CopyTo(entryStream);
}
i++;
}
}
}
outStream.Position = 0;
return outStream;
}
If you want , write zip to file stream.
using (var fileStream = new FileStream(@"D:\Tools\DBExtractor\DBExtractor\bin\Debug\test.zip", FileMode.Create))
{
outStream.Position = 0;
outStream.WriteTo(fileStream);
}
`
There's an amazing type test operator in XPath 2.0 you can use:
<xsl:if test="$number castable as xs:double">
<!-- implementation -->
</xsl:if>
Right click on the folder you want to download in, and open up tortoise-svn -> repo-browser
.
Enter in the URL above in the next window.
right click on the trunk
folder and choose either checkout
(if you want to update from SVN later) or export
(if you just want your own copy of that revision).
Well, yes, and no...
I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)
That said, though, it's really easy to do the "right thing..."
Step 1:
git stash
in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.
Step 2:
git pull
to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.
Step 3:
git stash pop
That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!
If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.
Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.
for bootstrap 3 use like
$('#myModal').on('hidden.bs.modal', function () {
// do something…
})
It's possible to scale NodeJS out to multiple boxes using a pure TCP load balancer (HAProxy) in front of multiple boxes running one NodeJS process each.
If you then have some common knowledge to share between all instances you could use a central Redis store or similar which can then be accessed from all process instances (e.g. from all boxes)
Using jQuery, and assuming that you have <div id="foo">
:
jQuery(function($){
$('#foo').click(function(e){
console.log( 'clicked on div' );
e.stopPropagation(); // Prevent bubbling
});
$('body').click(function(e){
console.log( 'clicked outside of div' );
});
});
Edit: For a single handler:
jQuery(function($){
$('body').click(function(e){
var clickedOn = $(e.target);
if (clickedOn.parents().andSelf().is('#foo')){
console.log( "Clicked on", clickedOn[0], "inside the div" );
}else{
console.log( "Clicked outside the div" );
});
});
Swift 4.2
For multiple selections you need to set the UITableView
property allowsMultipleSelection
to true.
myTableView.allowsMultipleSelection = true
In case you subclassed the UITableViewCell, you override setSelected(_ selected: Bool, animated: Bool)
method in your custom cell class.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
contentView.backgroundColor = UIColor.green
} else {
contentView.backgroundColor = UIColor.blue
}
}
The Content-Security-Policy
meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.
I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.
For brevity I won’t write the full tag in each sample. Instead I'll only show the content
property, so a sample that says content="default-src 'self'"
means this:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
1. How can I allow multiple sources?
You can simply list your sources after a directive as a space-separated list:
content="default-src 'self' https://example.com/js/"
Note that there are no quotes around parameters other than the special ones, like 'self'
. Also, there's no colon (:
) after the directive. Just the directive, then a space-separated list of parameters.
Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:
https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js
These, however, would not be valid:
http://example.com/js/file.js
^^^^ wrong protocol
https://example.com/file.js
^^ above the specified path
2. How can I use different directives? What do they each do?
The most common directives are:
default-src
the default policy for loading javascript, images, CSS, fonts, AJAX requests, etcscript-src
defines valid sources for javascript filesstyle-src
defines valid sources for css filesimg-src
defines valid sources for imagesconnect-src
defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400
errorThere are others, but these are the ones you're most likely to need.
3. How can I use multiple directives?
You define all your directives inside one meta-tag by terminating them with a semicolon (;
):
content="default-src 'self' https://example.com/js/; style-src 'self'"
4. How can I handle ports?
Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:
content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"
The above would result in:
https://ajax.googleapis.com:123
^^^^ Not ok, wrong port
https://ajax.googleapis.com - OK
http://example.com/free/stuff/file.js
^^ Not ok, only the port 123 is allowed
http://example.com:123/free/stuff/file.js - OK
As I mentioned, you can also use an asterisk to explicitly allow all ports:
content="default-src example.com:*"
5. How can I handle different protocols?
By default, only standard protocols are allowed. For example to allow WebSockets ws://
you will have to allow it explicitly:
content="default-src 'self'; connect-src ws:; style-src 'self'"
^^^ web Sockets are now allowed on all domains and ports.
6. How can I allow the file protocol file://
?
If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem
parameter:
content="default-src filesystem"
7. How can I use inline scripts and style definitions?
Unless explicitly allowed, you can't use inline style definitions, code inside <script>
tags or in tag properties like onclick
. You allow them like so:
content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"
You'll also have to explicitly allow inline, base64 encoded images:
content="img-src data:"
8. How can I allow eval()
?
I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:
content="script-src 'unsafe-eval'"
9. What exactly does 'self'
mean?
You might take 'self'
to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.
I've used 'self'
in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.
But hang on a minute! Can't I just use content="default-src *"
and be done with it?
No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:
content="default-src * 'unsafe-inline' 'unsafe-eval'"
... but I trust you won’t.
Further reading:
I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):
print_r(file_get_contents($url));
Turned out there was a trailing <pre>
tag.
Code coverage tools, such as Emma, Cobertura, and Clover, will instrument your code and record which parts of it gets invoked by running a suite of tests. This is very useful, and should be an integral part of your development process. It will help you identify how well your test suite covers your code.
However, this is not the same as identifying real dead code. It only identifies code that is covered (or not covered) by tests. This can give you false positives (if your tests do not cover all scenarios) as well as false negatives (if your tests access code that is actually never used in a real world scenario).
I imagine the best way to really identify dead code would be to instrument your code with a coverage tool in a live running environment and to analyse code coverage over an extended period of time.
If you are runnning in a load balanced redundant environment (and if not, why not?) then I suppose it would make sense to only instrument one instance of your application and to configure your load balancer such that a random, but small, portion of your users run on your instrumented instance. If you do this over an extended period of time (to make sure that you have covered all real world usage scenarios - such seasonal variations), you should be able to see exactly which areas of your code are accessed under real world usage and which parts are really never accessed and hence dead code.
I have never personally seen this done, and do not know how the aforementioned tools can be used to instrument and analyse code that is not being invoked through a test suite - but I am sure they can be.
This one works for me:
<tr style="height: 15px;"/>
You could add it:
public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {
//parse the string into property names
//Use reflection to get and sort by properties
//something like
foreach( string propname in queryString.Split(','))
input.OrderBy( x => GetPropertyValue( x, propname ) );
// I used Kjetil Watnedal's reflection example
}
The GetPropertyValue
function is from Kjetil Watnedal's answer
The issue would be why? Any such sort would throw exceptions at run-time, rather than compile time (like D2VIANT's answer).
If you're dealing with Linq to Sql and the orderby is an expression tree it will be converted into SQL for execution anyway.
As @Veger said, you can make it final
so that the variable can be used in the inner class.
final ViewPager pager = (ViewPager) findViewById(R.id.fieldspager);
I called it pager
rather than mPager
because you are using it as a local variable in the onCreate
method. The m
prefix is cusomarily reserved for class member variables (i.e. variables that are declared at the beginning of the class and are available to all class methods).
If you actually do need a class member variable, it doesn't work to make it final because you can't use findViewById
to set its value until onCreate
. The solution is to not use an anonymous inner class. This way the mPager
variable doesn't need to be declared final and can be used throughout the class.
public class MainActivity extends AppCompatActivity {
private ViewPager mPager;
private Button mButton;
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
mPager = (ViewPager) findViewById(R.id.fieldspager);
// ...
mButton.setOnClickListener(myButtonClickHandler);
}
View.OnClickListener myButtonClickHandler = new View.OnClickListener() {
@Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
};
}
Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:
def pairs(seq):
i = iter(seq)
prev = next(i)
for item in i:
yield prev, item
prev = item
My preferred approach, which uses data
attributes to hold the state of the number:
<input type='number' step='0.01'/>
// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)
// react to keys
el.addEventListener('onkeyup', ev => {
// user cleared field
if (!ev.target.value) ev.target.dataset.val = ''
// non num input
if (isNaN(ev.key)) {
// deleting
if (ev.keyCode == 8)
ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)
// num input
} else ev.target.dataset.val += ev.key
ev.target.value = parseFloat(ev.target.dataset.val) / 100
})
Try something like
"Line 1" & Environment.NewLine & "Line 2"
This sample show tooltip on cell table with text truncated. Is dynamic based on table width:
$.expr[':'].truncated = function (obj) {
var element = $(obj);
return (element[0].scrollHeight > (element.innerHeight() + 1)) || (element[0].scrollWidth > (element.innerWidth() + 1));
};
$(document).ready(function () {
$("td").mouseenter(function () {
var cella = $(this);
var isTruncated = cella.filter(":truncated").length > 0;
if (isTruncated)
cella.attr("title", cella.text());
else
cella.attr("title", null);
});
});
Demo: https://jsfiddle.net/t4qs3tqs/
It works on all version of jQuery
After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:
Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));
Please inform me if you have any difficulties implementing this solution so I can help.
This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.
Return false
to prevent the keystroke from continuing.
I found that the problem was to do with Powershell not being able to run scripts, if that's the case for you, here is the solution.
if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:
* {
padding: initial;
}
if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.
This is a late answer, but I had the exact same problem and Google sent me to this page, so for completeness here is how I got around the problem.
As far as I can tell, bash
does not have an option to do what the original poster wanted to do. The -c
option will always return after the commands have been executed.
Broken solution: The simplest and obvious attempt around this is:
bash -c 'XXXX ; bash'
This partly works (albeit with an extra sub-shell layer). However, the problem is that while a sub-shell will inherit the exported environment variables, aliases and functions are not inherited. So this might work for some things but isn't a general solution.
Better: The way around this is to dynamically create a startup file and call bash with this new initialization file, making sure that your new init file calls your regular ~/.bashrc
if necessary.
# Create a temporary file
TMPFILE=$(mktemp)
# Add stuff to the temporary file
echo "source ~/.bashrc" > $TMPFILE
echo "<other commands>" >> $TMPFILE
echo "rm -f $TMPFILE" >> $TMPFILE
# Start the new bash shell
bash --rcfile $TMPFILE
The nice thing is that the temporary init file will delete itself as soon as it is used, reducing the risk that it is not cleaned up correctly.
Note: I'm not sure if /etc/bashrc is usually called as part of a normal non-login shell. If so you might want to source /etc/bashrc as well as your ~/.bashrc
.
Use hashes when you don't want to be able to get back the original input, use encryption when you do.
Hashes take some input and turn it into some bits (usually thought of as a number, like a 32 bit integer, 64 bit integer, etc). The same input will always produce the same hash, but you PRINCIPALLY lose information in the process so you can't reliably reproduce the original input (there are a few caveats to that however).
Encryption principally preserves all of the information you put into the encryption function, just makes it hard (ideally impossible) for anyone to reverse back to the original input without possessing a specific key.
Simple Example of Hashing
Here's a trivial example to help you understand why hashing can't (in the general case) get back the original input. Say I'm creating a 1-bit hash. My hash function takes a bit string as input and sets the hash to 1 if there are an even number of bits set in the input string, else 0 if there were an odd number.
Example:
Input Hash
0010 0
0011 1
0110 1
1000 0
Note that there are many input values that result in a hash of 0, and many that result in a hash of 1. If you know the hash is 0, you can't know for sure what the original input was.
By the way, this 1-bit hash isn't exactly contrived... have a look at parity bit.
Simple Example of Encryption
You might encrypt text by using a simple letter substitution, say if the input is A, you write B. If the input is B, you write C. All the way to the end of the alphabet, where if the input is Z, you write A again.
Input Encrypted
CAT DBU
ZOO APP
Just like the simple hash example, this type of encryption has been used historically.
Do attributes migrated from parent to child help identify1 the child?
Note that identification-dependence implies existence-dependence, but not the other way around. Every non-NULL FK means a child cannot exist without parent, but that alone doesn't make the relationship identifying.
For more on this (and some examples), take a look at the "Identifying Relationships" section of the ERwin Methods Guide.
P.S. I realize I'm (extremely) late to the party, but I feel other answers are either not entirely accurate (defining it in terms of existence-dependence instead of identification-dependence), or somewhat meandering. Hopefully this answer provides more clarity...
1 The child's FK is a part of child's PRIMARY KEY or (non-NULL) UNIQUE constraint.
If you are interested in portability between different SQL servers you should use ANSI SQL queries. String escaping in ANSI SQL is done by using double quotes ("). Unfortunately, this escaping method is not portable to MySQL, unless it is set in ANSI compatibility mode.
Personally, I always start my MySQL server with the --sql-mode='ANSI' argument since this allows for both methods for escaping. If you are writing queries that are going to be executed in a MySQL server that was not setup / is controlled by you, here is what you can do:
Enclose them in the following MySQL specific queries:
SET @OLD_SQL_MODE=@@SQL_MODE;
SET SESSION SQL_MODE='ANSI';
-- ANSI SQL queries
SET SESSION SQL_MODE=@OLD_SQL_MODE;
This way the only MySQL specific queries are at the beginning and the end of your .sql script. If you what to ship them for a different server just remove these 3 queries and you're all set. Even more conveniently you could create a script named: script_mysql.sql that would contain the above mode setting queries, source a script_ansi.sql script and reset the mode.
Checkout this thread, it has some useful information about exiting and tracebacks.
If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
It's OK to run Docker-in-Docker (DinD) and in fact Docker (the company) has an official DinD image for this.
The caveat however is that it requires a privileged container, which depending on your security needs may not be a viable alternative.
The alternative solution of running Docker using sibling containers (aka Docker-out-of-Docker or DooD) does not require a privileged container, but has a few drawbacks that stem from the fact that you are launching the container from within a context that is different from that one in which it's running (i.e., you launch the container from within a container, yet it's running at the host's level, not inside the container).
I wrote a blog describing the pros/cons of DinD vs DooD here.
Having said this, Nestybox (a startup I just founded) is working on a solution that runs true Docker-in-Docker securely (without using privileged containers). You can check it out at www.nestybox.com.
This can simply also mean you are missing or have too many parentheses. For example this has too many, and will result in unexpected EOF
:
print(9, not (a==7 and b==6)
Since you said you want to know if its actually installed, I think the best way (short of running version specific code), is to check the reassuringly named "Install" registry key. 0x1 means yes:
C:\>reg query "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5"| findstr Install
Install REG_DWORD 0x1
InstallPath REG_SZ c:\WINNT\Microsoft.NET\Framework\v3.5\
This also happens to be the "Microsoft Recommended" official method.
WMI is another possibility, but seems impractical (Slow? Takes 2 min on my C2D, SSD). Maybe it works better on your server:
C:\>wmic product where "Name like 'Microsoft .Net%'" get Name, Version
Name Version
Microsoft .NET Compact Framework 1.0 SP3 Developer 1.0.4292
Microsoft .NET Framework 3.0 Service Pack 2 3.2.30729
Microsoft .NET Framework 3.5 SP1 3.5.30729
Microsoft .NET Compact Framework 2.0 2.0.5238
Microsoft .NET Framework 4 Client Profile 4.0.30319
Microsoft .NET Framework 4 Multi-Targeting Pack 4.0.30319
Microsoft .NET Framework 2.0 Service Pack 2 2.2.30729
Microsoft .NET Framework 1.1 1.1.4322
Microsoft .NET Framework 4 Extended 4.0.30319
C:\>wmic product where "name like 'Microsoft .N%' and version='3.5.30729'" get name
Name
Microsoft .NET Framework 3.5 SP1
Other than these I think the only way to be 100% sure is to actually run a simple console app compiled targeting your framework version. Personally, I consider this unnecessary and trust the registry method just fine.
Finally, you could set up an intranet test site which is reachable from your server and sniffs the User Agent to determine .NET versions. But that's not a batch file solution of course. Also see doc here.
I edited you fiddle
you just need to add z-index
to the front element and position it accordingly.
<h2>JavaScript Email Validation</h2>
<input id="textEmail">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo" style="color: red;"></p>
<script>
function myFunction() {
var email;
email = document.getElementById("textEmail").value;
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(textEmail.value) == false)
{
document.getElementById("demo").style.color = "red";
document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
alert('Invalid Email Address ->'+email);
return false;
} else{
document.getElementById("demo").style.color = "DarkGreen";
document.getElementById("demo").innerHTML ="Valid Email ->"+email;
}
return true;
}
</script>
pyspark.sql.functions.split()
is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem()
to retrieve each part of the array as a column itself:
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
The result will be:
col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
18 | 856-yygrm | 856 | yygrm
201 | 777-psgdg | 777 | psgdg
I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.
Please go through the post fully to get a clear idea,
map vs flatMap:
To return a length of each word from a list, we would do something like below..
When we collect two lists, given below
Without flat map => [1,2],[1,1] => [[1,2],[1,1]] Here two lists are placed inside a list, so the output will be list containing lists
With flat map => [1,2],[1,1] => [1,2,1,1] Here two lists are flattened and only the values are placed in list, so the output will be list containing only elements
Basically it merges all the objects in to one
## Detailed Version has been given below:-
For example:-
Consider a list [“STACK”, ”OOOVVVER”] and we are trying to return a list like [“STACKOVER”](returning only unique letters from that list)
Initially, we would do something like below to return a list [“STACKOVER”] from [“STACK”, ”OOOVVVER”]
public class WordMap {
public static void main(String[] args) {
List<String> lst = Arrays.asList("STACK","OOOVER");
lst.stream().map(w->w.split("")).distinct().collect(Collectors.toList());
}
}
Here the issue is, Lambda passed to the map method returns a String array for each word, So the stream returned by the map method is actually of type Stream, But what we need is Stream to represent a stream of characters, below image illustrates the problem.
Figure A:
You might think that, We can resolve this problem using flatmap,
OK, let us see how to solve this by using map and Arrays.stream
First of all you gonna need a stream of characters instead of a stream of arrays. There is a method called Arrays.stream() that would take an array and produces a stream, for example:
String[] arrayOfWords = {"STACK", "OOOVVVER"};
Stream<String> streamOfWords = Arrays.stream(arrayOfWords);
streamOfWords.map(s->s.split("")) //Converting word in to array of letters
.map(Arrays::stream).distinct() //Make array in to separate stream
.collect(Collectors.toList());
The above still does not work, because we now end up with a list of streams (more precisely, Stream>), Instead, we must first convert each word into an array of individual letters and then make each array into a separate stream
By using flatMap we should be able to fix this problem as below:
String[] arrayOfWords = {"STACK", "OOOVVVER"};
Stream<String> streamOfWords = Arrays.stream(arrayOfWords);
streamOfWords.map(s->s.split("")) //Converting word in to array of letters
.flatMap(Arrays::stream).distinct() //flattens each generated stream in to a single stream
.collect(Collectors.toList());
flatMap would perform mapping each array not with stream but with the contents of that stream. All of the individual streams that would get generated while using map(Arrays::stream) get merged into a single stream. Figure B illustrates the effect of using the flatMap method. Compare it with what map does in figure A. Figure B
The flatMap method lets you replace each value of a stream with another stream and then joins all the generated streams into a single stream.
We all know that PHP save errors in php_errors.log file.
But, that file contains a lot of data.
If we want to log our application data, we need to save it to a custom location.
We can use two parameters in the error_log function to achieve this.
http://php.net/manual/en/function.error-log.php
We can do it using:
error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log');
Where,
print_r($v, TRUE) :
logs $v (array/string/object) to log file.
3
: Put log message to custom log file specified in the third parameter.
'/var/tmp/errors.log'
: Custom log file (This path is for Linux, we can specify other depending upon OS).
OR, you can use file_put_contents()
file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND);
Where:
'/var/tmp/errors.log':
Custom log file (This path is for Linux, we can specify other depending upon OS).
print_r($v, TRUE) :
logs $v (array/string/object) to log file.
FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.
You have to Download the driver for your Device just go to device manager-->> your device-->update driver-->choose the usb driver path from sdk extras folder and click next. You can get the correct driver and you can run on real device
You should put the button inside a div, and in the div you should be able to use the classes:
text-left, text-center and text-right.
for example:
<div class="row">
<div class="col text-center">
<button class="button button-small button-light">Search</button>
</div>
</div>
And about the "textarea" position:
<div class="list">
<label class="item item-input">
<span class="input-label">Date</span>
<input type="text" placeholder="Text Area">
</label>
Demo using your code:
http://codepen.io/douglask/pen/zxXvYY
$("#myAudioElement")[0].play();
It doesn't work with $("#myAudioElement").play()
like you would expect. The official reason is that incorporating it into jQuery would add a play()
method to every single element, which would cause unnecessary overhead. So instead you have to refer to it by its position in the array of DOM elements that you're retrieving with $("#myAudioElement")
, aka 0.
This quote is from a bug that was submitted about it, which was closed as "feature/wontfix":
To do that we'd need to add a jQuery method name for each DOM element method name. And of course that method would do nothing for non-media elements so it doesn't seem like it would be worth the extra bytes it would take.
Here's a slightly different answer building off of S.Lott's answer that gives a list of dates between two dates start
and end
. In the example below, from the start of 2017 to today.
start = datetime.datetime(2017,1,1)
end = datetime.datetime.today()
daterange = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
This is a common problem, so here's a relatively thorough illustration.
For non-unicode strings (i.e. those without u
prefix like u'\xc4pple'
), one must decode from the native encoding (iso8859-1
/latin1
, unless modified with the enigmatic sys.setdefaultencoding
function) to unicode
, then encode to a character set that can display the characters you wish, in this case I'd recommend UTF-8
.
First, here is a handy utility function that'll help illuminate the patterns of Python 2.7 string and unicode:
>>> def tell_me_about(s): return (type(s), s)
>>> v = "\xC4pple" # iso-8859-1 aka latin1 encoded string
>>> tell_me_about(v)
(<type 'str'>, '\xc4pple')
>>> v
'\xc4pple' # representation in memory
>>> print v
?pple # map the iso-8859-1 in-memory to iso-8859-1 chars
# note that '\xc4' has no representation in iso-8859-1,
# so is printed as "?".
>>> uv = v.decode("iso-8859-1")
>>> uv
u'\xc4pple' # decoding iso-8859-1 becomes unicode, in memory
>>> tell_me_about(uv)
(<type 'unicode'>, u'\xc4pple')
>>> print v.decode("iso-8859-1")
Äpple # convert unicode to the default character set
# (utf-8, based on sys.stdout.encoding)
>>> v.decode('iso-8859-1') == u'\xc4pple'
True # one could have just used a unicode representation
# from the start
>>> u"Ä" == u"\xc4"
True # the native unicode char and escaped versions are the same
>>> "Ä" == u"\xc4"
False # the native unicode char is '\xc3\x84' in latin1
>>> "Ä".decode('utf8') == u"\xc4"
True # one can decode the string to get unicode
>>> "Ä" == "\xc4"
False # the native character and the escaped string are
# of course not equal ('\xc3\x84' != '\xc4').
>>> u8 = v.decode("iso-8859-1").encode("utf-8")
>>> u8
'\xc3\x84pple' # convert iso-8859-1 to unicode to utf-8
>>> tell_me_about(u8)
(<type 'str'>, '\xc3\x84pple')
>>> u16 = v.decode('iso-8859-1').encode('utf-16')
>>> tell_me_about(u16)
(<type 'str'>, '\xff\xfe\xc4\x00p\x00p\x00l\x00e\x00')
>>> tell_me_about(u8.decode('utf8'))
(<type 'unicode'>, u'\xc4pple')
>>> tell_me_about(u16.decode('utf16'))
(<type 'unicode'>, u'\xc4pple')
>>> print u8
Äpple # printing utf-8 - because of the encoding we now know
# how to print the characters
>>> print u8.decode('utf-8') # printing unicode
Äpple
>>> print u16 # printing 'bytes' of u16
???pple
>>> print u16.decode('utf16')
Äpple # printing unicode
>>> v == u8
False # v is a iso8859-1 string; u8 is a utf-8 string
>>> v.decode('iso8859-1') == u8
False # v.decode(...) returns unicode
>>> u8.decode('utf-8') == v.decode('latin1') == u16.decode('utf-16')
True # all decode to the same unicode memory representation
# (latin1 is iso-8859-1)
>>> u8.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
>>> u16.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)
>>> v.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0:
ordinal not in range(128)
One would get around these by converting from the specific encoding (latin-1, utf8, utf16) to unicode e.g. u8.decode('utf8').encode('latin1')
.
So perhaps one could draw the following principles and generalizations:
str
is a set of bytes, which may have one of a number of encodings such as Latin-1, UTF-8, and UTF-16unicode
is a set of bytes that can be converted to any number of encodings, most commonly UTF-8 and latin-1 (iso8859-1)print
command has its own logic for encoding, set to sys.stdout.encoding
and defaulting to UTF-8str
to unicode before converting to another encoding.Of course, all of this changes in Python 3.x.
Hope that is illuminating.
And the very illustrative rants by Armin Ronacher:
You should give your <tr>
tag an id foo_row
or whatever. And hide that instead
Having $line
as it is now, you can simply split the string based on at least one whitespace separator
my @answer = split(' ', $line); # creates an @answer array
then
print("@answer\n"); # print array on one line
or
print("$_\n") for (@answer); # print each element on one line
I prefer using ()
for split
, print
and for
.
To get sms: and mailto: links to work on both iPhone and Android, without any javascript, try this:
<a href="sms:321-555-1111?&body=This is what I want to sent">click to text</a>
<a href="mailto:[email protected]?&subject=My subject&body=This is what I want to sent">click to email</a>
I tested it on Chrome for Android & iPhone, and Safari on iPhone.
They all worked as expected.
They worked without the phone number or email address as well.
Here is a working solution:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char str1[16];
char str2[16];
strcpy(str1, "sssss");
strcpy(str2, "kkkk");
strcat(str1, str2);
printf("%s", str1);
return 0;
}
Output:
ssssskkkk
You have to allocate memory for your strings. In the above code, I declare str1
and str2
as character arrays containing 16 characters. I used strcpy
to copy characters of string literals into them, and strcat
to append the characters of str2
to the end of str1
. Here is how these character arrays look like during the execution of the program:
After declaration (both are empty):
str1: [][][][][][][][][][][][][][][][][][][][]
str2: [][][][][][][][][][][][][][][][][][][][]
After calling strcpy (\0 is the string terminator zero byte):
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
After calling strcat:
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
Here is my option to Edit the project file without the need to Unload the project:
Navigate to the Project which you want to edit inside the Solution folders and right-click on it.
That is it!
You will see the *.csproj
file opened inside Visual Studio Editor.
After you can switch back to a Solution/Project view (see step 1).
**
bundle install --no-deployment
**
$ jekyll help
jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby
USE THIS
I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.
http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/
I hope this helps people because it was exactly what I was looking for
Here's a quick overview that explains the different build targets.
From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."
The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.
Maybe try to refresh your ListView:
receiptsListView.invalidate()
.
EDIT: Another thought came into my mind. Just for the record, try to disable list view cache:
<ListView
...
android:scrollingCache="false"
android:cacheColorHint="@android:color/transparent"
... />
As clean as this :)
function makedir(fullpath) {
let destination_split = fullpath.replace('/', '\\').split('\\')
let path_builder = destination_split[0]
$.each(destination_split, function (i, path_segment) {
if (i < 1) return true
path_builder += '\\' + path_segment
if (!fs.existsSync(path_builder)) {
fs.mkdirSync(path_builder)
}
})
}
Let's start with a quote from the virtual machine spec:
Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.
This may not occur - This is a hint, that there's something special about String
objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:
1: a := "one"
--> if(pool[hash("one")] == null) // true
pool[hash("one") --> "one"]
return pool[hash("one")]
2: b := "one"
--> if(pool[hash("one")] == null) // false, "one" already in pool
pool[hash("one") --> "one"]
return pool[hash("one")]
So in this case, variables a
and b
hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true
.
This is not the case if we use the constructor:
1: a := "one"
2: b := new String("one")
Again, "one"
is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false
So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).
As programmers we don't have to care much about the String pool, as long as we keep in mind:
(a == b) && (a.equals(b))
may be true
or false
(always use equals
to compare Strings)char[]
of a String (as you don't know who is actualling using that String)Very simple ! Here is my suggestion :
If you want to select dataframes in your workspace, try this :
Filter(function(x) is.data.frame(get(x)) , ls())
or
ls()[sapply(ls(), function(x) is.data.frame(get(x)))]
all these will give the same result.
You can change is.data.frame
to check other types of variables like is.function
Determine primary keys and unique keys for all tables in a database...
This should list all the constraints and at the end you can put your filters
/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME)
AS
(
SELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME='' ,
REFERENCE_COL_NAME=''
FROM sys.key_constraints as PKnUKEY
INNER JOIN sys.tables as PKnUTable
ON PKnUTable.object_id = PKnUKEY.parent_object_id
INNER JOIN sys.index_columns as PKnUColIdx
ON PKnUColIdx.object_id = PKnUTable.object_id
AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
INNER JOIN sys.columns as PKnUKEYCol
ON PKnUKEYCol.object_id = PKnUTable.object_id
AND PKnUKEYCol.column_id = PKnUColIdx.column_id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=PKnUTable.name
AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE='FK',
PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30))
FROM sys.foreign_key_columns FKC
INNER JOIN sys.sysobjects oConstraint
ON FKC.constraint_object_id=oConstraint.id
INNER JOIN sys.sysobjects oParent
ON FKC.parent_object_id=oParent.id
INNER JOIN sys.all_columns oParentCol
ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
INNER JOIN sys.sysobjects oReference
ON FKC.referenced_object_id=oReference.id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=oParent.name
AND oParentColDtl.COLUMN_NAME=oParentCol.name
INNER JOIN sys.all_columns oReferenceCol
ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
)
select * from ALL_KEYS_IN_TABLE
where
PARENT_TABLE_NAME in ('YOUR_TABLE_NAME')
or REFERENCE_TABLE_NAME in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;
For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx
Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.
Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103)
Your command is completely incorrect. The output format is not rawvideo
and you don't need the bitstream filter h264_mp4toannexb
which is used when you want to convert the h264
contained in an mp4
to the Annex B
format used by MPEG-TS
for example. What you want to use instead is the aac_adtstoasc
for the AAC
streams.
ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4
Mark color: #005580;
as color: #005580 !important;
.
It will override default bootstrap hover.
You are looking for "|." See http://cran.r-project.org/doc/manuals/R-intro.html#Logical-vectors
my.data.frame <- data[(data$V1 > 2) | (data$V2 < 4), ]
To understand get and set, it's all related to how variables are passed between different classes.
The get method is used to obtain or retrieve a particular variable value from a class.
A set value is used to store the variables.
The whole point of the get and set is to retrieve and store the data values accordingly.
What I did in this old project was I had a User class with my get and set methods that I used in my Server class.
The User class's get set methods:
public int getuserID()
{
//getting the userID variable instance
return userID;
}
public String getfirstName()
{
//getting the firstName variable instance
return firstName;
}
public String getlastName()
{
//getting the lastName variable instance
return lastName;
}
public int getage()
{
//getting the age variable instance
return age;
}
public void setuserID(int userID)
{
//setting the userID variable value
this.userID = userID;
}
public void setfirstName(String firstName)
{
//setting the firstName variable text
this.firstName = firstName;
}
public void setlastName(String lastName)
{
//setting the lastName variable text
this.lastName = lastName;
}
public void setage(int age)
{
//setting the age variable value
this.age = age;
}
}
Then this was implemented in the run()
method in my Server class as follows:
//creates user object
User use = new User(userID, firstName, lastName, age);
//Mutator methods to set user objects
use.setuserID(userID);
use.setlastName(lastName);
use.setfirstName(firstName);
use.setage(age);
Yet another variation.
Somehow, my formerly working test classes appeared to be running from some other location; my edits would not execute when I ran the tests.
I found that the output folder for my ${project_loc}src/test/java files was not what I expected. It had inadvertently been set to ${project_loc}target/classes. I set it properly in project properties, Java Build Path, Source tab.
Picasso graphic library you can used: cross platform
A previous poster said..
If you have PHP installed as a command line tool… your shebang (#!) line needs to look like this:
#!/usr/bin/php
While this could be true… just because you can type in php
does NOT necessarily mean that's where php is going to be... /usr/bin/php
is A common location… but as with any shebang… it needs to be tailored to YOUR env
.
a quick way to find out WHERE YOUR particular executable is located on your $PATH
, try..
?which -a php
ENTER, which for me looks like..
php is /usr/local/php5/bin/php
php is /usr/bin/php
php is /usr/local/bin/php
php is /Library/WebServer/CGI-Executables/php
The first one is the default i'd get if I just typed in php at a command prompt… but I can use any of them in a shebang, or directly… You can also combine the executable name with env
, as is often seen, but I don't really know much about / trust that. XOXO.
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
Alternatively:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);
You could easily replace the forward slashes /
with something like an underscore _
such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.
Load data into a table in MySQL and specify columns:
LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE t1
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
(@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ;
@col1,2,3,4 are variables to hold the csv file columns (assume 4 ) name,id are table columns.
IMHO, You can get your result by concatenating your input *.md files like:
$ pandoc -s -o outputDoc.pdf inputDoc1.md inputDoc2.md outputDoc3.md
Gson is very usefull for this. easier even. here is my example:
public class Bean {
private String nombre="juan";
private String apellido="machado";
private List<InnerBean> datosCriticos;
class InnerBean
{
private int edad=12;
}
public Bean() {
datosCriticos = new ArrayList<>();
datosCriticos.add(new InnerBean());
}
}
Bean bean = new Bean();
Gson gson = new Gson();
String json =gson.toJson(bean);
out.print(json);
{"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}
Have to say people if yours vars are empty when using gson it wont build the json for you.Just the
{}
I tested each of the above methods for finding if any alphabets are contained in a given string and found out average processing time per string on a standard computer.
~250 ns for
import re
~3 µs for
re.search('[a-zA-Z]', string)
~6 µs for
any(c.isalpha() for c in string)
~850 ns for
string.upper().isupper()
Opposite to as alleged, importing re takes negligible time, and searching with re takes just about half time as compared to iterating isalpha() even for a relatively small string.
Hence for larger strings and greater counts, re would be significantly more efficient.
But converting string to a case and checking case (i.e. any of upper().isupper() or lower().islower() ) wins here. In every loop it is significantly faster than re.search() and it doesn't even require any additional imports.
Set the connection string in your config file:
<connectionStrings>
<add name="ConnString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\gadgetDatabase.mdf;Integrated Security=True" />
</connectionStrings>
The other respondents are correct in describing the double leading and trailing underscores as a naming convention for "special" or "magic" methods.
While you can call these methods directly ([10, 20].__len__()
for example), the presence of the underscores is a hint that these methods are intended to be invoked indirectly (len([10, 20])
for example). Most python operators have an associated "magic" method (for example, a[x]
is the usual way of invoking a.__getitem__(x)
).
from subprocess import call
def cp_dir(source, target):
call(['cp', '-a', source, target]) # Linux
cp_dir('/a/b/c/', '/x/y/z/')
It works for me. Basically, it executes shell command cp.
Here's a function that will dynamically create a CSS rule in all major browsers. createCssRule
takes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document
(the current document is used by default):
var addRule;
if (typeof document.styleSheets != "undefined" && document.styleSheets) {
addRule = function(selector, rule) {
var styleSheets = document.styleSheets, styleSheet;
if (styleSheets && styleSheets.length) {
styleSheet = styleSheets[styleSheets.length - 1];
if (styleSheet.addRule) {
styleSheet.addRule(selector, rule)
} else if (typeof styleSheet.cssText == "string") {
styleSheet.cssText = selector + " {" + rule + "}";
} else if (styleSheet.insertRule && styleSheet.cssRules) {
styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
}
}
}
} else {
addRule = function(selector, rule, el, doc) {
el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
};
}
function createCssRule(selector, rule, doc) {
doc = doc || document;
var head = doc.getElementsByTagName("head")[0];
if (head && addRule) {
var styleEl = doc.createElement("style");
styleEl.type = "text/css";
styleEl.media = "screen";
head.appendChild(styleEl);
addRule(selector, rule, styleEl, doc);
styleEl = null;
}
};
createCssRule("body", "background-color: purple;");
This was the shortest way I could find to sort a DataTable without having to create any new variables.
DataTable.DefaultView.Sort = "ColumnName ASC"
DataTable = DataTable.DefaultView.ToTable
Where:
ASC - Ascending
DESC - Descending
ColumnName - The column you want to sort by
DataTable - The table you want to sort
What about just:
:%s/\r//g
That totally worked for me.
What this does is just to clean the end of line of all lines, it removes the ^M and that's it.
With gitk
you can view the two branches graphically:
gitk branch1 branch2
And then it's easy to find the common ancestor in the history of the two branches.
Since there were no answer on how to do this in Combine, here is the approach i used.
userInfo
and check if the current active responder is contained in it. If it's covered return keyboard frame height. If it is not covered return 0, we don't want to move the frame. For the hide notification we simply return 0.private var keyboardHeightPublisher: AnyPublisher<CGFloat, Never> {
Publishers.Merge(
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
.map { $0.intersects(self.view.firstResponder!.frame) ? $0.height : 0 }
.map { $0 * -1 },
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillHideNotification)
.map { _ in CGFloat(0) }
).eraseToAnyPublisher()
}
In the viewDidLoad
we simply subscribe to the publisher changing the views frame accordingly.
override func viewDidLoad() {
super.viewDidLoad()
keyboardHeightPublisher.sink{ [weak self] height in
self?.view.frame.origin.y = height
}.store(in: &cancelables)
}
EDIT
Be careful! If the firstResponder
is in a subview, you have to calculate the frame corresponding to the whole screen to check if they actually intersect.
Example:
let myViewGlobalFrame = myView.convert(myView.frame, to: parentView)
I think this will work even though this was forever ago.
SELECT employee_number, Row_Number()
OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
AND rownum = 1
If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.
SELECT employee_number, Row_Number()
OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
AND rownum = 1
If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.
Tables
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;
Then you just insert rows to table1
INSERT INTO Table1 (name)
VALUES ('Jhon'), ('Mark');
And you'll have
| ID | NAME | ------------------ | LHPL001 | Jhon | | LHPL002 | Mark |
Here is SQLFiddle demo
The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.
http://msdn.microsoft.com/en-us/library/ms181765.aspx
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.
I agree with using sed: it is the best tool for search/replace. Here is my approach:
$ cat template.txt
the number is ${i}
the dog's name is ${name}
$ cat replace.sed
s/${i}/5/
s/${name}/Fido/
$ sed -f replace.sed template.txt > out.txt
$ cat out.txt
the number is 5
the dog's name is Fido
function uniqueid(){
// always start with a letter (for DOM friendlyness)
var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
do {
// between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
var ascicode=Math.floor((Math.random()*42)+48);
if (ascicode<58 || ascicode>64){
// exclude all chars between : (58) and @ (64)
idstr+=String.fromCharCode(ascicode);
}
} while (idstr.length<32);
return (idstr);
}
This probably means that python doesn't know where PyQt5 is located. To check, go into the interactive terminal and type:
import sys
print sys.path
What you probably need to do is add the directory that contains the PyQt5 module to your PYTHONPATH
environment variable. If you use bash
, here's how:
~/.bashrc
export PYTHONPATH=/path/to/PyQt5/directory:$PYTHONPATH
where /path/to/PyQt5/directory
is the path to the folder where the PyQt5 library is located.
Step 1: Goto your Android sdk folder -> platform tools
and copy the whole path
For example: C:\Program Files (x86)\Android\android-sdk\platform-tools
Step 2: Goto command prompt or Android studio terminal
windows users cd C:\Program Files (x86)\Android\android-sdk\platform-tools
Mac Users /Users/<username>/Library/Android/sdk/platform-tools
and press enter
Step 3: Connect your device & system with same wifi.
Step 4: Type adb tcpip 5555
and press Enter.
Step 5: Type adb connect x.x.x.x:5555
, replacing the x.x.x.x with your phone IP address.
find out phone IP address
Settings -> About phone -> Status
(some phones may be vary)
Note: In case that you connect more than one device, disconnect other phones except the one you need to connect.
install this
sudo apt install libgl-dev libglu-dev libglib2.0-dev libsm-dev libxrender-dev libfontconfig1-dev libxext-dev
http://www.qtcentre.org/threads/69625-collect2-error-ld-returned-1-exit-status
Just use the . at the end of the git clone
command (being in that directory), like this:
cd your_dir_to_clone_in/
git clone [email protected]/somerepo/ .
openssl rsa -in privkey.pem -pubout > key.pub
That writes the public key to key.pub
This is similar to some of the other answers, but is compact and avoids the conversion to dictionary if you already have a list.
Given a ComboBox
"combobox" on a windows form and a class SomeClass
with the string
type property Name
,
List<SomeClass> list = new List<SomeClass>();
combobox.DisplayMember = "Name";
combobox.DataSource = list;
Which means that the SelectedItem is a SomeClass
object from list
, and each item in combobox
will be displayed using its name.
Mark all the desired projects in solution explorer.
Press Alt-F7 or right click in solution explorer and select "Properties"
Configurations:All Configurations
Click on the Preprocessor Definitions line to invoke its editor
Choose Edit...
Copy "_CRT_SECURE_NO_WARNINGS" into the Preprocessor Definitions white box on the top.
db.collection("collection_name").deleteOne({_id:ObjectId("4d513345cc9374271b02ec6c")})
The version you have specified, or one of your dependencies has specified is not published to npmjs.com
Executing npm view ionic-native
(see docs) the following output is returned for package versions:
versions:
[ '1.0.7',
'1.0.8',
'1.0.9',
'1.0.10',
'1.0.11',
'1.0.12',
'1.1.0',
'1.1.1',
'1.2.0',
'1.2.1',
'1.2.2',
'1.2.3',
'1.2.4',
'1.3.0',
'1.3.1',
'1.3.2',
'1.3.3',
'1.3.4',
'1.3.5',
'1.3.6',
'1.3.7',
'1.3.8',
'1.3.9',
'1.3.10',
'1.3.11',
'1.3.12',
'1.3.13',
'1.3.14',
'1.3.15',
'1.3.16',
'1.3.17',
'1.3.18',
'1.3.19',
'1.3.20',
'1.3.21',
'1.3.22',
'1.3.23',
'1.3.24',
'1.3.25',
'1.3.26',
'1.3.27',
'2.0.0',
'2.0.1',
'2.0.2',
'2.0.3',
'2.1.2',
'2.1.3',
'2.1.4',
'2.1.5',
'2.1.6',
'2.1.7',
'2.1.8',
'2.1.9',
'2.2.0',
'2.2.1',
'2.2.2',
'2.2.3',
'2.2.4',
'2.2.5',
'2.2.6',
'2.2.7',
'2.2.8',
'2.2.9',
'2.2.10',
'2.2.11',
'2.2.12',
'2.2.13',
'2.2.14',
'2.2.15',
'2.2.16',
'2.2.17',
'2.3.0',
'2.3.1',
'2.3.2',
'2.4.0',
'2.4.1',
'2.5.0',
'2.5.1',
'2.6.0',
'2.7.0',
'2.8.0',
'2.8.1',
'2.9.0' ],
As you can see no version higher than 2.9.0
has been published to the npm repository. Strangely they have versions higher than this on GitHub. I would suggest opening an issue with the maintainers on this.
For now you can manually install the package via the tarball URL of the required release:
npm install https://github.com/ionic-team/ionic-native/tarball/v3.5.0
Using 'now()' as default value automatically generates time-stamp.
Two UDF to deal with UTF-8 in T-SQL:
CREATE Function UcsToUtf8(@src nvarchar(MAX)) returns varchar(MAX) as
begin
declare @res varchar(MAX)='', @pi char(8)='%[^'+char(0)+'-'+char(127)+']%', @i int, @j int
select @i=patindex(@pi,@src collate Latin1_General_BIN)
while @i>0
begin
select @j=unicode(substring(@src,@i,1))
if @j<0x800 select @res=@res+left(@src,@i-1)+char((@j&1984)/64+192)+char((@j&63)+128)
else select @res=@res+left(@src,@i-1)+char((@j&61440)/4096+224)+char((@j&4032)/64+128)+char((@j&63)+128)
select @src=substring(@src,@i+1,datalength(@src)-1), @i=patindex(@pi,@src collate Latin1_General_BIN)
end
select @res=@res+@src
return @res
end
CREATE Function Utf8ToUcs(@src varchar(MAX)) returns nvarchar(MAX) as
begin
declare @i int, @res nvarchar(MAX)=@src, @pi varchar(18)
select @pi='%[à-ï][€-¿][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
while @i>0 select @res=stuff(@res,@i,3,nchar(((ascii(substring(@src,@i,1))&31)*4096)+((ascii(substring(@src,@i+1,1))&63)*64)+(ascii(substring(@src,@i+2,1))&63))), @src=stuff(@src,@i,3,'.'), @i=patindex(@pi,@src collate Latin1_General_BIN)
select @pi='%[Â-ß][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
while @i>0 select @res=stuff(@res,@i,2,nchar(((ascii(substring(@src,@i,1))&31)*64)+(ascii(substring(@src,@i+1,1))&63))), @src=stuff(@src,@i,2,'.'),@i=patindex(@pi,@src collate Latin1_General_BIN)
return @res
end
Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).
This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.
# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np
# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8) # mask is only
for i in circles[0, :]:
cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)
# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)
# combine foreground+background
final = cv2.bitwise_or(fg, bk)
Note: It is better to use the opencv methods because they are optimized.
I have your answer, as I just had the same problem today:
Someone made a working vba code that changes the vba protection password to "macro", for all excel files, including .xlsm (2007+ versions). You can see how it works by browsing his code.
This is the guy's blog: http://lbeliarl.blogspot.com/2014/03/excel-removing-password-from-vba.html Here's the file that does the work: https://docs.google.com/file/d/0B6sFi5sSqEKbLUIwUTVhY3lWZE0/edit
Pasted from a previous post from his blog:
For Excel 2007/2010 (.xlsm) files do following steps:
Find and copy the value from parameter DPB (value in quotation mark), example: DPB="282A84CBA1CBA1345FCCB154E20721DE77F7D2378D0EAC90427A22021A46E9CE6F17188A". (This value generated for 'macro' password. You can use this DPB value to skip steps 1-8)
Do steps 4-7 for file with unknown password (file you want to unlock).
Change DBP value in this file on value that you have copied in step 8.
If copied value is shorter than in encrypted file you should populate missing characters with 0 (zero). If value is longer - that is not a problem (paste it as is).
Save the 'vbaProject.bin' file and exit from hex editor.
Jeff Atwood has a recent blog post about this: The Great Newline Schism
Here is the essence from Wikipedia:
The sequence CR+LF was in common use on many early computer systems that had adopted teletype machines, typically an ASR33, as a console device, because this sequence was required to position those printers at the start of a new line. On these systems, text was often routinely composed to be compatible with these printers, since the concept of device drivers hiding such hardware details from the application was not yet well developed; applications had to talk directly to the teletype machine and follow its conventions. The separation of the two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in one-character time. That is why the sequence was always sent with the CR first. In fact, it was often necessary to send extra characters (extraneous CRs or NULs, which are ignored) to give the print head time to move to the left margin. Even after teletypes were replaced by computer terminals with higher baud rates, many operating systems still supported automatic sending of these fill characters, for compatibility with cheaper terminals that required multiple character times to scroll the display.
From the Python documentation wiki, I think you can do:
a = ([[1, 2, 3], [4, 5, 6], [0, 0, 1]]);
a = sorted(a, key=lambda a_entry: a_entry[1])
print a
The output is:
[[[0, 0, 1], [1, 2, 3], [4, 5, 6]]]
You can use the toISOString
function :
var today = new Date();
today.toISOString().substring(0, 10);
It will give you a "yyyy-mm-dd" format.
Rules that tell how to compare and sort strings: letters order; whether case matters, whether diacritics matter etc.
For instance, if you want all letters to be different (say, if you store filenames in UNIX
), you use UTF8_BIN
collation:
SELECT 'A' COLLATE UTF8_BIN = 'a' COLLATE UTF8_BIN
---
0
If you want to ignore case and diacritics differences (say, for a search engine), you use UTF8_GENERAL_CI
collation:
SELECT 'A' COLLATE UTF8_GENERAL_CI = 'ä' COLLATE UTF8_GENERAL_CI
---
1
As you can see, this collation (comparison rule) considers capital A
and lowecase ä
the same letter, ignoring case and diacritic differences.
Angular elements (such as the root element of a directive) are jQuery [Lite] objects. This means we can register the event listener like so:
link($scope, $el) {
const fileInputSelector = '.my-file-input'
function setFile() {
// access file via $el.find(fileInputSelector).get(0).files[0]
}
$el.on('change', fileInputSelector, setFile)
}
This is jQuery event delegation. Here, the listener is attached to the root element of the directive. When the event is triggered, it will bubble up to the registered element and jQuery will determine if the event originated on an inner element matching the defined selector. If it does, the handler will fire.
Benefits of this method are:
ng-if
or ng-switch
)Here's a Scala 2.11.4 implementation of recursive BFS. I've sacrificed tail-call optimization for brevity, but the TCOd version is very similar. See also @snv's post.
import scala.collection.immutable.Queue
object RecursiveBfs {
def bfs[A](tree: Tree[A], target: A): Boolean = {
bfs(Queue(tree), target)
}
private def bfs[A](forest: Queue[Tree[A]], target: A): Boolean = {
forest.dequeueOption exists {
case (E, tail) => bfs(tail, target)
case (Node(value, _, _), _) if value == target => true
case (Node(_, l, r), tail) => bfs(tail.enqueue(List(l, r)), target)
}
}
sealed trait Tree[+A]
case class Node[+A](data: A, left: Tree[A], right: Tree[A]) extends Tree[A]
case object E extends Tree[Nothing]
}
vim-fugitive is versatile for that kind of examining in Vim.
Use :Ggrep
to do that. For more information you can install vim-fugitive and look up the turorial by :help Grep
. And this episode: exploring-the-history-of-a-git-repository will guide you to do all that.
The only thing that can be a null
is a non-primivite.
A boolean
which can only hold TRUE
or FALSE
is a primitive. The TRUE
/FALSE
in memory are actually numbers (0
and 1
)
0 = FALSE
1 = TRUE
So when you instantiate an object it will be null
String str; // will equal null
On the other hand if you instaniate a primitive it will be assigned to 0 default.
boolean isTrue; // will be 0
int i; // will be 0
//img[@title='Modify'][i]
is short for
/descendant-or-self::node()/img[@title='Modify'][i]
hence is returning the i'th node under the same parent node.
You want
/descendant-or-self::img[@title='Modify'][i]
onClose: function(selectedDate) {
$("#dpTodate").datepicker("option", "minDate", selectedDate);
var maxDate = new Date(selectedDate);
maxDate.setDate(maxDate.getDate() + 6); //6 days extra in from date
$("#dpTodate").datepicker("option", "maxDate", maxDate);
}
Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).
<div class="container">
<div class="row">
<div class="col-3 col-md-6">
<div class="card card-block">1</div>
</div>
<div class="col-6 col-md-12 flex-md-last">
<div class="card card-block">3</div>
</div>
<div class="col-3 col-md-6 ">
<div class="card card-block">2</div>
</div>
</div>
Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.
public static class Employee
{
public static string SomeSetting
{
get
{
return ConfigurationManager.AppSettings["SomeSetting"];
}
}
}
Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.
If you feel that you must store a reference to appsettings, try
public static class Employee
{
private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;
public static NameValueCollection AppSettings { get { return _appSettings; } }
}
It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.
Just use the following code with initializing a field
private int count = 0;
@Override
public void onBackPressed() {
count++;
if (count >=1) {
/* If count is greater than 1 ,you can either move to the next
activity or just quit. */
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();
overridePendingTransition
(R.anim.push_left_in, R.anim.push_left_out);
/* Quitting */
finishAffinity();
} else {
Toast.makeText(this, "Press back again to Leave!", Toast.LENGTH_SHORT).show();
// resetting the counter in 2s
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
count = 0;
}
}, 2000);
}
super.onBackPressed();
}
import java.util.ArrayList;
import java.util.List;
class ArrLst{
public static void main(String args[]){
List l=new ArrayList();
l.add(10);
l.add(11);
l.add(12);
l.add(13);
l.add(14);
l.forEach((a)->System.out.println(a));
}
}
This error occurs in angular when you didn't intialise the array blank.
For an example:
userlist: any[ ];
this.userlist = [ ];
or
userlist: any = [ ];
Using a Set
is your fastest option. Here is a generic function for getting a unique random that uses a callback generator. Now it's fast and reusable.
// Get a unique 'anything'_x000D_
let unique = new Set()_x000D_
_x000D_
function getUnique(generator) {_x000D_
let number = generator()_x000D_
while (!unique.add(number)) {_x000D_
number = generator()_x000D_
}_x000D_
return number;_x000D_
}_x000D_
_x000D_
// The generator. Return anything, not just numbers._x000D_
const between_1_100 = () => 1 + Math.floor(Math.random() * 100)_x000D_
_x000D_
// Test it_x000D_
for (var i = 0; i < 8; i++) {_x000D_
const aNumber = getUnique(between_1_100)_x000D_
}_x000D_
// Dump the 'stored numbers'_x000D_
console.log(Array.from(unique))
_x000D_
systemd
sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
sysvinit
sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
You could try using "typeid".
This doesn't work for "object" name but YOU know the object name so you'll just have to store it somewhere. The Compiler doesn't care what you namned an object.
Its worth bearing in mind, though, that the output of typeid is a compiler specific thing so even if it produces what you are after on the current platform it may not on another. This may or may not be a problem for you.
The other solution is to create some kind of template wrapper that you store the class name in. Then you need to use partial specialisation to get it to return the correct class name for you. This has the advantage of working compile time but is significantly more complex.
Edit: Being more explicit
template< typename Type > class ClassName
{
public:
static std::string name()
{
return "Unknown";
}
};
Then for each class somethign liek the following:
template<> class ClassName<MyClass>
{
public:
static std::string name()
{
return "MyClass";
}
};
Which could even be macro'd as follows:
#define DefineClassName( className ) \
\
template<> class ClassName<className> \
{ \
public: \
static std::string name() \
{ \
return #className; \
} \
}; \
Allowing you to, simply, do
DefineClassName( MyClass );
Finally to Get the class name you'd do the following:
ClassName< MyClass >::name();
Edit2: Elaborating further you'd then need to put this "DefineClassName" macro in each class you make and define a "classname" function that would call the static template function.
Edit3: And thinking about it ... Its obviously bad posting first thing in the morning as you may as well just define a member function "classname()" as follows:
std::string classname()
{
return "MyClass";
}
which can be macro'd as follows:
DefineClassName( className ) \
std::string classname() \
{ \
return #className; \
}
Then you can simply just drop
DefineClassName( MyClass );
into the class as you define it ...
I've written a library called AnsiScape that allows you to write coloured output in a more structured way:
Example:
AnsiScape ansiScape = new AnsiScape();
String colors = ansiScape.format("{red {blueBg Red text with blue background}} {b Bold text}");
System.out.println(colors);
The library it also allows you to define your own "escape classes" akin to css classes.
Example:
AnsiScapeContext context = new AnsiScapeContext();
// Defines a "class" for text
AnsiClass text = AnsiClass.withName("text").add(RED);
// Defines a "class" for the title used
AnsiClass title = AnsiClass.withName("title").add(BOLD, BLUE_BG, YELLOW);
// Defines a "class" to render urls
AnsiClass url = AnsiClass.withName("url").add(BLUE, UNDERLINE);
// Registering the classes to the context
context.add(text).add(title).add(url);
// Creating an AnsiScape instance with the custom context
AnsiScape ansiScape = new AnsiScape(context);
String fmt = "{title Chapter 1}\n" +
"{text So it begins:}\n" +
"- {text Option 1}\n" +
"- {text Url: {url www.someurl.xyz}}";
System.out.println(ansiScape.format(fmt));
Database:
Used for Online Transactional Processing (OLTP).
Data Warehouse:
Used for Online Analytical Processing (OLAP).
This is a clever little trick (that I think I've seen on SO before):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):
That is, with the above:
Supporting negative numbers is left as an exercise ;-)
Happy coding.
This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.
from tkinter import *
master = Tk()
def change_text():
my_var.set("Second click")
my_var = StringVar()
my_var.set("First click")
label = Label(mas,textvariable=my_var,fg="red")
button = Button(mas,text="Submit",command = change_text)
button.pack()
label.pack()
master.mainloop()
public static string ComputeSHA256Hash(string text)
{
using (var sha256 = new SHA256Managed())
{
return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
}
}
The reason why you get different results is because you don't use the same string encoding. The link you put for the on-line web site that computes SHA256 uses UTF8 Encoding, while in your example you used Unicode Encoding. They are two different encodings, so you don't get the same result. With the example above you get the same SHA256 hash of the linked web site. You need to use the same encoding also in PHP.
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Other answers here address the general question of what the proper Content-Type
for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml
and application/xml
are permissible. However, none address whether there are any rules specific to sitemaps.
Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site:
searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type
should be used for serving sitemaps.
In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type
of any other XML document - i.e. that it may be either text/xml
or application/xml
.
ArrayUtils.isNotEmpty(testArrayName)
from the package org.apache.commons.lang3
ensures Array is not null or empty
As an addition to @ANisus' answer...
below is some information from the "Go in action" book, which I think is worth mentioning:
nil
& empty
slicesIf we think of a slice like this:
[pointer] [length] [capacity]
then:
nil slice: [nil][0][0]
empty slice: [addr][0][0] // points to an address
nil slice
They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.
// Create a nil slice of integers. var slice []int
empty slice
Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.
// Use make to create an empty slice of integers. slice := make([]int, 0) // Use a slice literal to create an empty slice of integers. slice := []int{}
Regardless of whether you’re using a nil slice or an empty slice, the built-in functions
append
,len
, andcap
work the same.
package main
import (
"fmt"
)
func main() {
var nil_slice []int
var empty_slice = []int{}
fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))
}
prints:
true 0 0
false 0 0
eof() checks the eofbit in the stream state.
On each read operation, if the position is at the end of stream and more data has to be read, eofbit is set to true. Therefore you're going to get an extra character before you get eofbit=1.
The correct way is to check whether the eof was reached (or, whether the read operation succeeded) after the reading operation. This is what your second version does - you do a read operation, and then use the resulting stream object reference (which >> returns) as a boolean value, which results in check for fail().
I'm using the following configuration:
#site.yml:
- name: Example play
hosts: all
remote_user: ansible
become: yes
become_method: sudo
vars:
ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"
A. Grab file data from the file field
The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
This saves the file data to a file variable for later use.
B. Handle the file upload on submit
When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:
C. Upload the files
Quick and dirty php script to upload the files and pass back some info:
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = './uploads/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
IMP: Don't use this, write your own.
D. Handle the form submit
The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
Final note
This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.
Another:
>>> lst=[10,11,12]
>>> fmt="%i: %i"
>>> for d in enumerate(lst):
... print(fmt%d)
...
0: 10
1: 11
2: 12
Yet another form:
>>> for i,j in enumerate(lst): print "%i: %i"%(i,j)
That method is nice since the individual elements in tuples produced by enumerate can be modified such as:
>>> for i,j in enumerate([3,4,5],1): print "%i^%i: %i "%(i,j,i**j)
...
1^3: 1
2^4: 16
3^5: 243
Of course, don't forget you can get a slice from this like so:
>>> for i,j in list(enumerate(lst))[1:2]: print "%i: %i"%(i,j)
...
1: 11
I've spent 2 days attempting to convert layouts to ConstraintLayout
in the so-called "stable" release Android Studio 2.2 and I've not got ScrollView
to work in the designer. I'm not going to start down the route of adding constraints in XML for Views
that are further down the scroll. After all this is supposed to be a visual design tool.
And the number of rendering errors, stack overflows and theme issues I've had has led me to conclude that the whole ConstraintLayout
implementation is still riddled with bugs. Unless you are developing simple layouts then I'd leave it well alone until it's had a few more iterations at least.
That's 2 days I'm not going to get back.
You could try this:
string input = "lala.bla";
output = input.Split('.').Last();
type
%matplotlib qt
when you want graphs in a separate window and
%matplotlib inline
when you want an inline plot
If you want statically make columns not sortable. You can do this way
In Solution Explorer:
I use this to install add-ons like HTML editors and third-party file browsers.
I'd have to recommend NumPy as well
Not only is it faster for doing vector math, but it also has a ton of convenience functions.
If you want something even faster for 1d vectors, try vop
It's similar to MatLab, but free and stuff. Here's an example of what you'd do
from numpy import matrix
a = matrix((2,2,2))
b = matrix((1,1,1))
ret = a - b
print ret
>> [[1 1 1]]
Boom.
I defined two functions in Site.Master:
<script type="text/javascript">
var spinnerVisible = false;
function showProgress() {
if (!spinnerVisible) {
$("div#spinner").fadeIn("fast");
spinnerVisible = true;
}
};
function hideProgress() {
if (spinnerVisible) {
var spinner = $("div#spinner");
spinner.stop();
spinner.fadeOut("fast");
spinnerVisible = false;
}
};
</script>
And special section:
<div id="spinner">
Loading...
</div>
Visual style is defined in CSS:
div#spinner
{
display: none;
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
background:url(spinner.gif) no-repeat center #fff;
text-align:center;
padding:10px;
font:normal 16px Tahoma, Geneva, sans-serif;
border:1px solid #666;
margin-left: -50px;
margin-top: -50px;
z-index:2;
overflow: auto;
}
In case of hooks, you should use useEffect
hook.
const [fruit, setFruit] = useState('');
setFruit('Apple');
useEffect(() => {
console.log('Fruit', fruit);
}, [fruit])
Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.
A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.
Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.
I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.
in bootstrap use .list-inline
css class
<ul class="list-inline">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h
The JMeter docs say the following:
The summary report creates a table row for each differently named request in your test. This is similar to the Aggregate Report , except that it uses less memory. The thoughput is calculated from the point of view of the sampler target (e.g. the remote server in the case of HTTP samples). JMeter takes into account the total time over which the requests have been generated. If other samplers and timers are in the same thread, these will increase the total time, and therefore reduce the throughput value. So two identical samplers with different names will have half the throughput of two samplers with the same name. It is important to choose the sampler labels correctly to get the best results from the Report.
Times are in milliseconds.
RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.
This is a little off-topic (since Moe's answer seems complete to the OP's question), but it might be worth looking at the complexity for your whole procedure from end to end. If you're storing thing in a sorted lists (which is where a binary search would help), and then just checking for existence, you're incurring (worst-case, unless specified):
Sorted Lists
Whereas with a set()
, you're incurring
The thing a sorted list really gets you are "next", "previous", and "ranges" (including inserting or deleting ranges), which are O(1) or O(|range|), given a starting index. If you aren't using those sorts of operations often, then storing as sets, and sorting for display might be a better deal overall. set()
incurs very little additional overhead in python.
Note: The flag show-saved-copy
has been removed and the below answer will not work
You can read cached files using Chrome alone.
Chrome has a feature called Show Saved Copy Button:
Show Saved Copy Button Mac, Windows, Linux, Chrome OS, Android
When a page fails to load, if a stale copy of the page exists in the browser cache, a button will be presented to allow the user to load that stale copy. The primary enabling choice puts the button in the most salient position on the error page; the secondary enabling choice puts it secondary to the reload button. #show-saved-copy
First disconnect from the Internet to make sure that browser doesn't overwrite cache entry. Then navigate to chrome://flags/#show-saved-copy
and set flag value to Enable: Primary
. After you restart browser Show Saved Copy Button will be enabled. Now insert cached file URI into browser's address bar and hit enter. Chrome will display There is no Internet connection page alongside with Show saved copy button:
After you hit the button browser will display cached file.
Very simple and clean function to break the back arrow without interfering with the page afterward.
Benefits:
onbeforeunload
setInterval
, so it doesn't break slow browsers and always works.unbeforeunload
which interrupts user with modal dialog.Note: some of the other solutions use onbeforeunload
. Please do not use onbeforeunload
for this purpose, which pops up a dialog whenever users try to close the window, hit backarrow, etc. Modals like onbeforeunload
are usually only appropriate in rare circumstances, such as when they've actually made changes on screen and haven't saved them, not for this purpose.
How It Works
That's it. No further messing around, no background event monitoring, nothing else.
Use It In One Second
To deploy, just add this anywhere on your page or in your JavaScript code:
<script>
/* Break back button */
window.onload = function(){
var i = 0;
var previous_hash = window.location.hash;
var x = setInterval(function(){
i++;
window.location.hash = "/noop/" + i;
if (i==10){
clearInterval(x);
window.location.hash = previous_hash;
}
}, 10);
}
</script>
Ctrl-/ will insert //
style commenting, for javascript, etc
Ctrl-/ will insert <!-- -->
comments for HTML,
Ctrl-/ will insert #
comments for Ruby,
..etc
But does not work perfectly on HTML <script>
tags.
HTML <script> ..blah.. </script>
tags:
Ctrl-/ twice
(ie Ctrl-/Ctrl-/) will effectively comment out the line:
//
to the beginning of the line,//
" text to your webpage. <!-- -->
style comments, which accomplishes the task.Ctrl--Shift-/ does not produce multi-line comments on HTML (or even single line comments), but does
add /* */
style multi-line comments in Javascript, text, and other file formats.
--
[I added as a new answer since I could not add comments.
I included this info because this is the info I was looking for, and this is the only related StackOverflow page from my search results.
I since discovered the / / trick for HTML script tags and decided to share this additional information, since it requires a slight variation of the usual catch-all (and reported above)
/ and Ctrl--Shift-/ method of commenting out one's code in sublime.]
Using float does not work.
DECLARE @t1 datetime, @t2 datetime
SELECT @t1 = '19000101 23:55:00', @t2 = '20001102 23:55:00'
SELECT CAST(@t1 as float) - floor(CAST(@t1 as float)), CAST(@t2 as float) - floor(CAST(@t2 as float))
You'll see that the values are not the same (SQL Server 2005). I wanted to use this method to check for times around midnight (the full method has more detail) in which I was comparing the current time for being between 23:55:00 and 00:05:00.
Because it hasn't been mentioned yet, this was the solution for me:
I had this error with a DLL after creating a new configuration for my project. I had to go to Project Properties -> Configuration Properties -> General
and change the Configuration Type
to Dynamic Library (.dll)
.
So if you're still having trouble after trying everything else, it's worth checking to see if the configuration type is what you expect for your project. If it's not set correctly, the compiler will be looking for the wrong main symbol. In my case, it was looking for WinMain
instead of DllMain
.
As described in Documentation Environment.getExternalStorageDirectory() :
Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.
This is an example of how to use it reading an image :
String fileName = "stored_image.jpg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";
File f = new File(pathDir + File.separator + fileName);
if(f.exists()){
Log.d("Application", "The file " + file.getName() + " exists!";
}else{
Log.d("Application", "The file no longer exists!";
}
The best way to get the id of the entity you added is like this:
public int InsertEntity(Entity factor)
{
Db.Entities.Add(factor);
Db.SaveChanges();
var id = factor.id;
return id;
}
In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.
So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:
CREATE OR REPLACE TYPE array is table of number;
/
Then you can use it as in these two examples within PL/SQL:
SQL> l
1 declare
2 p array := array();
3 begin
4 for i in (select level from dual connect by level < 10) loop
5 p.extend;
6 p(p.count) := i.level;
7 end loop;
8 for x in (select column_value from table(cast(p as array))) loop
9 dbms_output.put_line(x.column_value);
10 end loop;
11* end;
SQL> /
1
2
3
4
5
6
7
8
9
PL/SQL procedure successfully completed.
SQL> l
1 declare
2 p array := array();
3 begin
4 select level bulk collect into p from dual connect by level < 10;
5 for x in (select column_value from table(cast(p as array))) loop
6 dbms_output.put_line(x.column_value);
7 end loop;
8* end;
SQL> /
1
2
3
4
5
6
7
8
9
PL/SQL procedure successfully completed.
Additional example based on comments
Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.
CREATE OR REPLACE PACKAGE p_cache AS
FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/
CREATE OR REPLACE PACKAGE BODY p_cache AS
cache_array array;
FUNCTION get_p_cursor RETURN sys_refcursor IS
pCursor sys_refcursor;
BEGIN
OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
RETURN pCursor;
END get_p_cursor;
-- Package initialization runs once in each session that references the package
BEGIN
SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
END p_cache;
/
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
When I tried git pull heroku master
, I got an error fatal: refusing to merge unrelated histories
.
So I tried git pull heroku master --allow-unrelated-histories
and it worked for me
It's simpler to use numpy
from my opinion:
import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)
Results:
For detailed parameter information, check here: numpy.add
You should really use generics and the enhanced for loop for this:
Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");
for (Integer key : hm.keySet()) {
System.out.println(key);
System.out.println(hm.get(key));
}
Or the entrySet()
version:
Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");
for (Map.Entry<Integer, String> e : hm.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}
The problem is that you invoked Undefined Behaviour.
When you invoke UB anything can happen.
The assignments are ok; there is an implicit conversion in the first line
int x = 0xFFFFFFFF;
unsigned int y = 0xFFFFFFFF;
However, the call to printf
, is not ok
printf("%d, %d, %u, %u", x, y, x, y);
It is UB to mismatch the %
specifier and the type of the argument.
In your case you specify 2 int
s and 2 unsigned int
s in this order by provide 1 int
, 1 unsigned int
, 1 int
, and 1 unsigned int
.
Don't do UB!
My solution was to add a UIView
with height of 20 points on top of the window when on iOS 7.
Then I created a method in my AppDelegate class to show/hide the "solid" status bar background. In application:didFinishLaunchingWithOptions:
:
// ...
// Add a status bar background
self.statusBarBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.window.bounds.size.width, 20.0f)];
self.statusBarBackground.backgroundColor = [UIColor blackColor];
self.statusBarBackground.alpha = 0.0;
self.statusBarBackground.userInteractionEnabled = NO;
self.statusBarBackground.layer.zPosition = 999; // Position its layer over all other views
[self.window addSubview:self.statusBarBackground];
// ...
return YES;
Then I created a method to fade in/out the black status bar background:
- (void) showSolidStatusBar:(BOOL) solidStatusBar
{
[UIView animateWithDuration:0.3f animations:^{
if(solidStatusBar)
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
self.statusBarBackground.alpha = 1.0f;
}
else
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
self.statusBarBackground.alpha = 0.0f;
}
}];
}
All I have to do now is call is [appDelegate showSolidStatusBar:YES]
when needed.
I don't think location.LatLng
is working, however this works:
results[0].geometry.location.lat(), results[0].geometry.location.lng()
Found it while exploring Get Lat Lon source code.
Navigate to the folder in Windows Explorer, highlight the complete folder path in the top pane and type "cmd" - voila!
Another option, how to achieve this, is by using pandas.DataFrame.query()
method. Let me show you an example on the following data frame called df
.
>>> df = pd.DataFrame(np.random.random((5, 1)), columns=['col_1'])
>>> df['date'] = pd.date_range('2020-1-1', periods=5, freq='D')
>>> print(df)
col_1 date
0 0.015198 2020-01-01
1 0.638600 2020-01-02
2 0.348485 2020-01-03
3 0.247583 2020-01-04
4 0.581835 2020-01-05
As an argument, use the condition for filtering like this:
>>> start_date, end_date = '2020-01-02', '2020-01-04'
>>> print(df.query('date >= @start_date and date <= @end_date'))
col_1 date
1 0.244104 2020-01-02
2 0.374775 2020-01-03
3 0.510053 2020-01-04
If you do not want to include boundaries, just change the condition like following:
>>> print(df.query('date > @start_date and date < @end_date'))
col_1 date
2 0.374775 2020-01-03
The child can only take a height if the parent has one already set. See this exaple : Vertical Scrolling 100% height
html, body {
height: 100%;
margin: 0;
}
.header{
height: 10%;
background-color: #a8d6fe;
}
.middle {
background-color: #eba5a3;
min-height: 80%;
}
.footer {
height: 10%;
background-color: #faf2cc;
}
$(function() {_x000D_
$('a[href*="#nav-"]').click(function() {_x000D_
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {_x000D_
var target = $(this.hash);_x000D_
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');_x000D_
if (target.length) {_x000D_
$('html, body').animate({_x000D_
scrollTop: target.offset().top_x000D_
}, 500);_x000D_
return false;_x000D_
}_x000D_
}_x000D_
});_x000D_
});
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.header {_x000D_
height: 100%;_x000D_
background-color: #a8d6fe;_x000D_
}_x000D_
.middle {_x000D_
background-color: #eba5a3;_x000D_
min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
height: 100%;_x000D_
background-color: #faf2cc;_x000D_
}_x000D_
nav {_x000D_
position: fixed;_x000D_
top: 10px;_x000D_
left: 0px;_x000D_
}_x000D_
nav li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#nav-a">got to a</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#nav-b">got to b</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#nav-c">got to c</a>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>_x000D_
<div class="header" id="nav-a">_x000D_
_x000D_
</div>_x000D_
<div class="middle" id="nav-b">_x000D_
_x000D_
</div>_x000D_
<div class="footer" id="nav-c">_x000D_
_x000D_
</div>
_x000D_
You must ensure the URL contains embed rather watch as the /embed
endpoint allows outside requests, whereas the /watch
endpoint does not.
<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
body {
margin: 0;
padding: 0;
background: url('img/background.jpg') repeat;
}
body:before {
content: " ";
width: 100%;
height: 100%;
position: absolute;
z-index: -1;
top: 0;
left: 0;
background: -webkit-radial-gradient(top center, ellipse cover, rgba(255,255,255,0.2) 0%,rgba(0,0,0,0.5) 100%);
}
PLEASE NOTE: This only using webkit so it will only work in webkit browsers.
try :
-moz-linear-gradient = (Firefox)
-ms-linear-gradient = (IE)
-o-linear-gradient = (Opera)
-webkit-linear-gradient = (Chrome & safari)
How was your 2D array declared?
If it something like:
int arr[20][30];
You can zero it by doing:
memset(arr, sizeof(int)*20*30);
Window.Show will show the window, and continue execution -- it's a non-blocking call.
Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).
[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.
For this specific problem, something like this would work:
$ sed 's/^ *//g' < input.txt > output.txt
It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:
$ sed 's/^[ \t]+//g' < input.txt > output.txt
The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.
Finally, instead of < input.txt > output.txt
you can use the -i
option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.
One question is if you also want to use git for the deploment of your projects. If so you probably would like to exclude your local sqlite file from the repository, same probably applies to file uploads (mostly in your media folder). (I'm talking about django now, since your question is also tagged with django)
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
It is more effecient to convert CString
to std::string
using the conversion where the length is specified.
CString someStr("Hello how are you");
std::string std(somStr, someStr.GetLength());
In tight loop this makes a significant performance improvement.
In addition to using Request.Form
and Request.QueryString
and depending on your specific scenario, it may also be useful to check the Page
's IsPostBack
property.
if (Page.IsPostBack)
{
// HTTP Post
}
else
{
// HTTP Get
}
According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.
Assuming that you would really want your loop to run 24/7 as a background service
For a solution that doesn't involve injecting your code with libraries, you can simply create a service template, since you are using linux:
[Unit]
Description = <Your service description here>
After = network.target # Assuming you want to start after network interfaces are made available
[Service]
Type = simple
ExecStart = python <Path of the script you want to run>
User = # User to run the script as
Group = # Group to run the script as
Restart = on-failure # Restart when there are errors
SyslogIdentifier = <Name of logs for the service>
RestartSec = 5
TimeoutStartSec = infinity
[Install]
WantedBy = multi-user.target # Make it accessible to other users
Place that file in your daemon service folder (usually /etc/systemd/system/
), in a *.service
file, and install it using the following systemctl commands (will likely require sudo privileges):
systemctl enable <service file name without .service extension>
systemctl daemon-reload
systemctl start <service file name without .service extension>
You can then check that your service is running by using the command:
systemctl | grep running
// dict is Dictionary<string, Foo>
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
// or in C# 3.0:
var foos = dict.Values.ToArray();
If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:
In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.
At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.
To dismiss or cancel AlertDialog.Builder
dialog.setNegativeButton("?????", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
you call dismiss() on the dialog interface
From the OPENQUERY documentation it states that:
OPENQUERY does not accept variables for its arguments.
See this article for a workaround.
UPDATE:
As suggested, I'm including the recommendations from the article below.
Pass Basic Values
When the basic Transact-SQL statement is known, but you have to pass in one or more specific values, use code that is similar to the following sample:
DECLARE @TSQL varchar(8000), @VAR char(2)
SELECT @VAR = 'CA'
SELECT @TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + @VAR + ''''''')'
EXEC (@TSQL)
Pass the Whole Query
When you have to pass in the whole Transact-SQL query or the name of the linked server (or both), use code that is similar to the following sample:
DECLARE @OPENQUERY nvarchar(4000), @TSQL nvarchar(4000), @LinkedServer nvarchar(4000)
SET @LinkedServer = 'MyLinkedServer'
SET @OPENQUERY = 'SELECT * FROM OPENQUERY('+ @LinkedServer + ','''
SET @TSQL = 'SELECT au_lname, au_id FROM pubs..authors'')'
EXEC (@OPENQUERY+@TSQL)
Use the Sp_executesql Stored Procedure
To avoid the multi-layered quotes, use code that is similar to the following sample:
DECLARE @VAR char(2)
SELECT @VAR = 'CA'
EXEC MyLinkedServer.master.dbo.sp_executesql
N'SELECT * FROM pubs.dbo.authors WHERE state = @state',
N'@state char(2)',
@VAR
This is easily done by replacing the frame's content pane with a JPanel which draws your image:
try {
final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
setContentPane(new JPanel(new BorderLayout()) {
@Override public void paintComponent(Graphics g) {
g.drawImage(backgroundImage, 0, 0, null);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
This example also sets the panel's layout to BorderLayout to match the default content pane layout.
(If you have any trouble seeing the image, you might need to call setOpaque(false)
on some other components so that you can see through to the background.)
Updated on March 21 2019
Add GuzzleHttp
package using composer require guzzlehttp/guzzle:~6.3.3
Or you can specify Guzzle as a dependency in your project's composer.json
{
"require": {
"guzzlehttp/guzzle": "~6.3.3"
}
}
Include below line in the top of the class where you are calling the API
use GuzzleHttp\Client;
Add below code for making the request
$client = new Client();
$res = $client->request('POST', 'http://www.exmple.com/mydetails', [
'form_params' => [
'name' => 'george',
]
]);
if ($res->getStatusCode() == 200) { // 200 OK
$response_data = $res->getBody()->getContents();
}
The simplest solution might be to install Java 8 in parallel to Java 9 (if not still still existant) and specify the JVM to be used explicitly in eclipse.ini
. You can find a description of this setting including a description how to find eclipse.ini
on a Mac at Eclipsepedia
if ( ( single conditional expression A )
&& ( single conditional expression B )
&& ( single conditional expression C )
)
{
opAllABC();
}
else
{
opNoneABC();
}
Formatting a multiple conditional expressions in an if-else statement this way:
// disable any single conditional test with just a pre-pended '//'
// set a break point before any individual test
// syntax '(1 &&' and '(0 ||' usually never creates any real code
if ( 1
&& ( single conditional expression A )
&& ( single conditional expression B )
&& ( 0
|| ( single conditional expression C )
|| ( single conditional expression D )
)
)
{
... ;
}
else
{
... ;
}
<?
print_r(getDatesFromRange( '2010-10-01', '2010-10-05' ));
function getDatesFromRange($startDate, $endDate)
{
$return = array($startDate);
$start = $startDate;
$i=1;
if (strtotime($startDate) < strtotime($endDate))
{
while (strtotime($start) < strtotime($endDate))
{
$start = date('Y-m-d', strtotime($startDate.'+'.$i.' days'));
$return[] = $start;
$i++;
}
}
return $return;
}
Something like the following should result in each data frame as a separate element in a single list:
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)
This assumes that you have those CSVs in a single directory--your current working directory--and that all of them have the lower-case extension .csv
.
If you then want to combine those data frames into a single data frame, see the solutions in other answers using things like do.call(rbind,...)
, dplyr::bind_rows()
or data.table::rbindlist()
.
If you really want each data frame in a separate object, even though that's often inadvisable, you could do the following with assign
:
temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))
Or, without assign
, and to demonstrate (1) how the file name can be cleaned up and (2) show how to use list2env
, you can try the following:
temp = list.files(pattern="*.csv")
list2env(
lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))),
read.csv), envir = .GlobalEnv)
But again, it's often better to leave them in a single list.