Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?
For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization
(https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.
Example python implementation:
import sys
inner_loop = 0
def collatz_sequence(N, cache):
global inner_loop
l = [ ]
stop = False
n = N
tails = [ ]
while not stop:
inner_loop += 1
tmp = n
l.append(n)
if n <= 1:
stop = True
elif n in cache:
stop = True
elif n % 2:
n = 3*n + 1
else:
n = n // 2
tails.append((tmp, len(l)))
for key, offset in tails:
if not key in cache:
cache[key] = l[offset:]
return l
def gen_sequence(l, cache):
for elem in l:
yield elem
if elem in cache:
yield from gen_sequence(cache[elem], cache)
raise StopIteration
if __name__ == "__main__":
le_cache = {}
for n in range(1, 4711, 5):
l = collatz_sequence(n, le_cache)
print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))
print("inner_loop = {}".format(inner_loop))
Saving binary data as file using JavaScript from a browser
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
_x000D_
_x000D_
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
json: cannot unmarshal object into Go value of type
You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.
Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.
WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)
I believe I have encountered the same quandary. I started encountering the problem when I changed to:
</system.web>
<httpRuntime targetFramework="4.5"/>
Which gives the error message you describe above.
adding:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
Solves the issue, but then it makes your validation controls/scripts throw Javascript runtime errors.
If you change to:
</system.web>
<httpRuntime targetFramework="4.0"/>
You should be OK, but you’ll have to make sure the rest of your code does/ behaves as desired. You might also have to forgo some new features only available in 4.5 onward.
P.S. It is highly recommended that you read the following before implementing this solution. Especially, if you use Async functionality:
https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/
UPDATE April 2017:
After some some experimentation and testing I have come up with a combination that works:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<httpRuntime targetFramework="4.5.1" />
with:
jQuery version 1.11.3
fetch in git doesn't get all branches
I had this issue today on a repo.
It wasn't the +refs/heads/*:refs/remotes/origin/*
issue as per top solution.
Symptom was simply that git fetch origin
or git fetch
just didn't appear to do anything, although there were remote branches to fetch.
After trying lots of things, I removed the origin remote, and recreated it. That seems to have fixed it. Don't know why.
remove with:
git remote rm origin
and recreate with:
git remote add origin <git uri>
How to convert image into byte array and byte array to base64 String in android?
here is another solution...
System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];
System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
m.Write (buffer, 0, buffer.Length);
}
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();
hope it helps!
CSS3 background image transition
You can use pseudo element to get the effect you want like I did in that Fiddle.
CSS:
.title a {
display: block;
width: 340px;
height: 338px;
color: black;
position: relative;
}
.title a:after {
background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
content: "";
opacity: 0;
width: inherit;
height: inherit;
position: absolute;
top: 0;
left: 0;
/* TRANSISITION */
transition: opacity 1s ease-in-out;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
}
.title a:hover:after{
opacity: 1;
}
HTML:
<div class="title">
<a href="#">HYPERLINK</a>
</div>
How to place object files in separate subdirectory
None of these answers seemed simple enough - the crux of the problem is not having to rebuild:
makefile
OBJDIR=out
VPATH=$(OBJDIR)
# make will look in VPATH to see if the target needs to be rebuilt
test: moo
touch $(OBJDIR)/$@
example use
touch moo
# creates out/test
make test
# doesn't update out/test
make test
# will now update test
touch moo
make test
Use jQuery to scroll to the bottom of a div with lots of text
Scrolling with animation:
Your DIV:
<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>
jQuery part:
jQuery(document).ready(function(){
var $t = $('.messageScrollArea');
$t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});
?http://jsfiddle.net/3Wx3U/
Python base64 data decode
base64 encode/decode example:
import base64
mystr = 'O João mordeu o cão!'
# Encode
mystr_encoded = base64.b64encode(mystr.encode('utf-8'))
# b'TyBKb8OjbyBtb3JkZXUgbyBjw6NvIQ=='
# Decode
mystr_encoded = base64.b64decode(mystr_encoded).decode('utf-8')
# 'O João mordeu o cão!'
how to prevent "directory already exists error" in a makefile when using mkdir
Here is a trick I use with GNU make for creating compiler-output directories. First define this rule:
%/.d:
mkdir -p $(@D)
touch $@
Then make all files that go into the directory dependent on the .d file in that directory:
obj/%.o: %.c obj/.d
$(CC) $(CFLAGS) -c -o $@ $<
Note use of $< instead of $^.
Finally prevent the .d files from being removed automatically:
.PRECIOUS: %/.d
Skipping the .d file, and depending directly on the directory, will not work, as the directory modification time is updated every time a file is written in that directory, which would force rebuild at every invocation of make.
Local variable referenced before assignment?
Put a global statement at the top of your function and you should be good:
def onLoadFinished(result):
global feed
...
To demonstrate what I mean, look at this little test:
x = 0
def t():
x += 1
t()
this blows up with your exact same error where as:
x = 0
def t():
global x
x += 1
t()
does not.
The reason for this is that, inside t
, Python thinks that x
is a local variable. Furthermore, unless you explicitly tell it that x
is global, it will try to use a local variable named x
in x += 1
. But, since there is no x
defined in the local scope of t
, it throws an error.
Duplicating a MySQL table, indices, and data
To create table structure only use this below code :
CREATE TABLE new_table LIKE current_table;
To copy data from table to another use this below code :
INSERT INTO new_table SELECT * FROM current_table;
Find OpenCV Version Installed on Ubuntu
To install this product you can see this tutorial: OpenCV on Ubuntu
There are listed the packages you need. So, with:
# dpkg -l | grep libcv2
# dpkg -l | grep libhighgui2
and more listed in the url you can find which packages are installed.
With
# dpkg -L libcv2
you can check where are installed
This operative is used for all debian packages.
How to implement the Softmax function in Python
I would say that while both are correct mathematically, implementation-wise, first one is better. When computing softmax, the intermediate values may become very large. Dividing two large numbers can be numerically unstable. These notes (from Stanford) mention a normalization trick which is essentially what you are doing.
Oracle - How to create a materialized view with FAST REFRESH and JOINS
To start with, from the Oracle Database Data Warehousing Guide:
Restrictions on Fast Refresh on Materialized Views with Joins Only
...
- Rowids of all the tables in the FROM list must appear in the SELECT
list of the query.
This means that your statement will need to look something like this:
CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.*, V.ROWID as V_ROWID, P.ROWID as P_ROWID
FROM TPM_PROJECTVERSION V,
TPM_PROJECT P
WHERE P.PROJECTID = V.PROJECTID
Another key aspect to note is that your materialized view logs must be created as with rowid
.
Below is a functional test scenario:
CREATE TABLE foo(foo NUMBER, CONSTRAINT foo_pk PRIMARY KEY(foo));
CREATE MATERIALIZED VIEW LOG ON foo WITH ROWID;
CREATE TABLE bar(foo NUMBER, bar NUMBER, CONSTRAINT bar_pk PRIMARY KEY(foo, bar));
CREATE MATERIALIZED VIEW LOG ON bar WITH ROWID;
CREATE MATERIALIZED VIEW foo_bar
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT AS SELECT foo.foo,
bar.bar,
foo.ROWID AS foo_rowid,
bar.ROWID AS bar_rowid
FROM foo, bar
WHERE foo.foo = bar.foo;
How can I set Image source with base64
img = new Image();
img.src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
img.outerHTML;
"<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">"
Click a button with XPath containing partial id and title in Selenium IDE
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
Use Robocopy to copy only changed files?
To answer all your questions:
Can I use ROBOCOPY for this?
Yes, RC should fit your requirements (simplicity, only copy what needed)
What exactly does it mean to exclude?
It will exclude copying - RC calls it skipping
Would the /XO
option copy only newer files, not files of the same age?
Yes, RC will only copy newer files. Files of the same age will be skipped.
(the correct command would be robocopy C:\SourceFolder D:\DestinationFolder ABC.dll /XO
)
Maybe in your case using the /MIR
option could be useful. In general RC is rather targeted at directories and directory trees than single files.
Using Ajax.BeginForm with ASP.NET MVC 3 Razor
Example:
Model:
public class MyViewModel
{
[Required]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content("Thanks", "text/html");
}
}
View:
@model AppName.Models.MyViewModel
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<div id="result"></div>
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
<input type="submit" value="OK" />
}
and here's a better (in my perspective) example:
View:
@model AppName.Models.MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>
<div id="result"></div>
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
<input type="submit" value="OK" />
}
index.js
:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
which can be further enhanced with the jQuery form plugin.
How to copy file from host to container using Dockerfile
Use COPY command like this:
COPY foo.txt /data/foo.txt
# where foo.txt is the relative path on host
# and /data/foo.txt is the absolute path in the image
read more details for COPY in the official documentation
An alternative would be to use ADD but this is not the best practise if you dont want to use some advanced features of ADD like decompression of tar.gz files.If you still want to use ADD command, do it like this:
ADD abc.txt /data/abc.txt
# where abc.txt is the relative path on host
# and /data/abc.txt is the absolute path in the image
read more details for ADD in the official documentation
Android Center text on canvas
Try the following:
Paint textPaint = new Paint();
textPaint.setTextAlign(Paint.Align.CENTER);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);
How to increment variable under DOS?
A little bit late for the party, but it's an interessting question.
You can write your own inc.bat for incrementing a number.
It can increment numbers from 0 to 9998.
@echo off
if "%1"==":inc" goto :increment
call %0 :inc %counter0%
set counter0=%_cnt%
if %_overflow%==0 goto :exit
call %0 :inc %counter1%
set counter1=%_cnt%
if %_overflow%==0 goto :exit
call %0 :inc %counter2%
set counter2=%_cnt%
if %_overflow%==0 goto :exit
call %0 :inc %counter3%
set counter3=%_cnt%
goto :exit
:increment
set _overflow=0
set _cnt=%2
if "%_cnt%"=="" set _cnt=0
if %_cnt%==9 goto :overflow
if %_cnt%==8 set _cnt=9
if %_cnt%==7 set _cnt=8
if %_cnt%==6 set _cnt=7
if %_cnt%==5 set _cnt=6
if %_cnt%==4 set _cnt=5
if %_cnt%==3 set _cnt=4
if %_cnt%==2 set _cnt=3
if %_cnt%==1 set _cnt=2
if %_cnt%==0 set _cnt=1
goto :exit
:overflow
set _cnt=0
set _overflow=1
goto :exit
:exit
set count=%counter3%%counter2%%counter1%%counter0%
A sample for using it is here
@echo off
set counter0=0
set counter1=
set counter2=
set counter3=
:loop
call inc.bat
echo %count%
if not %count%==250 goto :loop
Check if passed argument is file or directory in Bash
Using the "file" command may be useful for this:
#!/bin/bash
check_file(){
if [ -z "${1}" ] ;then
echo "Please input something"
return;
fi
f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
echo "DIRECTORY FOUND ($result) ";
else
echo "FILE FOUND ($result) ";
fi
}
check_file "${1}"
Output examples :
$ ./f.bash login
DIRECTORY FOUND (login: directory)
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or directory))
$ ./f.bash evil.php
FILE FOUND (evil.php: PHP script, ASCII text)
FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:
#!/bin/bash
check_file(){
local file="${1}"
[[ -s "${file}" ]] || { echo "is not valid"; return; }
[[ -d "${file}" ]] && { echo "is a directory"; return; }
[[ -f "${file}" ]] && { echo "is a file"; return; }
}
check_file ${1}
What is offsetHeight, clientHeight, scrollHeight?
My descriptions for the three:
- offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's
position: absolute
descendents)
- clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
- scrollHeight: How much space is needed to see all of the element's content/descendents (including
position: absolute
ones) without scrolling.
Then there is also:
SQL - Rounding off to 2 decimal places
Could you not cast your result as numeric(x,2)
? Where x <= 38
select
round(630/60.0,2),
cast(round(630/60.0,2) as numeric(36,2))
Returns
10.500000 10.50
How do I clone a generic list in C#?
For a deep copy, ICloneable is the correct solution, but here's a similar approach to ICloneable using the constructor instead of the ICloneable interface.
public class Student
{
public Student(Student student)
{
FirstName = student.FirstName;
LastName = student.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
// wherever you have the list
List<Student> students;
// and then where you want to make a copy
List<Student> copy = students.Select(s => new Student(s)).ToList();
you'll need the following library where you make the copy
using System.Linq
you could also use a for loop instead of System.Linq, but Linq makes it concise and clean. Likewise you could do as other answers have suggested and make extension methods, etc., but none of that is necessary.
Resize a picture to fit a JLabel
public static void main(String s[])
{
BufferedImage image = null;
try
{
image = ImageIO.read(new File("your image path"));
} catch (Exception e)
{
e.printStackTrace();
}
ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
jLabel1.setIcon(imageIcon);
}
private Image fitimage(Image img , int w , int h)
{
BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedimage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0,w,h,null);
g2.dispose();
return resizedimage;
}
Is there a wikipedia API just for retrieve content summary?
My approach was as follows (in PHP):
$url = "whatever_you_need"
$html = file_get_contents('https://en.wikipedia.org/w/api.php?action=opensearch&search='.$url);
$utf8html = html_entity_decode(preg_replace("/U\+([0-9A-F]{4})/", "&#x\\1;", $html), ENT_NOQUOTES, 'UTF-8');
$utf8html
might need further cleaning, but that's basically it.
PHP - auto refreshing page
you can use
<meta http-equiv="refresh" content="10" >
just add it after the head tags
where 10 is the time your page will refresh itself
Java Project: Failed to load ApplicationContext
I've faced this issue because during bootstrapping my spring project
using the class that implements ApplicationListener<ContextRefreshedEvent>
and inside onApplicationEvent
function it throws an exception
so make sure that your application bootstrap points do not throw any exception
in my case, I was using maven surefire plugin for testing so to debug the test process use this command
mvn -Dmaven.surefire.debug test
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
Inline elements shifting when made bold on hover
What about this? A javascript - CSS3 free solution.
http://jsfiddle.net/u1aks77x/1/
ul{}
li{float:left; list-style-type:none; }
a{position:relative; padding-right: 10px; text-decoration:none;}
a > .l1{}
a:hover > .l1{visibility:hidden;}
a:hover > .l2{display:inline;}
a > .l2{position: absolute; left:0; font-weight:bold; display:none;}
<ul>
<li><a href="/" title="Home"><span class="l1">Home</span><span class="l2">Home</span></a></li>
<li><a href="/" title="Contact"><span class="l1">Contact</span><span class="l2">Contact</span></a></li>
<li><a href="/" title="Sitemap"><span class="l1">Sitemap</span><span class="l2">Sitemap</span></a></li>
</ul>
Case Function Equivalent in Excel
I understand that this is a response to an old post-
I like the If() function combined with Index()/Match():
=IF(B2>0,"x",INDEX($H$2:$I$9,MATCH(A2,$H$2:$H$9,0),2))
The if function compare what is in column b and if it is greater than 0, it returns x, if not it uses the array (table of information) identified by the Index() function and selected by Match() to return the value that a corresponds to.
The Index array has the absolute location set $H$2:$I$9
(the dollar signs) so that the place it points to will not change as the formula is copied. The row with the value that you want returned is identified by the Match() function. Match() has the added value of not needing a sorted list to look through that Vlookup() requires. Match() can find the value with a value: 1 less than, 0 exact, -1 greater than. I put a zero in after the absolute Match() array $H$2:$H$9
to find the exact match. For the column that value of the Index() array that one would like returned is entered. I entered a 2 because in my array the return value was in the second column. Below my index array looked like this:
32 1420
36 1650
40 1790
44 1860
55 2010
The value in your 'a' column to search for in the list is in the first column in my example and the corresponding value that is to be return is to the right. The look up/reference table can be on any tab in the work book - or even in another file. -Book2 is the file name, and Sheet2 is the 'other tab' name.
=IF(B2>0,"x",INDEX([Book2]Sheet2!$A$1:$B$8,MATCH(A2,[Book2]Sheet2!$A$1:$A$8,0),2))
If you do not want x return when the value of b is greater than zero delete the x for a 'blank'/null equivalent or maybe put a 0 - not sure what you would want there.
Below is beginning of the function with the x deleted.
=IF(B2>0,"",INDEX...
How can I install a previous version of Python 3 in macOS using homebrew?
Short Answer
To make a clean install of Python 3.6.5 use:
brew unlink python # ONLY if you have installed (with brew) another version of python 3
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb
If you prefer to recover a previously installed version, then:
brew info python # To see what you have previously installed
brew switch python 3.x.x_x # Ex. 3.6.5_1
Long Answer
There are two formulas for installing Python with Homebrew: python@2
and python
.
The first is for Python 2 and the second for Python 3.
Note: You can find outdated answers on the web where it is mentioned python3
as the formula name for installing Python version 3. Now it's just python
!
By default, with these formulas you can install the latest version of the corresponding major version of Python. So, you cannot directly install a minor version like 3.6.
Solution
With brew
, you can install a package using the address of the formula, for example in a git repository.
brew install https://the/address/to/the/formula/FORMULA_NAME.rb
Or specifically for Python 3
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/COMMIT_IDENTIFIER/Formula/python.rb
The address you must specify is the address to the last commit of the formula (python.rb) for the desired version.
You can find the commint identifier by looking at the history for homebrew-core/Formula/python.rb
https://github.com/Homebrew/homebrew-core/commits/master/Formula/python.rb
Python > 3.6.5
In the link above you will not find a formula for a version of Python above 3.6.5.
After the maintainers of that (official) repository released Python 3.7, they only submit updates to the recipe of Python 3.7.
As explained above, with homebrew you have only Python 2 (python@2) and Python 3 (python), there is no explicit formula for Python 3.6.
Although those minor updates are mostly irrelevant in most cases and for most users, I will search if someone has done an explicit formula for 3.6.
XMLHttpRequest (Ajax) Error
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open()
because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send()
. Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml
file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
How to convert a NumPy array to PIL image applying matplotlib colormap
- input = numpy_image
- np.unit8 -> converts to integers
- convert('RGB') -> converts to RGB
Image.fromarray -> returns an image object
from PIL import Image
import numpy as np
PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
Is there a maximum number you can set Xmx to when trying to increase jvm memory?
Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):
peregrino:$ java -Xmx4096M -cp bin WheelPrimes
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.
peregrino:$ java -Xmx4095M -cp bin WheelPrimes
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified
peregrino:$ java -Xmx4092M -cp bin WheelPrimes
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size
peregrino:$ java -Xmx4000M -cp bin WheelPrimes
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
(experiment reducing from 4000M until)
peregrino:$ java -Xmx2686M -cp bin WheelPrimes
(normal execution)
Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.
What's the difference between returning value or Promise.resolve from then()
In simple terms, inside a then
handler function:
A) When x
is a value (number, string, etc):
return x
is equivalent to return Promise.resolve(x)
throw x
is equivalent to return Promise.reject(x)
B) When x
is a Promise that is already settled (not pending anymore):
return x
is equivalent to return Promise.resolve(x)
, if the Promise was already resolved.
return x
is equivalent to return Promise.reject(x)
, if the Promise was already rejected.
C) When x
is a Promise that is pending:
return x
will return a pending Promise, and it will be evaluated on the subsequent then
.
Read more on this topic on the Promise.prototype.then() docs.
Apply style ONLY on IE
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
#myElement {
/* Enter your style code */
}
}
Explanation: It is a Microsoft-specific media query. Using -ms-high-contrast property specific to Microsoft IE, it will only be parsed in Internet Explorer 10 or greater. I have used both the valid values of the media query, so it will be parsed by IE only, whether the user has high contrast enabled or not.
Insert a string at a specific index
Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:
var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
Git pushing to remote branch
First, let's note that git push
"wants" two more arguments and will make them up automatically if you don't supply them. The basic command is therefore git push remote refspec
.
The remote
part is usually trivial as it's almost always just the word origin
. The trickier part is the refspec
. Most commonly, people write a branch name here: git push origin master
, for instance. This uses your local branch to push to a branch of the same name1 on the remote, creating it if necessary. But it doesn't have to be just a branch name.
In particular, a refspec
has two colon-separated parts. For git push
, the part on the left identifies what to push,2 and the part on the right identifies the name to give to the remote. The part on the left in this case would be branch_name
and the part on the right would be branch_name_test
. For instance:
git push origin foo:foo_test
As you are doing the push, you can tell your git push
to set your branch's upstream name at the same time, by adding -u
to the git push
options. Setting the upstream name makes your git save the foo_test
(or whatever) name, so that a future git push
with no arguments, while you're on the foo
branch, can try to push to foo_test
on the remote (git also saves the remote, origin
in this case, so that you don't have to enter that either).
You need only pass -u
once: it basically just runs git branch --set-upstream-to
for you. (If you pass -u
again later, it re-runs the upstream-setting, changing it as directed; or you can run git branch --set-upstream-to
yourself.)
However, if your git is 2.0 or newer, and you have not set any special configuration, you will run into the same kind of thing that had me enter footnote 1 above: push.default
will be set to simple
, which will refuse to push because the upstream's name differs from your own local name. If you set push.default
to upstream
, git will stop complaining—but the simplest solution is just to rename your local branch first, so that the local and remote names match. (What settings to set, and/or whether to rename your branch, are up to you.)
1More precisely, git consults your remote.remote.push
setting to derive the upstream half of the refspec. If you haven't set anything here, the default is to use the same name.
2This doesn't have to be a branch name. For instance, you can supply HEAD
, or a commit hash, here. If you use something other than a branch name, you may have to spell out the full refs/heads/branch
on the right, though (it depends on what names are already on the remote).
REST API - why use PUT DELETE POST GET?
Good Semantics is important in programming.
Utilizing more methods besides GET/POST will be helpful because it will increase the readability of your code and make it easier to maintain.
Why?
Because you know GET will retrieve data from your api. You know POST will add new data to your system. You know PUT will make updates. DELETE will delete rows etc, etc,
I normally structure my RESTFUL Web Services so that I have a function callback named the same thing as the method.
I use PHP, so I use function_exists (I think its called). If the function doesn't exist, I throw a 405 (METHOD NOT ALLOWED).
Load content with ajax in bootstrap modal
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
Model backing a DB Context has changed; Consider Code First Migrations
This happens when your table structure and model class no longer in sync. You need to update the table structure according to the model class or vice versa -- this is when your data is important and must not be deleted. If your data structure has changed and the data isn't important to you, you can use the DropCreateDatabaseIfModelChanges
feature (formerly known as 'RecreateDatabaseIfModelChanges
' feature) by adding the following code in your Global.asax.cs:
Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());
Run your application again.
As the name implies, this will drop your database and recreate according to your latest model class (or classes) -- provided you believe the table structure definitions in your model classes are the most current and latest; otherwise change the property definitions of your model classes instead.
Convert seconds into days, hours, minutes and seconds
All in one solution. Gives no units with zeroes. Will only produce number of units you specify (3 by default).
Quite long, perhaps not very elegant. Defines are optional, but might come in handy in a big project.
define('OneMonth', 2592000);
define('OneWeek', 604800);
define('OneDay', 86400);
define('OneHour', 3600);
define('OneMinute', 60);
function SecondsToTime($seconds, $num_units=3) {
$time_descr = array(
"months" => floor($seconds / OneMonth),
"weeks" => floor(($seconds%OneMonth) / OneWeek),
"days" => floor(($seconds%OneWeek) / OneDay),
"hours" => floor(($seconds%OneDay) / OneHour),
"mins" => floor(($seconds%OneHour) / OneMinute),
"secs" => floor($seconds%OneMinute),
);
$res = "";
$counter = 0;
foreach ($time_descr as $k => $v) {
if ($v) {
$res.=$v." ".$k;
$counter++;
if($counter>=$num_units)
break;
elseif($counter)
$res.=", ";
}
}
return $res;
}
Feel free to down-vote, but be sure to try it in your code. It might just be what you need.
How do I open the "front camera" on the Android platform?
All older answers' methods are deprecated by Google (supposedly because of troubles like this), since API 21 you need to use the Camera 2 API:
This class was deprecated in API level 21. We recommend using the new
android.hardware.camera2 API for new applications.
In the newer API you have almost complete power over the Android device camera and documentation explicitly advice to
String[] getCameraIdList()
and then use obtained CameraId to open the camera:
void openCamera(String cameraId, CameraDevice.StateCallback callback, Handler handler)
99% of the frontal cameras have id = "1", and the back camera id = "0"
according to this:
Non-removable cameras use integers starting at 0 for their
identifiers, while removable cameras have a unique identifier for each
individual device, even if they are the same model.
However, this means if device situation is rare like just 1-frontal -camera tablet you need to count how many embedded cameras you have, and place the order of the camera by its importance ("0"). So CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0, which implies that the back camera is more important than frontal.
I don't know about a uniform method to identify the frontal camera on all Android devices. Simply said, the Android OS inside the device can't really find out which camera is exactly where for some reasons: maybe the only camera hardcoded id is an integer representing its importance or maybe on some devices whichever side you turn will be .. "back".
Documentation: https://developer.android.com/reference/android/hardware/camera2/package-summary.html
Explicit Examples: https://github.com/googlesamples/android-Camera2Basic
For the older API (it is not recommended, because it will not work on modern phones newer Android version and transfer is a pain-in-the-arse). Just use the same Integer CameraID (1) to open frontal camera like in this answer:
cam = Camera.open(1);
If you trust OpenCV to do the camera part:
Inside
<org.opencv.android.JavaCameraView
../>
use the following for the frontal camera:
opencv:camera_id="1"
Using iText to convert HTML to PDF
The easiest way of doing this is using pdfHTML.
It's an iText7 add-on that converts HTML5 (+CSS3) into pdf syntax.
The code is pretty straightforward:
HtmlConverter.convertToPdf(
"<b>This text should be written in bold.</b>", // html to be converted
new PdfWriter(
new File("C://users/mark/documents/output.pdf") // destination file
)
);
To learn more, go to http://itextpdf.com/itext7/pdfHTML
How to generate gcc debug symbol outside the build target?
NOTE: Programs compiled with high-optimization levels (-O3, -O4) cannot generate many debugging symbols for optimized variables, in-lined functions and unrolled loops, regardless of the symbols being embedded (-g) or extracted (objcopy) into a '.debug' file.
Alternate approaches are
- Embed the versioning (VCS, git, svn) data into the program, for compiler optimized executables (-O3, -O4).
- Build a 2nd non-optimized version of the executable.
The first option provides a means to rebuild the production code with full debugging and symbols at a later date. Being able to re-build the original production code with no optimizations is a tremendous help for debugging. (NOTE: This assumes testing was done with the optimized version of the program).
Your build system can create a .c file loaded with the compile date, commit, and other VCS details. Here is a 'make + git' example:
program: program.o version.o
program.o: program.cpp program.h
build_version.o: build_version.c
build_version.c:
@echo "const char *build1=\"VCS: Commit: $(shell git log -1 --pretty=%H)\";" > "$@"
@echo "const char *build2=\"VCS: Date: $(shell git log -1 --pretty=%cd)\";" >> "$@"
@echo "const char *build3=\"VCS: Author: $(shell git log -1 --pretty="%an %ae")\";" >> "$@"
@echo "const char *build4=\"VCS: Branch: $(shell git symbolic-ref HEAD)\";" >> "$@"
# TODO: Add compiler options and other build details
.TEMPORARY: build_version.c
After the program is compiled you can locate the original 'commit' for your code by using the command: strings -a my_program | grep VCS
VCS: PROGRAM_NAME=my_program
VCS: Commit=190aa9cace3b12e2b58b692f068d4f5cf22b0145
VCS: BRANCH=refs/heads/PRJ123_feature_desc
VCS: AUTHOR=Joe Developer [email protected]
VCS: COMMIT_DATE=2013-12-19
All that is left is to check-out the original code, re-compile without optimizations, and start debugging.
Dynamically add child components in React
Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);
With React, you should use SampleComponent directly in the main App.
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);
The content of your Component is irrelevant, but it should be used like this:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
<SampleComponent name="SomeName"/>
</div>
);
}
});
You can then extend your app component to use a list.
var App = React.createClass({
render: function() {
var componentList = [
<SampleComponent name="SomeName1"/>,
<SampleComponent name="SomeName2"/>
]; // Change this to get the list from props or state
return (
<div>
<h1>App main component! </h1>
{componentList}
</div>
);
}
});
I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.
https://facebook.github.io/react/index.html
Saving response from Requests to file
You can use the response.text
to write to a file:
import requests
files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()
XPath: Get parent node from child node
Use the parent
axes with the parent node's name.
//*[title="50"]/parent::store
This XPath will only select the parent node if it is a store
.
But you can also use one of these
//*[title="50"]/parent::*
//*[title="50"]/..
These xpaths will select any parent node. So if the document changes you will always select a node, even if it is not the node you expect.
EDIT
What happens in the given example where the parent is a bicycle but the parent of the parent is a store?
Does it ascent?
No, it only selects the store if it is a parent of the node that matches //*[title="50"]
.
If not, is there a method to ascent in such cases and return None if there is no such parent?
Yes, you can use ancestor
axes
//*[title="50"]/ancestor::store
This will select all ancestors of the node matching //*[title="50"]
that are ` stores. E.g.
<data xmlns:d="defiant-namespace" d:mi="23">
<store mi="1">
<store mi="22">
<book price="8.95" d:price="Number" d:mi="13">
<title d:constr="String" d:mi="10">50</title>
<category d:constr="String" d:mi="11">reference</category>
<author d:constr="String" d:mi="12">Nigel Rees</author>
</book>
</store>
</store>
</data>
Getting list of files in documents folder
Simple and dynamic solution (Swift 5):
extension FileManager {
class func directoryUrl() -> URL? {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths.first
}
class func allRecordedData() -> [URL]? {
if let documentsUrl = FileManager.directoryUrl() {
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
return directoryContents.filter{ $0.pathExtension == "m4a" }
} catch {
return nil
}
}
return nil
}}
do-while loop in R
Noticing that user 42-'s perfect approach {
* "do while" = "repeat until not"
* The code equivalence:
do while (condition) # in other language
..statements..
endo
repeat{ # in R
..statements..
if(! condition){ break } # Negation is crucial here!
}
} did not receive enough attention from the others, I'll emphasize and bring forward his approach via a concrete example. If one does not negate the condition in do-while (via !
or by taking negation), then distorted situations (1. value persistence 2. infinite loop) exist depending on the course of the code.
In Gauss:
proc(0)=printvalues(y);
DO WHILE y < 5;
y+1;
y=y+1;
ENDO;
ENDP;
printvalues(0); @ run selected code via F4 to get the following @
1.0000000
2.0000000
3.0000000
4.0000000
5.0000000
In R:
printvalues <- function(y) {
repeat {
y=y+1;
print(y)
if (! (y < 5) ) {break} # Negation is crucial here!
}
}
printvalues(0)
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
I still insist that without the negation of the condition in do-while, Salcedo's answer is wrong. One can check this via removing negation symbol in the above code.
Why is <deny users="?" /> included in the following example?
Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.
Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.
Bulk insert with SQLAlchemy ORM
SQLAlchemy introduced that in version 1.0.0
:
Bulk operations - SQLAlchemy docs
With these operations, you can now do bulk inserts or updates!
For instance, you can do:
s = Session()
objects = [
User(name="u1"),
User(name="u2"),
User(name="u3")
]
s.bulk_save_objects(objects)
s.commit()
Here, a bulk insert will be made.
Angular2 multiple router-outlet in the same template
Yes you can as said by @tomer above. i want to add some point to @tomer answer.
for more info read out here and here.
import {RouteConfig, AuxRoute} from 'angular2/router';
@RouteConfig([
new AuxRoute({path: '/home', component: HomeCmp})
])
class MyApp {}
How to call a Parent Class's method from Child Class in Python?
I would recommend using CLASS.__bases__
something like this
class A:
def __init__(self):
print "I am Class %s"%self.__class__.__name__
for parentClass in self.__class__.__bases__:
print " I am inherited from:",parentClass.__name__
#parentClass.foo(self) <- call parents function with self as first param
class B(A):pass
class C(B):pass
a,b,c = A(),B(),C()
failed to open stream: HTTP wrapper does not support writeable connections
May this code help you. It works in my case.
$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
$fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
if(!file_exists($filename)):
$handle = fopen( $filename, 'a' ) or die( 'Cannot open file: ' . $fileUrl ); //implicitly creates file
fwrite( $handle, json_encode(array()));
fclose( $handle );
endif;
$response = file_get_contents($filename);
$tempArray = json_decode($response);
if(!empty($tempArray)):
$count = count($tempArray) + 1;
else:
$count = 1;
endif;
$tempArray[] = array_merge(array("sn." => $count), $data);
$jsonData = json_encode($tempArray);
file_put_contents($filename, $jsonData);
How to remove application from app listings on Android Developer Console
Note: Adding a new answer as the publish/unpublish option is moved to different location.
As mentioned in other answers you cannot delete the app. With updated Google Play Console (Beta), the Unpublish option is moved to different location:
Setup -> Advanced Settings -> App Availability
Enable Published / Unpublished accordingly!
How can I do a BEFORE UPDATED trigger with sql server?
Full example:
CREATE TRIGGER [dbo].[trig_020_Original_010_010_Gamechanger]
ON [dbo].[T_Original]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @Old_Gamechanger int;
DECLARE @New_Gamechanger int;
-- Insert statements for trigger here
SELECT @Old_Gamechanger = Gamechanger from DELETED;
SELECT @New_Gamechanger = Gamechanger from INSERTED;
IF @Old_Gamechanger != @New_Gamechanger
BEGIN
INSERT INTO [dbo].T_History(ChangeDate, Reason, Callcenter_ID, Old_Gamechanger, New_Gamechanger)
SELECT GETDATE(), 'Time for a change', Callcenter_ID, @Old_Gamechanger, @New_Gamechanger
FROM deleted
;
END
END
Which is faster: Stack allocation or Heap allocation
Stack is much faster. It literally only uses a single instruction on most architectures, in most cases, e.g. on x86:
sub esp, 0x10
(That moves the stack pointer down by 0x10 bytes and thereby "allocates" those bytes for use by a variable.)
Of course, the stack's size is very, very finite, as you will quickly find out if you overuse stack allocation or try to do recursion :-)
Also, there's little reason to optimize the performance of code that doesn't verifiably need it, such as demonstrated by profiling. "Premature optimization" often causes more problems than it's worth.
My rule of thumb: if I know I'm going to need some data at compile-time, and it's under a few hundred bytes in size, I stack-allocate it. Otherwise I heap-allocate it.
ASP.NET Core Identity - get current user
Just if any one is interested this worked for me. I have a custom Identity which uses int for a primary key so I overrode the GetUserAsync method
Override GetUserAsync
public override Task<User> GetUserAsync(ClaimsPrincipal principal)
{
var userId = GetUserId(principal);
return FindByNameAsync(userId);
}
Get Identity User
var user = await _userManager.GetUserAsync(User);
If you are using a regular Guid primary key you don't need to override GetUserAsync. This is all assuming that you token is configured correctly.
public async Task<string> GenerateTokenAsync(string email)
{
var user = await _userManager.FindByEmailAsync(email);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_tokenProviderOptions.SecretKey);
var userRoles = await _userManager.GetRolesAsync(user);
var roles = userRoles.Select(o => new Claim(ClaimTypes.Role, o));
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)),
new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
}
.Union(roles);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddHours(_tokenProviderOptions.Expires),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token)).Result;
}
Why can't I define a static method in a Java interface?
To solve this :
error: missing method body, or declare abstract
static void main(String[] args);
interface I
{
int x=20;
void getValue();
static void main(String[] args){};//Put curly braces
}
class InterDemo implements I
{
public void getValue()
{
System.out.println(x);
}
public static void main(String[] args)
{
InterDemo i=new InterDemo();
i.getValue();
}
}
output :
20
Now we can use static method in interface
mysqli_select_db() expects parameter 1 to be mysqli, string given
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
You got the order of the arguments to mysqli_select_db()
backwards. And mysqli_error()
requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.
Note also that with mysqli you can specify the DB in mysqli_connect()
:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error();
}
You must use mysqli_connect_error()
, not mysqli_error()
, to get the error from mysqli_connect()
, since the latter requires you to supply a valid connection.
NGinx Default public www location?
Look into nginx config file to be sure.
This command greps for whatever is configured on your Machine:
cat /etc/nginx/sites-enabled/default |grep "root"
on my machine it was :root /usr/share/nginx/www;
java.lang.IllegalArgumentException: contains a path separator
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for(int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file,array[array.length- 1]);
RandomAccessFileOutputStream rvalue =
new RandomAccessFileOutputStream(f, append);
How to print binary tree diagram?
I needed to print a binary tree in one of my projects, for that I have prepared a java class TreePrinter
, one of the sample output is:
[+]
/ \
/ \
/ \
/ \
/ \
[*] \
/ \ [-]
[speed] [2] / \
[45] [12]
Here is the code for class TreePrinter
along with class TextNode
. For printing any tree you can just create an equivalent tree with TextNode
class.
import java.util.ArrayList;
public class TreePrinter {
public TreePrinter(){
}
public static String TreeString(TextNode root){
ArrayList layers = new ArrayList();
ArrayList bottom = new ArrayList();
FillBottom(bottom, root); DrawEdges(root);
int height = GetHeight(root);
for(int i = 0; i s.length()) min = s.length();
if(!n.isEdge) s += "[";
s += n.text;
if(!n.isEdge) s += "]";
layers.set(n.depth, s);
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i temp = new ArrayList();
for(int i = 0; i 0) temp.get(i-1).left = x;
temp.add(x);
}
temp.get(count-1).left = n.left;
n.left.depth = temp.get(count-1).depth+1;
n.left = temp.get(0);
DrawEdges(temp.get(count-1).left);
}
if(n.right != null){
int count = n.right.x - (n.x + n.text.length() + 2);
ArrayList temp = new ArrayList();
for(int i = 0; i 0) temp.get(i-1).right = x;
temp.add(x);
}
temp.get(count-1).right = n.right;
n.right.depth = temp.get(count-1).depth+1;
n.right = temp.get(0);
DrawEdges(temp.get(count-1).right);
}
}
private static void FillBottom(ArrayList bottom, TextNode n){
if(n == null) return;
FillBottom(bottom, n.left);
if(!bottom.isEmpty()){
int i = bottom.size()-1;
while(bottom.get(i).isEdge) i--;
TextNode last = bottom.get(i);
if(!n.isEdge) n.x = last.x + last.text.length() + 3;
}
bottom.add(n);
FillBottom(bottom, n.right);
}
private static boolean isLeaf(TextNode n){
return (n.left == null && n.right == null);
}
private static int GetHeight(TextNode n){
if(n == null) return 0;
int l = GetHeight(n.left);
int r = GetHeight(n.right);
return Math.max(l, r) + 1;
}
}
class TextNode {
public String text;
public TextNode parent, left, right;
public boolean isEdge;
public int x, depth;
public TextNode(String text){
this.text = text;
parent = null; left = null; right = null;
isEdge = false;
x = 0; depth = 0;
}
}
Finally here is a test class for printing given sample:
public class Test {
public static void main(String[] args){
TextNode root = new TextNode("+");
root.left = new TextNode("*"); root.left.parent = root;
root.right = new TextNode("-"); root.right.parent = root;
root.left.left = new TextNode("speed"); root.left.left.parent = root.left;
root.left.right = new TextNode("2"); root.left.right.parent = root.left;
root.right.left = new TextNode("45"); root.right.left.parent = root.right;
root.right.right = new TextNode("12"); root.right.right.parent = root.right;
System.out.println(TreePrinter.TreeString(root));
}
}
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
As for #2, in my case it magically came to life after replacing
<body>
tag with
<h:body>
After having done several (simpler, to be honest) JSF projects, I couldn't remember of doing anything different setting it up now, and I got this kind of error for the first time. I was making a very basic login page (username, password, user Bean...) and set up everything like usual. The only difference I spotted is tags aforementioned. Maybe someone finds this useful.
gradlew: Permission Denied
I got the same error trying to execute flutter run on a mac. Apparently, in your flutter project, there is a file android/gradlew that is expected to be executable (and it wasn't). So in my case,
chmod a+rx android/gradlew
i used this command and execute the project
Pandas KeyError: value not in index
I had the same issue.
During the 1st development I used a .csv file (comma as separator) that I've modified a bit before saving it.
After saving the commas became semicolon.
On Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.
When testing from a brand new file I encountered that issue.
I've removed the 'sep' argument in read_csv method
before:
df1 = pd.read_csv('myfile.csv', sep=',');
after:
df1 = pd.read_csv('myfile.csv');
That way, the issue disappeared.
Post order traversal of binary tree without recursion
void postorder_stack(Node * root){
stack ms;
ms.top = -1;
if(root == NULL) return ;
Node * temp ;
push(&ms,root);
Node * prev = NULL;
while(!is_empty(ms)){
temp = peek(ms);
/* case 1. We are nmoving down the tree. */
if(prev == NULL || prev->left == temp || prev->right == temp){
if(temp->left)
push(&ms,temp->left);
else if(temp->right)
push(&ms,temp->right);
else {
/* If node is leaf node */
printf("%d ", temp->value);
pop(&ms);
}
}
/* case 2. We are moving up the tree from left child */
if(temp->left == prev){
if(temp->right)
push(&ms,temp->right);
else
printf("%d ", temp->value);
}
/* case 3. We are moving up the tree from right child */
if(temp->right == prev){
printf("%d ", temp->value);
pop(&ms);
}
prev = temp;
}
}
Python code to remove HTML tags from a string
Using a regex
Using a regex, you can clean everything inside <>
:
import re
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
Some HTML texts can also contain entities that are not enclosed in brackets, such as '&nsbm
'. If that is the case, then you might want to write the regex as
cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
This link contains more details on this.
Using BeautifulSoup
You could also use BeautifulSoup
additional package to find out all the raw text.
You will need to explicitly set a parser when calling BeautifulSoup
I recommend "lxml"
as mentioned in alternative answers (much more robust than the default one (html.parser
) (i.e. available without additional install).
from bs4 import BeautifulSoup
cleantext = BeautifulSoup(raw_html, "lxml").text
But it doesn't prevent you from using external libraries, so I recommend the first solution.
EDIT: To use lxml
you need to pip install lxml
.
Convert Java string to Time, NOT Date
You might want to take a look at this example:
public static void main(String[] args) {
String myTime = "10:30:54";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = null;
try {
date = sdf.parse(myTime);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedTime = sdf.format(date);
System.out.println(formattedTime);
}
SQL Server Insert Example
I hope this will help you
Create table :
create table users (id int,first_name varchar(10),last_name varchar(10));
Insert values into the table :
insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');
How to overwrite the previous print to stdout in python?
Better to overwrite the whole line otherwise the new line will mix with the old ones if the new line is shorter.
import time, os
for s in ['overwrite!', 'the!', 'whole!', 'line!']:
print(s.ljust(os.get_terminal_size().columns - 1), end="\r")
time.sleep(1)
Had to use columns - 1
on Windows.
Replace characters from a column of a data frame R
Use gsub
:
data1$c <- gsub('_', '-', data1$c)
data1
a b c
1 0.34597094 a A-B
2 0.92791908 b A-B
3 0.30168772 c A-B
4 0.46692738 d A-B
5 0.86853784 e A-C
6 0.11447618 f A-C
7 0.36508645 g A-C
8 0.09658292 h A-C
9 0.71661842 i A-C
10 0.20064575 j A-C
NotificationCompat.Builder deprecated in Android O
Instead of checking for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
as many answers suggest, there is a slightly simpler way -
Add the following line to the application
section of AndroidManifest.xml file as explained in the Set Up a Firebase Cloud Messaging Client App on Android doc:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
Then add a line with a channel name to the values/strings.xml file:
<string name="default_notification_channel_id">default</string>
After that you will be able to use the new version of NotificationCompat.Builder constructor with 2 parameters (since the old constructor with 1 parameter has been deprecated in Android Oreo):
private void sendNotification(String title, String body) {
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this,
0 /* Request code */,
i,
PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pi);
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
Returning multiple objects in an R function
Unlike many other languages, R functions don't return multiple objects in the strict sense. The most general way to handle this is to return a list
object. So if you have an integer foo
and a vector of strings bar
in your function, you could create a list that combines these items:
foo <- 12
bar <- c("a", "b", "e")
newList <- list("integer" = foo, "names" = bar)
Then return
this list.
After calling your function, you can then access each of these with newList$integer
or newList$names
.
Other object types might work better for various purposes, but the list
object is a good way to get started.
Origin <origin> is not allowed by Access-Control-Allow-Origin
I was facing a problem while calling cross origin resource using ajax from chrome.
I have used node js and local http server to deploy my node js app.
I was getting error response, when I access cross origin resource
I found one solution on that ,
1) I have added below code to my app.js file
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
2) In my html page called cross origin resource using $.getJSON();
$.getJSON("http://localhost:3000/users", function (data) {
alert("*******Success*********");
var response=JSON.stringify(data);
alert("success="+response);
document.getElementById("employeeDetails").value=response;
});
Difference between SRC and HREF
A simple definition
- SRC: If a resource can be placed inside the body tag (for image, script, iframe, frame)
- HREF: If a resource cannot be placed inside the body tag and can only be linked (for html, css)
alert a variable value
A couple of things:
- You can't use
new
as a variable name, it's a reserved word.
- On
input
elements, you can just use the value
property directly, you don't have to go through getAttribute
. The attribute is "reflected" as a property.
- Same for
name
.
So:
var inputs, input, newValue, i;
inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
input = inputs[i];
if (input.name == "ans") {
newValue = input.value;
alert(newValue);
}
}
How can I parse a String to BigDecimal?
Try this
// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);
If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)
Also keep in mind that decimalFormat.parse
can throw a ParseException
so you need to handle it (with try/catch) or throw it and let another part of your program handle it
How can I set / change DNS using the command-prompt at windows 8
There are little difference in command of adding AND changing DNS-IPs:
To Add:
Syntax:
netsh interface ipv4 add dnsserver "Network Interface Name" dns.server.ip index=1(for primary)2(for secondary)
Eg:
netsh interface ipv4 add dnsserver "Ethernet" 8.8.8.8 index=1
- Here, to know "Network Interface Name", type command
netsh interface show interface
- 8.8.8.8 is Google's recursive DNS server, use it, if your's not working
To Set/Change: (as OP asked this)
Syntax:
netsh interface ipv4 set dnsservers "Network Interface Name" static dns.server.ip primary
Eg:
netsh interface ipv4 set dnsservers "Wi-Fi" static 8.8.4.4 primary
netsh interface ipv4 set dnsservers "Wi-Fi" dhcp
Last parameter can be none
:disable DNS, both
:set for primary and secondary DNS both, primary: for primary DNS only. You can notice here we are not using index-parameter as we did in adding DNS.
In the place of static
you can type dhcp
to make DNS setting automatic, but further parameter will not be required.
Note: Tested in windows 8,8.1 & 10.
is there a function in lodash to replace matched item
function findAndReplace(arr, find, replace) {
let i;
for(i=0; i < arr.length && arr[i].id != find.id; i++) {}
i < arr.length ? arr[i] = replace : arr.push(replace);
}
Now let's test performance for all methods:
_x000D_
_x000D_
// TC's first approach_x000D_
function first(arr, a, b) {_x000D_
_.each(arr, function (x, idx) {_x000D_
if (x.id === a.id) {_x000D_
arr[idx] = b;_x000D_
return false;_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// solution with merge_x000D_
function second(arr, a, b) {_x000D_
const match = _.find(arr, a);_x000D_
if (match) {_x000D_
_.merge(match, b);_x000D_
} else {_x000D_
arr.push(b);_x000D_
}_x000D_
}_x000D_
_x000D_
// most voted solution_x000D_
function third(arr, a, b) {_x000D_
const match = _.find(arr, a);_x000D_
if (match) {_x000D_
var index = _.indexOf(arr, _.find(arr, a));_x000D_
arr.splice(index, 1, b);_x000D_
} else {_x000D_
arr.push(b);_x000D_
}_x000D_
}_x000D_
_x000D_
// my approach_x000D_
function fourth(arr, a, b){_x000D_
let l;_x000D_
for(l=0; l < arr.length && arr[l].id != a.id; l++) {}_x000D_
l < arr.length ? arr[l] = b : arr.push(b);_x000D_
}_x000D_
_x000D_
function test(fn, times, el) {_x000D_
const arr = [], size = 250;_x000D_
for (let i = 0; i < size; i++) {_x000D_
arr[i] = {id: i, name: `name_${i}`, test: "test"};_x000D_
}_x000D_
_x000D_
let start = Date.now();_x000D_
_.times(times, () => {_x000D_
const id = Math.round(Math.random() * size);_x000D_
const a = {id};_x000D_
const b = {id, name: `${id}_name`};_x000D_
fn(arr, a, b);_x000D_
});_x000D_
el.innerHTML = Date.now() - start;_x000D_
}_x000D_
_x000D_
test(first, 1e5, document.getElementById("first"));_x000D_
test(second, 1e5, document.getElementById("second"));_x000D_
test(third, 1e5, document.getElementById("third"));_x000D_
test(fourth, 1e5, document.getElementById("fourth"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>_x000D_
<div>_x000D_
<ol>_x000D_
<li><b id="first"></b> ms [TC's first approach]</li>_x000D_
<li><b id="second"></b> ms [solution with merge]</li>_x000D_
<li><b id="third"></b> ms [most voted solution]</li>_x000D_
<li><b id="fourth"></b> ms [my approach]</li>_x000D_
</ol>_x000D_
<div>
_x000D_
_x000D_
_x000D_
Way to read first few lines for pandas dataframe
I think you can use the nrows
parameter. From the docs:
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):
In [1]: import pandas as pd
In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
In [3]: len(z)
Out[3]: 20
In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s
Load jQuery with Javascript and use jQuery
You need to run your code AFTER jQuery finished loading
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = function(){
// your jQuery code here
}
or if you're running it in an async function you could use await
in the above code
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
// your jQuery code here
If you want to check first if jQuery already exists in the page, try this
Filter object properties by key in ES6
I know that this already has plenty of answers and is a rather old question. But I just came up with this neat one-liner:
JSON.parse(JSON.stringify(raw, ['key', 'value', 'item1', 'item3']))
That returns another object with just the whitelisted attributes. Note that the key
and value
is included in the list.
How to execute powershell commands from a batch file?
untested.cmd
;@echo off
;Findstr -rbv ; %0 | powershell -c -
;goto:sCode
set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item TESTSERVERNAME
set-location TESTSERVERNAME
new-itemproperty . -Name http -Value 2 -Type DWORD
;:sCode
;echo done
;pause & goto :eof
Multi-Column Join in Hibernate/JPA Annotations
Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:
Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)
So if you are unwilling to make AnEmbeddableObject
the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject
, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.
Run a script in Dockerfile
Try to create script with ADD
command and specification of working directory
Like this("script" is the name of script and /root/script.sh
is where you want it in the container, it can be different path:
ADD script.sh /root/script.sh
In this case ADD
has to come before CMD
, if you have one
BTW it's cool way to import scripts to any location in container from host machine
In CMD
place [./script]
It should automatically execute your script
You can also specify WORKDIR
as /root
, then you'l be automatically placed in root, upon starting a container
How to replace captured groups only?
With two capturing groups would have been also possible; I would have also included two dashes, as additional left and right boundaries, before and after the digits, and the modified expression would have looked like:
(.*name=".+_)\d+(_[^"]+".*)
_x000D_
_x000D_
const regex = /(.*name=".+_)\d+(_[^"]+".*)/g;_x000D_
const str = `some_data_before name="some_text_0_some_text" and then some_data after`;_x000D_
const subst = `$1!NEW_ID!$2`;_x000D_
const result = str.replace(regex, subst);_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_
If you wish to explore/simplify/modify the expression, it's been
explained on the top right panel of
regex101.com. If you'd like, you
can also watch in this
link, how it would match
against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
how to download file in react js
I have the exact same problem, and here is the solution I make use of now:
(Note, this seems ideal to me because it keeps the files closely tied to the SinglePageApplication React app, that loads from Amazon S3. So, it's like storing on S3, and in an application, that knows where it is in S3, relatively speaking.
Steps
3 steps:
- Make use of file saver in project: npmjs/package/file-saver (
npm install file-saver
or something)
- Place the file in your project You say it's in the components folder. Well, chances are if you've got web-pack it's going to try and minify it.(someone please pinpoint what webpack would do with an asset file in components folder), and so I don't think it's what you'd want. So, I suggest to place the asset into the
public
folder, under a resource
or an asset
name. Webpack doesn't touch the public
folder and index.html
and your resources get copied over in production build as is, where you may refer them as shown in next step.
- Refer to the file in your project Sample code:
import FileSaver from 'file-saver';
FileSaver.saveAs(
process.env.PUBLIC_URL + "/resource/file.anyType",
"fileNameYouWishCustomerToDownLoadAs.anyType");
Source
Appendix
- I also try
Link
component of react-router
react-router-docs/Link. The zip file would download, and somehow would unzip properly. Generally, links have blue color, to inherit parent color scheme, simply add a prop like: style={color: inherit}
or simply assign a class of your CSS library like button button-primary
or something if you're Bootstrappin'
- Other sage questions it's closely related to:
How to re-create database for Entity Framework?
Follow below steps:
1) First go to Server Explorer in Visual Studio, check if the ".mdf" Data Connections for this project are connected, if so, right click and delete.
2 )Go to Solution Explorer, click show All Files icon.
3) Go to App_Data, right click and delete all ".mdf" files for this project.
4) Delete Migrations folder by right click and delete.
5) Go to SQL Server Management Studio, make sure the DB for this project is not there, otherwise delete it.
6) Go to Package Manager Console in Visual Studio and type:
Enable-Migrations -Force
Add-Migration init
Update-Database
7) Run your application
Note: In step 6 part 3, if you get an error "Cannot attach the file...", it is possibly because you didn't delete the database files completely in SQL Server.
Changing API level Android Studio
In build.gradle
change minSdkVersion 13
to minSdkVersion 8
Thats all you need to do. I solved my problem by only doing this.
defaultConfig {
applicationId "com.example.sabrim.sbrtest"
minSdkVersion 8
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
ASP.NET MVC controller actions that return JSON or partial html
In your action method, return Json(object) to return JSON to your page.
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
SomeMethod would be a javascript method that then evaluates the Json object returned.
If you want to return a plain string, you can just use the ContentResult:
public ActionResult SomeActionMethod() {
return Content("hello world!");
}
ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
How do you performance test JavaScript code?
Most browsers are now implementing high resolution timing in performance.now()
. It's superior to new Date()
for performance testing because it operates independently from the system clock.
Usage
var start = performance.now();
// code being timed...
var duration = performance.now() - start;
References
Counting number of occurrences in column?
A simpler approach to this
At the beginning of column B, type
=UNIQUE(A:A)
Then in column C, use
=COUNTIF(A:A, B1)
and copy them in all row column C.
Edit: If that doesn't work for you, try using semicolon instead of comma:
=COUNTIF(A:A; B1)
How do I turn a C# object into a JSON string in .NET?
You could use the JavaScriptSerializer
class (add reference to System.Web.Extensions
):
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
A full example:
using System;
using System.Web.Script.Serialization;
public class MyDate
{
public int year;
public int month;
public int day;
}
public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}
class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}
Call parent method from child class c#
To access properties and methods of a parent class use the base
keyword. So in your child class LoadData()
method you would do this:
public class Child : Parent
{
public void LoadData()
{
base.MyMethod(); // call method of parent class
base.CurrentRow = 1; // set property of parent class
// other stuff...
}
}
Note that you would also have to change the access modifier of your parent MyMethod()
to at least protected
for the child class to access it.
jQuery Force set src attribute for iframe
$(".excel").click(function () {
var t = $(this).closest(".tblGrid").attr("id");
window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});
this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.
How to render an array of objects in React?
Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax
Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.
To avoid this, use key
prop in root element which is looped over in JSX tree of .map()
. Also adding React's Fragment
will avoid adding another element in between of ul
and li
when rendered via calling method.
state = {
userData: [
{ id: '1', name: 'Joe', user_type: 'Developer' },
{ id: '2', name: 'Hill', user_type: 'Designer' }
]
};
deleteUser = id => {
// delete operation to remove item
};
renderItems = () => {
const data = this.state.userData;
const mapRows = data.map((item, index) => (
<Fragment key={item.id}>
<li>
{/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree */}
<span>Name : {item.name}</span>
<span>User Type: {item.user_type}</span>
<button onClick={() => this.deleteUser(item.id)}>
Delete User
</button>
</li>
</Fragment>
));
return mapRows;
};
render() {
return <ul>{this.renderItems()}</ul>;
}
Important : Decision to use which value should we pass to key
prop also matters as common way is to use index
parameter provided by .map()
.
TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id
from data which is being iterated such as item.id
. There's a good article on this - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
Remove tracking branches no longer on remote
Here's a solution that I use for the fish shell. Tested on Mac OS X 10.11.5
, fish 2.3.0
and git 2.8.3
.
function git_clean_branches
set base_branch develop
# work from our base branch
git checkout $base_branch
# remove local tracking branches where the remote branch is gone
git fetch -p
# find all local branches that have been merged into the base branch
# and delete any without a corresponding remote branch
set local
for f in (git branch --merged $base_branch | grep -v "\(master\|$base_branch\|\*\)" | awk '/\s*\w*\s*/ {print $1}')
set local $local $f
end
set remote
for f in (git branch -r | xargs basename)
set remote $remote $f
end
for f in $local
echo $remote | grep --quiet "\s$f\s"
if [ $status -gt 0 ]
git branch -d $f
end
end
end
A few notes:
Make sure to set the correct base_branch
. In this case I use develop
as the base branch, but it could be anything.
This part is very important: grep -v "\(master\|$base_branch\|\*\)"
. It ensures that you don't delete master or your base branch.
I use git branch -d <branch>
as an extra precaution, so as to not delete any branch that has not been fully merged with upstream or current HEAD.
An easy way to test is to replace git branch -d $f
with echo "will delete $f"
.
I suppose I should also add: USE AT YOUR OWN RISK!
How can I use the python HTMLParser library to extract data from a specific div tag?
Little correction at Line 3
HTMLParser.HTMLParser.__init__(self)
it should be
HTMLParser.__init__(self)
The following worked for me though
import urllib2
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.recording = 0
self.data = []
def handle_starttag(self, tag, attrs):
if tag == 'required_tag':
for name, value in attrs:
if name == 'somename' and value == 'somevale':
print name, value
print "Encountered the beginning of a %s tag" % tag
self.recording = 1
def handle_endtag(self, tag):
if tag == 'required_tag':
self.recording -=1
print "Encountered the end of a %s tag" % tag
def handle_data(self, data):
if self.recording:
self.data.append(data)
p = MyHTMLParser()
f = urllib2.urlopen('http://www.someurl.com')
html = f.read()
p.feed(html)
print p.data
p.close()
`
jQuery - prevent default, then continue default
In a pure Javascript way, you can submit the form after preventing default.
This is because HTMLFormElement.submit()
never calls the onSubmit()
. So we're relying on that specification oddity to submit the form as if it doesn't have a custom onsubmit handler here.
var submitHandler = (event) => {
event.preventDefault()
console.log('You should only see this once')
document.getElementById('formId').submit()
}
See this fiddle for a synchronous request.
Waiting for an async request to finish up is just as easy:
var submitHandler = (event) => {
event.preventDefault()
console.log('before')
setTimeout(function() {
console.log('done')
document.getElementById('formId').submit()
}, 1400);
console.log('after')
}
You can check out my fiddle for an example of an asynchronous request.
And if you are down with promises:
var submitHandler = (event) => {
event.preventDefault()
console.log('Before')
new Promise((res, rej) => {
setTimeout(function() {
console.log('done')
res()
}, 1400);
}).then(() => {
document.getElementById('bob').submit()
})
console.log('After')
}
And here's that request.
.gitignore all the .DS_Store files in every folder and subfolder
You can also add the --cached
flag to auco's answer to maintain local .DS_store files, as Edward Newell mentioned in his original answer. The modified command looks like this: find . -name .DS_Store -print0 | xargs -0 git rm --cached --ignore-unmatch
..cheers and thanks!
How to put a new line into a wpf TextBlock control?
Even though this is an old question, I've just come across the problem and solved it differently from the given answers. Maybe it could be helpful to others.
I noticed that even though my XML files looked like:
<tag>
<subTag>content with newline.\r\nto display</subTag>
</tag>
When it was read into my C# code the string had double backslashes.
\\r\\n
To fix this I wrote a ValueConverter to strip the extra backslash.
public class XmlStringConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
string valueAsString = value as string;
if (string.IsNullOrEmpty(valueAsString))
{
return value;
}
valueAsString = valueAsString.Replace("\\r\\n", "\r\n");
return valueAsString;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
how to convert java string to Date object
try
{
String datestr="06/27/2007";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/dd/yyyy");
date = (Date)formatter.parse(datestr);
}
catch (Exception e)
{}
month is MM, minutes is mm..
How do I obtain a Query Execution Plan in SQL Server?
In addition to the comprehensive answer already posted sometimes it is useful to be able to access the execution plan programatically to extract information. Example code for this is below.
DECLARE @TraceID INT
EXEC StartCapture @@SPID, @TraceID OUTPUT
EXEC sp_help 'sys.objects' /*<-- Call your stored proc of interest here.*/
EXEC StopCapture @TraceID
Example StartCapture
Definition
CREATE PROCEDURE StartCapture
@Spid INT,
@TraceID INT OUTPUT
AS
DECLARE @maxfilesize BIGINT = 5
DECLARE @filepath NVARCHAR(200) = N'C:\trace_' + LEFT(NEWID(),36)
EXEC sp_trace_create @TraceID OUTPUT, 0, @filepath, @maxfilesize, NULL
exec sp_trace_setevent @TraceID, 122, 1, 1
exec sp_trace_setevent @TraceID, 122, 22, 1
exec sp_trace_setevent @TraceID, 122, 34, 1
exec sp_trace_setevent @TraceID, 122, 51, 1
exec sp_trace_setevent @TraceID, 122, 12, 1
-- filter for spid
EXEC sp_trace_setfilter @TraceID, 12, 0, 0, @Spid
-- start the trace
EXEC sp_trace_setstatus @TraceID, 1
Example StopCapture
Definition
CREATE PROCEDURE StopCapture
@TraceID INT
AS
WITH XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' as sql),
CTE
as (SELECT CAST(TextData AS VARCHAR(MAX)) AS TextData,
ObjectID,
ObjectName,
EventSequence,
/*costs accumulate up the tree so the MAX should be the root*/
MAX(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
FROM fn_trace_getinfo(@TraceID) fn
CROSS APPLY fn_trace_gettable(CAST(value AS NVARCHAR(200)), 1)
CROSS APPLY (SELECT CAST(TextData AS XML) AS xPlan) x
CROSS APPLY (SELECT T.relop.value('@EstimatedTotalSubtreeCost',
'float') AS EstimatedTotalSubtreeCost
FROM xPlan.nodes('//sql:RelOp') T(relop)) ca
WHERE property = 2
AND TextData IS NOT NULL
AND ObjectName not in ( 'StopCapture', 'fn_trace_getinfo' )
GROUP BY CAST(TextData AS VARCHAR(MAX)),
ObjectID,
ObjectName,
EventSequence)
SELECT ObjectName,
SUM(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
FROM CTE
GROUP BY ObjectID,
ObjectName
-- Stop the trace
EXEC sp_trace_setstatus @TraceID, 0
-- Close and delete the trace
EXEC sp_trace_setstatus @TraceID, 2
GO
How to convert string to string[]?
You can create a string[]
(string array) that contains your string
like :
string someString = "something";
string[] stringArray = new string[]{ someString };
The variable stringArray
will now have a length of 1 and contain someString
.
Apply multiple functions to multiple groupby columns
This is a twist on 'exans' answer that uses Named Aggregations. It's the same but with argument unpacking which allows you to still pass in a dictionary to the agg function.
The named aggs are a nice feature, but at first glance might seem hard to write programmatically since they use keywords, but it's actually simple with argument/keyword unpacking.
animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]})
agg_dict = {
"min_height": pd.NamedAgg(column='height', aggfunc='min'),
"max_height": pd.NamedAgg(column='height', aggfunc='max'),
"average_weight": pd.NamedAgg(column='weight', aggfunc=np.mean)
}
animals.groupby("kind").agg(**agg_dict)
The Result
min_height max_height average_weight
kind
cat 9.1 9.5 8.90
dog 6.0 34.0 102.75
Running a cron every 30 seconds
You can check out my answer to this similar question
Basically, I've included there a bash script named "runEvery.sh" which you can run with cron every 1 minute and pass as arguments the real command you wish to run and the frequency in seconds in which you want to run it.
something like this
* * * * * ~/bin/runEvery.sh 5 myScript.sh
Detect whether there is an Internet connection available on Android
Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work.
_ how could I have found myself the information I needed in the online documentation?
You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.
Unresolved Import Issues with PyDev and Eclipse
I had some issues importing additional libraries, after trying to resolve the problem, by understanding
PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, I just add a new empty line in the files that had the import errors and saved them and the error was resolved.
How to use subprocess popen Python
It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split()
can do the correct tokenization for args (I'm using Blender's example of the call):
import shlex
from subprocess import Popen, PIPE
command = shlex.split('swfdump /tmp/filename.swf/ -d')
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
https://docs.python.org/3/library/subprocess.html
How to create/read/write JSON files in Qt5
Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.
So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL
as needed):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.
Return different type of data from a method in java?
the approach you took is good.
Just Implementation may need to be better.
For instance ReturningValues should be well defined and
Its better if you can make ReturningValues as immutable.
// this approach is better
public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues("value", 12);
return rv;
}
public final class ReturningValues {
private final String value;
private final int index;
public ReturningValues(String value, int index) {
this.value = value;
this.index = index;
}
}
Or if you have lots of key value pairs you can use HashMap then
public static Map<String,Object> myMethod() {
Map<String,Object> map = new HashMap<String,Object>();
map.put(VALUE, "value");
map.put(INDEX, 12);
return Collections.unmodifiableMap(map); // try to use this
}
Getting ssh to execute a command in the background on target machine
Actually, whenever I need to run a command on a remote machine that's complicated, I like to put the command in a script on the destination machine, and just run that script using ssh.
For example:
# simple_script.sh (located on remote server)
#!/bin/bash
cat /var/log/messages | grep <some value> | awk -F " " '{print $8}'
And then I just run this command on the source machine:
ssh user@ip "/path/to/simple_script.sh"
How can I convert string to double in C++?
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999
(which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
I want a function that returns 0 when the string is not numerical.
You can add try catch statement when stod
throws an exception.
Count work days between two dates
One approach is to 'walk the dates' from start to finish in conjunction with a case expression which checks if the day is not a Saturday or a Sunday and flagging it(1 for weekday, 0 for weekend). And in the end just sum flags(it would be equal to the count of 1-flags as the other flag is 0) to give you the number of weekdays.
You can use a GetNums(startNumber,endNumber) type of utility function which generates a series of numbers for 'looping' from start date to end date. Refer http://tsql.solidq.com/SourceCodes/GetNums.txt for an implementation. The logic can also be extended to cater for holidays(say if you have a holidays table)
declare @date1 as datetime = '19900101'
declare @date2 as datetime = '19900120'
select sum(case when DATENAME(DW,currentDate) not in ('Saturday', 'Sunday') then 1 else 0 end) as noOfWorkDays
from dbo.GetNums(0,DATEDIFF(day,@date1, @date2)-1) as Num
cross apply (select DATEADD(day,n,@date1)) as Dates(currentDate)
Javascript how to parse JSON array
In a for-in-loop the running variable holds the property name, not the property value.
for (var counter in jsonData.counters) {
console.log(jsonData.counters[counter].counter_name);
}
But as counters is an Array, you have to use a normal for-loop:
for (var i=0; i<jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
Last executed queries for a specific database
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
jQuery issue in Internet Explorer 8
The onload event does not always work on IE7/8 in <head> ... </head>
You can force it by adding an onload script at the end of your page before the tag as below.
<script>
window.onload();
</script>
</body>
Twitter Bootstrap button click to toggle expand/collapse text section above button
Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.
You would replace his .btn
with the following:
<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>
And add a small CSS for when the content is displayed:
.in.collapse+a.btn.showdetails:before {
content:'Hide details «';
}
.collapse+a.btn.showdetails:before {
content:'Show details »';
}
Here is his modified example
Convert hex string (char []) to int?
Have you tried strtol()
?
strtol - convert string to a long integer
Example:
const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);
In case the string representation of the number begins with a 0x
prefix, one must should use 0 as base:
const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);
(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)
Customizing the template within a Directive
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.replaceWith(htmlText);
}
};
})
display data from SQL database into php/ html table
Look in the manual http://www.php.net/manual/en/mysqli.query.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET @a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>
How to post object and List using postman
I'm not sure what server side technology you are using but try using a json array. A couple of options for you to try:
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
},
[
1436517454492,
1436517476993
]
If that doesn't work you may also try:
{
freelancer: {
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
},
skills : [
1436517454492,
1436517476993
]
}
Add comma to numbers every three digits
You could try NumberFormatter.
$(this).format({format:"#,###.00", locale:"us"});
It also supports different locales, including of course US.
Here's a very simplified example of how to use it:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.numberformatter.js"></script>
<script>
$(document).ready(function() {
$(".numbers").each(function() {
$(this).format({format:"#,###", locale:"us"});
});
});
</script>
</head>
<body>
<div class="numbers">1000</div>
<div class="numbers">2000000</div>
</body>
</html>
Output:
1,000
2,000,000
Checking the form field values before submitting that page
While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()"
instead.
You may want to considering replacing this method with onsubmit="return checkform()"
in the form tag instead, though both will work for clicking the button.
What's in an Eclipse .classpath/.project file?
This eclipse documentation has details on the markups in .project
file: The project description file
It describes the .project
file as:
When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"
SASS :not selector
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
How to get the difference between two dictionaries in Python?
You were right to look at using a set, we just need to dig in a little deeper to get your method to work.
First, the example code:
test_1 = {"foo": "bar", "FOO": "BAR"}
test_2 = {"foo": "bar", "f00": "b@r"}
We can see right now that both dictionaries contain a similar key/value pair:
{"foo": "bar", ...}
Each dictionary also contains a completely different key value pair. But how do we detect the difference? Dictionaries don't support that. Instead, you'll want to use a set.
Here is how to turn each dictionary into a set we can use:
set_1 = set(test_1.items())
set_2 = set(test_2.items())
This returns a set containing a series of tuples. Each tuple represents one key/value pair from your dictionary.
Now, to find the difference between set_1 and set_2:
print set_1 - set_2
>>> {('FOO', 'BAR')}
Want a dictionary back? Easy, just:
dict(set_1 - set_2)
>>> {'FOO': 'BAR'}
What does mscorlib stand for?
It stands for
Microsoft's Common Object Runtime Library
and it is the primary assembly for the Framework Common Library.
It contains the following namespaces:
System
System.Collections
System.Configuration.Assemblies
System.Diagnostics
System.Diagnostics.SymbolStore
System.Globalization
System.IO
System.IO.IsolatedStorage
System.Reflection
System.Reflection.Emit
System.Resources
System.Runtime.CompilerServices
System.Runtime.InteropServices
System.Runtime.InteropServices.Expando
System.Runtime.Remoting
System.Runtime.Remoting.Activation
System.Runtime.Remoting.Channels
System.Runtime.Remoting.Contexts
System.Runtime.Remoting.Lifetime
System.Runtime.Remoting.Messaging
System.Runtime.Remoting.Metadata
System.Runtime.Remoting.Metadata.W3cXsd2001
System.Runtime.Remoting.Proxies
System.Runtime.Remoting.Services
System.Runtime.Serialization
System.Runtime.Serialization.Formatters
System.Runtime.Serialization.Formatters.Binary
System.Security
System.Security.Cryptography
System.Security.Cryptography.X509Certificates
System.Security.Permissions
System.Security.Policy
System.Security.Principal
System.Text
System.Threading
Microsoft.Win32
Interesting info about MSCorlib:
- The .NET 2.0 assembly will reference and use the 2.0 mscorlib.The
.NET 1.1
assembly will reference the 1.1 mscorlib
but will use
the 2.0 mscorlib at runtime (due to hard-coded version redirects in
theruntime itself)
- In GAC there is only one version of mscorlib, you dont find 1.1
version on GAC even if you have 1.1 framework installed on your
machine. It would be good if somebody can explain why
MSCorlib 2.0
alone is in GAC whereas 1.x version live inside framework folder
- Is it possible to force a different runtime to be loaded by the
application by making a config setting in your app / web.config? you
won’t be able to choose the CLR version by settings in the
ConfigurationFile – at that point, a CLR will already be running, and
there can only be one per process. Immediately after the CLR is
chosen the MSCorlib appropriate for that CLR is loaded.
Python Pandas replicate rows in dataframe
This is an old question, but since it still comes up at the top of my results in Google, here's another way.
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))
Say you want to replicate the rows where col1="b".
reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]
You could replace the 3 if val=="b" else 1
in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.
Basic authentication with fetch?
NODE USERS (REACT,EXPRESS) FOLLOW THESE STEPS
npm install base-64 --save
import { encode } from "base-64";
const response = await fetch(URL, {
method: 'post',
headers: new Headers({
'Authorization': 'Basic ' + encode(username + ":" + password),
'Content-Type': 'application/json'
}),
body: JSON.stringify({
"PassengerMobile": "xxxxxxxxxxxx",
"Password": "xxxxxxx"
})
});
const posts = await response.json();
Don't forget to define this whole function as async
Change bootstrap navbar background color and font color
Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.
<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->
Otherwise, you can put !important
at the end of your CSS like this: color:#ffffff!important;
but I would advise against using !important
at all costs.
How do I get a Cron like scheduler in Python?
You could just use normal Python argument passing syntax to specify your crontab. For example, suppose we define an Event class as below:
from datetime import datetime, timedelta
import time
# Some utility classes / functions first
class AllMatch(set):
"""Universal set - match everything"""
def __contains__(self, item): return True
allMatch = AllMatch()
def conv_to_set(obj): # Allow single integer to be provided
if isinstance(obj, (int,long)):
return set([obj]) # Single item
if not isinstance(obj, set):
obj = set(obj)
return obj
# The actual Event class
class Event(object):
def __init__(self, action, min=allMatch, hour=allMatch,
day=allMatch, month=allMatch, dow=allMatch,
args=(), kwargs={}):
self.mins = conv_to_set(min)
self.hours= conv_to_set(hour)
self.days = conv_to_set(day)
self.months = conv_to_set(month)
self.dow = conv_to_set(dow)
self.action = action
self.args = args
self.kwargs = kwargs
def matchtime(self, t):
"""Return True if this event should trigger at the specified datetime"""
return ((t.minute in self.mins) and
(t.hour in self.hours) and
(t.day in self.days) and
(t.month in self.months) and
(t.weekday() in self.dow))
def check(self, t):
if self.matchtime(t):
self.action(*self.args, **self.kwargs)
(Note: Not thoroughly tested)
Then your CronTab can be specified in normal python syntax as:
c = CronTab(
Event(perform_backup, 0, 2, dow=6 ),
Event(purge_temps, 0, range(9,18,2), dow=range(0,5))
)
This way you get the full power of Python's argument mechanics (mixing positional and keyword args, and can use symbolic names for names of weeks and months)
The CronTab class would be defined as simply sleeping in minute increments, and calling check() on each event. (There are probably some subtleties with daylight savings time / timezones to be wary of though). Here's a quick implementation:
class CronTab(object):
def __init__(self, *events):
self.events = events
def run(self):
t=datetime(*datetime.now().timetuple()[:5])
while 1:
for e in self.events:
e.check(t)
t += timedelta(minutes=1)
while datetime.now() < t:
time.sleep((t - datetime.now()).seconds)
A few things to note: Python's weekdays / months are zero indexed (unlike cron), and that range excludes the last element, hence syntax like "1-5" becomes range(0,5) - ie [0,1,2,3,4]. If you prefer cron syntax, parsing it shouldn't be too difficult however.
Convert a string to integer with decimal in Python
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
SQL Insert Query Using C#
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...
here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
Passing headers with axios POST request
To set headers in an Axios POST request, pass the third object to the axios.post() call.
const token = '..your token..'
axios.post(url, {
//...data
}, {
headers: {
'Authorization': `Basic ${token}`
}
})
To set headers in an Axios GET request, pass a second object to the axios.get() call.
const token = '..your token..'
axios.get(url, {
headers: {
'Authorization': `Basic ${token}`
}
})
Cheers!! Read Simple Write Simple
Linux shell script for database backup
#!/bin/bash
# Add your backup dir location, password, mysql location and mysqldump location
DATE=$(date +%d-%m-%Y)
BACKUP_DIR="/var/www/back"
MYSQL_USER="root"
MYSQL_PASSWORD=""
MYSQL='/usr/bin/mysql'
MYSQLDUMP='/usr/bin/mysqldump'
DB='demo'
#to empty the backup directory and delete all previous backups
rm -r $BACKUP_DIR/*
mysqldump -u root -p'' demo | gzip -9 > $BACKUP_DIR/demo$date_format.sql.$DATE.gz
#changing permissions of directory
chmod -R 777 $BACKUP_DIR
Ignore self-signed ssl cert using Jersey Client
Just adding the same code with the imports. Also contains the unimplemented code that is needed for compilation. I initially had trouble finding out what was imported for this code. Also adding the right package for the X509Certificate. Got this working with trial and error:
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import javax.ws.rs.core.MultivaluedMap;
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
java.security.cert.X509Certificate[] chck = null;
;
return chck;
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
;
}
How to unpack an .asar file?
From the asar documentation
(the use of npx
here is to avoid to install the asar
tool globally with npm install -g asar
)
Extract the whole archive:
npx asar extract app.asar destfolder
Extract a particular file:
npx asar extract-file app.asar main.js
What's the difference between '$(this)' and 'this'?
Yes you only need $()
when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.
$(this)[0] === this
Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.
$("#myDiv")[0] === document.getElementById("myDiv");
And so on...
javascript scroll event for iPhone/iPad?
Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.
So, if you register the scroll
event handler and check window.pageYOffset
inside that event handler, everything works just fine.
Succeeded installing but could not start apache 2.4 on my windows 7 system
I was also facing the same issue, then i tried restarting my system after every change and it worked for me:
- Uninstall Apache2.4 in cmd prompt (run administrator) with the command:
httpd -k uninstall
.
- Restart the system.
- open cmd prompt (run administrator) with the command:
httpd -k install
.
- Then
httpd -k install
.
Hope you find useful.
Nginx reverse proxy causing 504 Gateway Timeout
Probably can add a few more line to increase the timeout period to upstream. The examples below sets the timeout to 300 seconds :
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
How to swap String characters in Java?
//this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use
package string_sorter;
public class String_Sorter {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String word = "jihgfedcba";
for (int endOfString = word.length(); endOfString > 0; endOfString--) {
int largestWord = word.charAt(0);
int location = 0;
for (int index = 0; index < endOfString; index++) {
if (word.charAt(index) > largestWord) {
largestWord = word.charAt(index);
location = index;
}
}
if (location < endOfString - 1) {
String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
word = newString;
}
System.out.println(word);
}
System.out.println(word);
}
}
How to pass a variable from Activity to Fragment, and pass it back?
thanks to @??s???? K and Terry ... it helps me a lot and works perfectly
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// get arguments
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
reference :
Send data from activity to fragment in android
Read from a gzip file in python
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
What's the C# equivalent to the With statement in VB?
Not really, you have to assign a variable. So
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
Or in C# 3.0:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
Disabled UIButton not faded or grey
I am stuck on the same problem. Setting alpha is not what I want.
UIButton
has "background image" and "background color".
For image, UIButton
has a property as
@property (nonatomic) BOOL adjustsImageWhenDisabled
And background image is drawn lighter when the button is disabled.
For background color, setting alpha, Ravin's solution, works fine.
First, you have to check whether you have unchecked "disabled adjusts image" box under Utilities-Attributes.
Then, check the background color for this button.
(Hope it's helpful. This is an old post; things might have changed in Xcode).
Fail during installation of Pillow (Python module) in Linux
There is a bug reported for Pillow here, which indicates that libjpeg
and zlib
are now required as of Pillow 3.0.0.
The installation instructions for Pillow on Linux give advice of how to install these packages. Note that not all of the following packages may be missing on your machine (comments suggest that only libjpeg8-dev
is actually missing).
pip / PyPi (Pillow>3.4.2)
The latest releases of Pillow are available on PyPi as wheels — the new standard packaging mechanism for Python. These prebuilt packages include all neccessary binary dependencies to allow Pillow to run and should be used if you want to install Pillow using PyPi
To use wheels, you need to have a version of pip>=1.4
. If you are using an earlier version (pip --version
) upgrade pip using the following:
pip install --upgrade pip
Once pip
is upgraded, pip install
will use platform-specific wheel files by default if they are available. Use the following command to upgrade Pillow to the latest version available on PyPi:
pip install --upgrade pillow
Ubuntu 12.04 LTS or Raspian Wheezy 7.0
sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
Ubuntu 14.04
sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk
Ubuntu 18.04
sudo apt install libjpeg8-dev zlib1g-dev
Fedora 20
The Fedora 20 equivalent of libjpeg8-dev
is libjpeg-devel
.
sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel
Mac OS X (via Homebrew)
On Mac OS X with Homebrew this can be fixed using:
brew install libjpeg zlib
You may also need to force-link zlib using the following:
brew link zlib --force
Update April 2019: In Mojave the above will not work and you need to run the following as taken from this bug report on Pillow
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
Update July 2016: There is no longer a formula for zlib
available in the main repository (Homebrew will prompt you to install lzlib
which is a different library and will not solve this problem).
There is a formula available in the dupes repository. You can either tap this repository, and install as normal:
brew tap homebrew/dupes
brew install zlib
Or you can install zlib
via xcode
instead, as follows:
xcode-select --install
Thanks to phoenix, Panos Angelopoulou, nelsonvarela, benjaminz and Kal in the comments
After these are installed the pip installation of Pillow should work normally.