text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Firebase: Search by email without letting users see all users
Imagine I have a database:
emails
- [email protected]: userID1
- [email protected]: userID2
- [email protected]: userID3
How can i create a Firebase rule that a user can search to see if an email address exists and subsequently get the userID, but can't view the entire list?
e.g
/path emails {
read() { true }, // But will let user view all emails signed up
write() { writeIfNotExists() }
}
A:
There is no way for a user to search data that they are not allowed to read. Either a user can read data, in which case they can search and retrieve it, or they can't read data, in which case they can neither retrieve nor search it.
If you want to implement such a use-case, your best bet is to implement a search API as a HTTP endpoint in Cloud Functions for Firebase.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does this haiku have a 5-6-5 pattern?
I was amazed to read the following haiku in "小林 一茶" (a book written by 宗左近/Sō Sakon about the famous poet) :
我と来てあそぶ親のない雀
At first sight, the text given by 宗左近 doesn't seem regular : 5+6+5 morae ?.
I knew the following version with a 'や' after あそぶ :
我{われ}と来{き}てあそぶや親{おや}のない雀{すずめ}
I thought the haiku given by 宗左近 was misprinted but it seems incredible such an error occured at the very beginning of the book, in the first haiku given by the author, page 1 !
There's obviously something I'm missing... Any idea to help me ?
A:
Some haiku do not strictly follow the 5-7-5 pattern. Irregular haiku with one more or less morae than usual are called 字余り or 字足らず, respectively. Some haiku even ignore the 5-7-5 rule completely (See 自由律俳句).
Wikipedia says 一茶's haiku do have many variations:
最も多くの俳句を残したのは、正岡子規で約24,000句であるが、一茶の句は類似句や異形句が多いため、数え方によっては、子規の句数を上回るかもしれない。よく知られている「我と来て遊べや親のない雀」にも、「我と来て遊ぶや親のない雀」と「我と来て遊ぶ親のない雀」の類似句があり、これを1句とするか3句とするかは議論の分かれるところである。
According to 一茶の俳句データベース, the sources of these three variations are as follows:
我と来てあそぶ親のない雀 is from 七番日記
我と来て遊ぶや親のない雀 is from 句稿消息/etc
我と来て遊べや親のない雀 is from おらが春/etc
I think the third one is best-known, but it seems that the first one is the original version, although being 字足らず. 七番日記 is his personal diary, which he did not intend to publish.
According to the article of おらが春, 一茶 wanted to publish his poetry book, but he died before he could do that. おらが春 was compiled and published by another person, 25 years after 一茶's death.
『おらが春』は、まったくの時系列に沿って書き記された日記ではなく、刊行を意図して構成されたものである。さらに一茶自身、改訂や推敲を重ねたが、未刊のままに留まっていたものである。内容的には、一部脚色や時系列を事実とは若干ずらした箇所なども指摘する研究者もあり、作品として意識されたものという性格が強い。
So I think the well-known third version was the revised version either by 一茶 himself or by the editor.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Magento add product size and attribute inventory
I think this is a common situation, I'm selling clothes and shoes and I need to have an option for sizes and attribute an inventory level for each. How could I do that?
Here is an example, I m selling shoes in sizes 41 to 45. I have 5 pairs of each except the size 45 which I only have 2.
(Keep in mind that clothes and shoes don t have the same measurement options).
Would be awesome if I could do it for all products in a category at the same time, even if that means having to go through the DB.
Thanks.
A:
Creating a Configurable Product
There are a few steps involved:
Create the attributes that will be configurable by the user - for our example they will be Size and Color
Create the attribute set that will be assigned to the variant products - for our example, we’ll call it “T-shirt”
Create the individual variant products
Create the configurable product, and add the “T-shirt” attribute set
Add the individual variants to this configurable product
http://www.magentocommerce.com/knowledge-base/entry/tutorial-creating-a-configurable-product/
Adding a new attribute to the table isn't to difficult, but you need to find a good way of making sure it's not dirty. You do not want to add empty attributes to make sure you have room for enough products and you don't want to have too few. I was recommended using implode on an array to put it into a variable in which each element of the original ray is stored and separated by a character. You could then put this into one column. You can find some good information for updating a magento table here: http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-6-magento-setup-resources/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how can I set input text value in child window that is called from parent window?
I want to set textbox value in child window.This value is passed from parent window.I am using HTML and Javascript.Thanks in advance.My code is as below.
in parent window
var newWindow = window.open('child.html');
newWindow.id = 1;
newWindow.init();
in child window
function init(){
document.getElementById('id').value = id;
}
I think my code does not call to init() function.
I have tried
window.open('child.html').document.getElementById('id').value += 1;
in my parent window and it does not work.
A:
You need to wait for the page to actually load in the child:
var newWindow = window.open('child.html');
newWindow.addEventListener("DOMContentLoaded", function() {
newWindow.id = 1;
newWindow.init();
});
Depending on the script tag used to load init, you may need to be a bit more defensive:
var newWindow = window.open('child.html');
newWindow.addEventListener("DOMContentLoaded", function() {
tryInit();
function tryInit() {
if (!newWindow.init) {
setTimeout(tryInit, 10);
return;
}
newWindow.id = 1;
newWindow.init();
}
});
You might have that give up after (say) 20 seconds so it's not constantly looping if something goes wrong.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove non alphanumeric characters and space, but keep foreign language in JavaScript
I want to remove signs like:
!@#$%^&*()_+`-=[]\|{};':",./<>?。,‘“”’;【】『』
and many more.
But ensuring all the foreign characters are kept, such as Chinese, French, Greece, etc.
In Ruby, I'm able to do it with regex
/[^\p{Alnum}]/
It doesn't work in JS. Thanks in advance.
Answer
Thank Jordan Gray. The 8400-letter regex is awesome. It is a short solution as it is only 8.4kb compare to 63kb of XRegExp.
For the record, the full answer I use is
/[^1-9\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]+/g
This is funny, isn't it?
A:
Someone has already suggested XRegExp. That's a great package, but if all you want is a way of matching letters you can grab it straight from the source.
In this case, what you're looking for is a way to match the whole Unicode Letter category, which is defined in the source for the XRegExp Unicode Base package. With XRegExp, you could match these with \p{L} or \p{Letter}. A JS-compatible expression for matching characters not in this category would work out to (brace yourself):
var NonLetters = /[^\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
jsFiddle demo.
Pretty hefty, but what you'd expect if you aim to match uppercase, lowercase, title case, modifier and other letters in every language in the basic multilingual plane¹, including all ligatures and accented characters. Don't forget to add 0-9 to the beginning if you want to match numbers as well!
If you trust your Unicode not to get mangled, you could use this shorter version:
var NonLetters = /[^A-Za-zªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々〆〱-〵〻〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛥꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]/
This gives a little idea of the sheer diversity of this category. Personally, I would use the first expression since it is far less likely to be invisibly mucked up in a way that you will probably never find out about.
¹ This doesn't include characters from the so-called astral planes such as emoji, ancient/historic scripts like Egyptian hieroglyphs and the many many CJK ideographs. It's your call if you think these should count as "letters" in some very extended sense and thus want to include them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Call object method of generic
I have a method that is passing in a object as a generic. Note that these objects do not derive from the same class. I have a function that I would like to call regardless of the type but am not able to call because it cannot determine the type.
'T' does not contain a definition for 'Validate'
And the code
public void VerifyInput<T>(T obj)
{
((T)obj).Validate();
}
This is being used to validate user data passed in. Each of the classes are responsible for setting their own validation but they are not necessarily related in any way.
I have simplified this but the basic question remains. How can I cast the type of a generic to call an object method?
A:
Note that these objects do not derive from the same class. I have a function that I would like to call regardless of the type but am not able to call because it cannot determine the type.
This is where you should be using an interface.
public interface IValidatable {
void Validate();
}
And on your method
public void VerifyInput<T>(T obj) where T : IValidatable
{
obj.Validate();
}
Doing this will ensure that the passed in type conforms to the interface contract but not restrict it to a specific type definition.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ionViewDidLeave and ionViewDidEnter not firing when i change pages
I have an Ionic 4 application with Angular 7 development, the event ionViewDidEnter works if I first enter on the page, but if I move to another page and go back this event is not firing.
I change to ngOnDestroy from Angular and this works when the page is first loaded but when I go to the page and go back and leave this not working too.
My real problem that I have a login page and a home panel page, when I start the application my ngOnInit from my app.component.ts he verifies if the user is logged if is he redirect the user to panel home page that use this code
this.router.navigate(['painel/home']);
When this happens this event ionViewDidEnter and ionViewWillEnter work when this page appears, but when I click my button logout, my application clear the cache and change the navigation to this page auth.component.ts this is the code from logout
public logout(refresh?: boolean): void {
this.tokenStorage.clear();
if (refresh) {
this.router.navigate(['auth']);
}
}
Simple, but when I make a login again this events ionViewDidEnter and ionViewWillEnter don't fire and I want this to fire every time the user enters in panel home page, this is my code to log in application
async authenticationLogin() {
const loading = await this.loadingController.create({
message: 'Autenticando',
});
loading.present();
const userModel: any = {
afiliate_code: this.authForm.value.afiliate_code,
device_uuid: this.device.uuid,
};
let companyCode: string = this.authForm.value.company_code;
companyCode = companyCode.toUpperCase();
this.auth.login(userModel, companyCode, this.uuidValidation).pipe(
catchError(
(error: any): Observable<any> => {
loading.dismiss();
return this.utilService.errorHandler(error);
}))
.subscribe( async response => {
if (response.responseData.success === 1) {
if (this.authForm.value.checkauth_param) {
this.authParam = {
afiliate_code: userModel.afiliate_code,
companyCodeData: companyCode,
};
this.storageService.saveKeyStorage('param', this.authParam);
} else {
if (this.storageService.getKeyParamData('param')) {
this.storageService.removeKeyStorage('param');
}
}
this.submitted = false;
setTimeout(() => {
this.authForm.reset();
}, 2000);
this.router.navigate(['painel/home']);
} else if (response.responseData.success === 2) {
this.utilService.errorMsgAlert(response.responseData.message);
} else if (response.responseData.success === 3) {
const alert = await this.alertController.create({
header: 'Atenção!',
message: 'Você ainda não possui um dispositivo vinculado, deseja vincular este dispositivo ao seu usuário?',
buttons: [
{
text: 'Não',
role: 'cancel',
cssClass: 'secondary'
}, {
text: 'Sim',
handler: () => {
this.uuidValidation = true;
this.authenticationLogin();
}
}
]
});
await alert.present();
} else {
this.utilService.errorMsgAlert('Não foi possível fazer autenticação');
}
loading.dismiss();
});
}
That is working fine, what I'm doing wrong to not fire these events?
A:
I solved my problem with this, I was using this code from Angular 7 core to change my pages
// import { Router } from '@angular/router';
this.router.navigate(['painel/home']);
But when I change to the Ionic 4 core
// import { NavController } from '@ionic/angular';
this.navController.navigateBack(['painel/home']);
Now ionViewDidEnter is fired every time, I read this article and solvend my problem.
Thank you all
https://medium.com/@paulstelzer/ionic-4-and-the-lifecycle-hooks-4fe9eabb2864
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sprite Kit stop playing music file and start from the beginning
Whenever I present my scene, I want to start playing a music file and stop the music playing from the last time my scene was presented. I'm trying to do it like this.
[self removeActionForKey:@"Music"];
[self runAction:[SKAction repeatActionForever:[SKAction playSoundFileNamed:@"Music.wav" waitForCompletion:YES]] withKey:@"Music"];
Should I use AVAudioPlayer or [SKAction playSoundFileNamed:]?
Also I would like to know if there is a way to play music file forever in all scenes without starting from the beginning.
A:
To play background music in all scenes I will recommend AVAudioPlayer. You can write the code somewhere in your AppDelegate to access from all the scenes. Here is a sample code to achieve this using AVAudioPlayer
// AVAudioPlayer *bgMusicLoop;
- (void)playBackroundMusic:(NSString *)fileName withExtenstion:(NSString *)fileExtension
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:fileExtension];
NSError *error;
if(bgMusicLoop)
[bgMusicLoop stop];
bgMusicLoop = nil;
bgMusicLoop = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:&error];
if (error) {
NSLog(@"Error in audioPlayer: %@", [error localizedDescription]);
} else {
bgMusicLoop.numberOfLoops = -1;
[bgMusicLoop prepareToPlay];
[bgMusicLoop play];
}
}
- (void)stopBackgroundMusic
{
if(bgMusicLoop)
[bgMusicLoop stop];
bgMusicLoop = nil;
}
- (void)pauseBackgroundMusic
{
if(bgMusicLoop && bgMusicLoop.isPlaying)
[bgMusicLoop pause];
}
- (void)resumeBackgroundMusic
{
if(bgMusicLoop && !bgMusicLoop.isPlaying)
[bgMusicLoop play];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get the Current ViewContext in ASP.Net MVC
I have a ASP.Net MVC JsonResult function in which I want to return the contents of a PartialView (The content has to be loaded using Ajax, and for some reason I can't return a PartialViewResult).
To render the PartialView I need the ViewContext object.
How do you get the current ViewContext object within an Action method? I don't even see HttpContext.Current in my action method.
I am using ASP.net MVC 1.
A:
a ViewContext is not available within the action method because it is constructed later before rendering the view. I would suggest you using MVCContrib's BlockRenderer to render the contents of a partial view into a string.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Display PowerShell mandatory parameter options?
Is there a way to have PowerShell display the options possible for a parameter? I have the following Parameter which requires one of the resource groups in Azure to be selected.
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, HelpMessage = "Enter the name of the resource group you would like to use.")]
[ValidateScript( {$_ -in (Get-AzureRMResourceGroup | Select-Object -ExpandProperty ResourceGroupName)})]
[String]$ResourceGroup
)
ValidateScript will check to see if it is one of the Resource groups in Azure, but my question is how can I display a list of the resource groups so that the person running the script knows what possible options they can input for the parameter? Can I use Write-Host or something within the Param block?
Something like this would be great to display on the line above where they input the value for the parametera (but not static options I want the script to query azure and display the list of resource groups the user can choose):
Please choose one of the following resource Groups: RG1 RG2 RG3 RG4
Thank you.
A:
As PetSerAI mentioned the answer is to use tab completion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why wp_mail() does not work on localhost?
I'm trying to make a contact form, but the wp_mail() does not work. I don't receive any messages.I'm using XAMPP localhost and my code is:
$name = sanitize_text_field($_POST['yourname']);
$email = sanitize_email($_POST['email']);
$subject = sanitize_text_field($_POST['subject']);
$message = sanitize_text_field($_POST['message']);
if ( isset( $_POST['submit']) ) {
//check for empty fields
if ( empty( $name ) || empty( $email ) || empty( $subject ) || empty( $message ) ) {
echo sprintf( '<h5 class="form_erros">%s</h5>', __('Please Fill All Fields!', 'promag') );
}else {
// check if input characters are valid
if ( !preg_match('/[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*/', $name ) ) {
echo sprintf( '<h5 class="form_erros">%s</h5>', __('Please Enter Valid Name!', 'promag') );
}else {
// check if email is valid
if ( !filter_var( $email, FILTER_VALIDATE_EMAIL )) {
echo sprintf( '<h5 class="form_erros">%s</h5>', __('Please Enter Valid E-Mail!', 'promag') );
}else {
// sending the message
$to = get_option('admin_email');
$headers = "From:" . get_option("blogname") . $email . "\r\n";
wp_mail( $to, $subject, $message, $headers, array( '' ) );
echo sprintf( '<h5 class="form_success">%s</h5>', __('Mail Successfully Sent!', 'promag') );
}
}
}
}//endif
A:
It's difficult to get mail working on localhost for a variety of reasons which include the SMTP server not being set up correctly.
I would suggest testing with sendmail first and checking to see if that works - if this does not work then I would suggest moving onto testing your local SMTP server using telnet. It could be that you have network issues whereby the ports needed are not accessible due to your internet provider. As far as I know, some ISP's block these ports specifically to help reduce spam.
One potential solution could be to configure PHP to use an external SMTP server like Google via the php configuration file (php.ini).
The best solution, in my opinion, is to get some shared hosting or a VPS and use that to develop on instead.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cross database search criteria object
In php Codeigniter you can write:
$this->db->select('username')->from->('users')->where('id',5);
Do you know any good lib for java/hibernate that function the same?
Thanks
A:
If you are talking about some kind of typed queries than have a look at Hibernate Criteria API.
When you like it even more typed, than hava a look at the typesave queries provided by the JPA 2.0 functionality of Hibernate (@see http://www.ibm.com/developerworks/java/library/j-typesafejpa/)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
On copyright laws and plots
I was pondering a lot on the issue with copyrights on plots. Is having an identical plot infringing someone else's copyrighted work?
I am fully aware that the character names are copyrighted and cannot be copied. I am also fully aware that the representation of the idea (the words themselves, in substantial amounts) are copyrighted.
But what I'm curious about is the play, the plot points, the storyline, in other words, the idea behind which the words convey.
Let's assume I hold the copyrights of the Harry Potter books.
If someone took all the pages of a Harry Potter book and rewrote each of them in his own words (when I say in his own words, I mean no simple task of rewriting. Paragraphs are removed, changed, added, dialogues changed, added, removed, even the chapters are different, the entire expression is different beyond recognition), plus he had renamed all the characters (e.g. Harry Potter to Gary Potter and so on). Although the entire expression of the idea is beyond different, the entire idea is identical. could I charge him for infringement by the copyright law? Could he publish his plagiarised work and claim copyrights for it?
I see that the Harry Potter movies do not use words copyrighted by the Harry Potter book (spoken words, or written words which are shown on screen). Does it mean that if the movie were to rename all its characters (while having exactly the same plot), it is fully original by the copyright law, and the publishers (or movie makers etc) do not have to pay a single cent to me (the copyright holder of the Harry Potter books)?
Now let's take another example, this time on the web.
If someone rewrote every single post in my blog in his own words and publish it, could I charge him for infringement by the copyright law? Could he publish his plagiarised work and claim copyrights for it?
If someone rewrote all the content of my website (keep in mind that I'm not talking about programming code/design of the webpage) in his own words and publish it, could I charge him for infringement by the copyright law? Could he publish his plagiarised work and claim copyrights for it?
A:
Technically you cannot copyright a plot. However, you can copyright a particular instance of that plot as long as it is not based on an older work in the public domain.
In your Harry Potter example if every chapter had exactly the same incidents and more or less the same dialogue with slightly altered character names you would probably lose in court trying to insist that yours is not just a rip-off. It's an area where the discretion of the court would come into play and you would probably be on the losing end of that discretion.
If, on the other hand, you wrote a story about a guy called Peter Thompson who, it turned out, was the son of the Greek god Mercury and went to "hero school" where it turned out there was some underlying plot to overthrow Zeus and incite war on Olympus and only Peter had the power to stop the plot with help from his two friends, a male and a female, on a jaunty magic schoolboy type quest JK Rowling's lawyers couldn't touch you.
Unfortunately Rick Riordan's lawyers would nail you to the wall for ripping off his "Percy Jackson" series.
However JK Rowling can't sue Riordan for his thinly disguised Potter rip-off. He's made Jackson sufficiently different that he's safe from the courts of civil law. The court of popular opinion, however, has branded him an unoriginal hack and his stories have not impinged on the public consciousness to anywhere near the degree of the Harry Potter series.
So, basically it's a matter of degree, and there are more ways for your work to be a failure than to be deemed infringing intellectual property in a court of law. On the other hand Riordan's ploy did get him a publisher... make of that what you will.
EDIT:
On your second point. In the electronic arena it matters whether the blog or website presented a work of fiction in which case, see above, or if what it produced was considered "news". In the latter case, well, just look at daily newspapers, they are all in the business of writing up the same source material in their own words. They call it bias. So if what you have on your website is "news" or "information" then it can be copied by someone else in their own words without issue. See also textbooks for examples of the same information rendered by different people in different words. If the work is creative, imaginative and "original" (such that it is not based on information in the public domain) then the rules apply as above.
Finally, to clarify one point I've now made twice. If you decide to write your own version of Snow White someone else may also write theirs with the same sequence of events and even the same character names as long as they don't steal any original elements that you added to the story (like Red Riding Hood's utility belt and addition of her sidekick "Sparrow" the girl wonder). Even then it gets a bit complicated and nothing is certain no matter what Disney's legal team will tell you.
And while I was writing that paragraph I remembered one other thing. Technically if what you have written is deemed "satire" in some areas that gives it special protection under "freedom of speech" a court ruling once set a precedent that zombies were a satirical device therefore adding zombies to anything instantly protects it as satire. This is, of course, a broad interpretation but it does serve as an example that all I have written is suspect and you never can be sure.
SECOND EDIT: And on your point about a movie that was very similar but sufficiently different not to occasion a lawsuit see National Treasure. The story goes that Disney wanted to buy the rights to The Da Vinci Code and lost the bid, so they made National Treasure. As you may note National Treasure is so sufficiently different from TDVC that it exists now as a thing in its own right having features not shared by the original work (e.g. IMO "fun"). Therein lies the problem in such a ploy. People who love "Lord of the Rings" want to see "Lord of the Rings" they don't want to see "Halfling and Elfboy's Bogus Questathon", so essentially by making your product sufficiently different you have also ensured it will have its own audience leaving the audience for the original pristine and unsullied.
A:
CAVEAT: I am not a lawyer.
At the level you're describing, yes, this is copyright infringement.
Basically, if it's easy to demonstrate that your work is "substantially similar" to another piece, to which you had access, then infringement can be proved. Working with similar themes, plot elements, and tropes generally doesn't constitute such extreme similarity, but if you're talking about rewriting a piece at a paragraph-by-paragraph level, merely re-wording without changing content or theme, then that's an easy case against you.
Note that there are plenty of retellings which don't constitute infringement - but they need to add or change something substantial. West Side Story 'wouldn't infringe on Romeo and Juliet (even if that illustrious work weren't long out of copyright) because it's a retelling in an entirely different era and setting, and these elements change the story. Barry Trotter and the Shameless Parody doesn't infringe on Harry Potter because it's a parody. Wicked doesn't infringe on Wizard of Oz because it retells the story from a vastly different POV, and is a riff on the Oz mythos. Also, "substantial similarity" can be vague and tough to prove, so even fairly blatant rip-offs can avoid infringement.
But a simple line-by-line rewriting - the same elements, characters and events in the same configuration - would be shot down pretty easily.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
local database will not deploy to Azure
I am new to Azure & have searched everywhere but here for help. I have a local MVC 5 app w/ simple database. I am using VS 2015 Community w/ all updates.
Problem: Using visual studio, my web app works perfectly in Azure, BUT my local database will not deploy. The db works perfect locally, but when I deploy, only the web app shows up...the database is not there in Azure. I get a generic message saying "There was an error processing your request". I have tried creating the db in Azure and connecting w/ no luck. Everything but the database deploys. Any suggestions are appreciated. Thanks, everybody.
Jeff
A:
You do not deploy the database in Azure. Instead, you create a database in Azure, and then, under deployment, you point your app's connectionstring to that instead.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If you don't need to breathe, what new opportunities open up for places to live?
To work around the space suits are SCUBA gear problem, I was wondering if it wouldn't make more sense to just bypass the lungs and their vent hole altogether and to oxygenate blood and remove CO2 (and possibly other exotic toxins) by routing it through an external machine. Maybe something light you can strap to your back or arm.
I mean... babies do this for several months before they're born, right?
Now it's self-evident that bypassing the lungs and doing away with the pressure suit won't offer any protection from heat, cold, or radiation, and you'd have to deal with those by other means or avoid those situations.
What it does offer is protection from some range of noxious atmospheres, the removal of acute vulnerability to punctures, and the freedom to talk (atmosphere permitting) and eat and poop (universe permitting) and bathe and change your clothes and generally to stay in those environments for as long as you can find fresh oxygen and power for your oxygen machine (and it may be harvesting what it needs from the local environment anyway).
It also obviates a weakness of human lungs that they only work in a restricted pressure range. A narrower range than a human might be able to endure otherwise (not a complete vacuum, but beyond 40000 ft Earth altitude).
But maybe it's not as simple as all that. Perhaps environments that seem otherwise benign are actually substantially less survivable than it would appear. The skin provides a porous interface to the local atmosphere, for example. It may allow reactions with the environment that are unhealthy or dangerous, or the local environment may obstruct reactions which are essential.
Wandering about on Wikipedia, methane and carbon dioxide atmospheres seem not uncommon, but anywhere we know that well has other serious blockers for human habitation (radiation and cold, mostly; also, wrong gravity). If not for those other problems, would they be safe environments?
A:
Addressing the question at hand...
If the body was coated in latex (yes like a condom) to maintain internal pressure, and that latex was coated with silicone for insulation/protection and that silicone was coated/covered with something abrasion resistant, you could probably survive in a vacuum. But not in space because radiation would cook you and micrometeorites would perforate you, and on the top of mount Everest the cold would kill you pretty quickly unless you had more layers of insulation.
Really the most useful aspect of not having to breathe is that you can avoid inhaling asbestos, viruses, toxins, spores, pollen, farts, and bugs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OS Concepts Terminology
I'm doing some fill in the blanks from a sample exam for my class and I was hoping you could double check my terminology.
The various scheduling queues used by the operating system would consist of lists of processes.
Interrupt handling is the technique of periodically checking to see if a condition (such as completion of some requested I/O operation) has been met.
When the CPU is in kernel mode, a running program has access to a restricted set of CPU functionality.
The job of the CPU scheduler is to select a process on the ready queue and change its state.
The CPU normally supports a vector of interrupts so the OS can respond appropriately when some event of interest occurs in the hardware.
Using traps, a device controller can use idle time on the bus to read from or write to main memory.
During a context switch, the state of one process is copied from the CPU and saved, and the state of a different process is restored.
An operating system consists of a kernel and a collection of application programs that run as user processes and either provide OS services to the user or work in the background to keep the computer running smooth.
There are so many terms from our chapters, I am not quite sure if I am using the correct ones.
A:
My thoughts:
1. Processes and/or threads. Jobs and tasks aren't unheard of either. There can be other things. E.g. in MS Windows there are also Deferred Procedure Calls (DPCs) that can be queued.
2. This must be polling.
4. Why CPU scheduler? Why not just scheduler?
6. I'm not sure about traps in the hardware/bus context.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex for substring of comma separated list
I'm a beginner to regex, so I apologize in advance if this is a naive question!
I have a string with two values separated by a comma: 12.345678,23.45678901
I am trying to use regex (this is a requirement) to return the first value with 3 decimals 12.345 and the second value with 2 decimals 23.45.
Ideally, the full regex match would be 12.345,23.45
I am able to get the first value 12.345 using the following regex: ^\d+\.\d{0,3}.
This works well because it only returns the full match (there is no Group 1 match). But I'm pretty stumped on how to get the second value 23.45 to be returned in the same string.
I've also tried this regex:
(^.{0,6})(?:.*)(,)(.{0,5}), which correctly parses the first and second values, but the full match is being returned with too many decimals.
Full match: 12.345678,23.45
Group 1: 12.345
Group 2: ,
Group 3: 23.45
Any suggestions are welcome! Thank you in advance.
A:
You can use this regex to get your data:
^(\d+\.\d{3})\d*,(\d+\.\d{2})\d*$
It looks for digits followed by . and 3 decimal places (first capture group), then some number of digits followed by a comma (discarded) and then digits followed by a . and 2 decimal places (second capture group), followed finally by some number of digits and the end of string (discarded).
To use in PHP
$str = '12.345678,23.45678901';
preg_match('/^(\d+\.\d{3})\d*,(\d+\.\d{2})\d*$/', $str, $matches);
echo "first number: {$matches[1]}\nsecond number: {$matches[2]}\n";
Output:
first number: 12.345
second number: 23.45
Demo on 3v4l.org
If you need to get both matches in the $matches[0] array (using preg_match_all), you can use this regex:
(?<=^)\d+\.\d{3}(?=\d*,)|(?<=,)\d+\.\d{2}(?=\d*$)
This regex looks for either
the start of string followed by some digits, a . and 3 digits (followed by some number of digits and a comma); or
a comma, some number of digits, a . and 2 digits (followed by some number of digits and the end of string).
To avoid capturing the unwanted data it is checked for using positive lookaheads and lookbehinds.
Demo on 3v4l.org
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get MessageBuilder status in Protocol Buffers?
When using Message.Builder.build() an exception is thrown when a required field is not set. Is there way to find out if the exception will be thrown? i.e. something like an iSReadyToBuild? There is a buildPartial method but it does not say whether the build was complete or partial.
A:
The method you are looking for is called "isInitialized()".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to force wrapped text to be right justified?
I have a column header where there is very limited horizontal space.
But I can afford a bit of vertical space so I've enabled wrapping.
My question is this: is there a way for me to force the wrapped text to be right-justified rather than left-justified.
In other words... it's wrapping like this:
Model
Validation
But I would prefer it to wrap more like this:
.....Model
Validation
Is there a way to do this in CSS?
A:
I believe text-align: right should fix this
|
{
"pile_set_name": "StackExchange"
}
|
Q:
merge ALMOST duplicate records IN sql
Greeting all...
i have two table and their structure is identical...
Table logDetail
Date Time CardID Status
2012-01-20 00:00:00 A1 ABSENT
2012-01-20 00:00:00 B1 ABSENT
2012-01-20 00:00:00 C3 ABSENT
2012-01-20 00:00:00 D1 ABSENT
Table preStatus
Date Time CardID Status
2012-01-20 07:00:10 A1 COMING
2012-01-20 07:10:00 C3 COMING
2012-01-20 08:00:00 B1 LATE
2012-01-20 17:00:00 B1 BACK
2012-01-20 17:10:10 A1 BACK
2012-01-20 17:13:00 C3 BACK
After Merge
Date
2012-01-20 07:00:10 A1 COMING
2012-01-20 07:10:00 C3 COMING
2012-01-20 08:00:00 B1 LATE
2012-01-20 00:00:00 D1 ABSENT
2012-01-20 17:00:00 B1 BACK
2012-01-20 17:10:10 A1 BACK
2012-01-20 17:13:00 C3 BACK
How may i merge these two table because in table b there is duplicate records and when i do
a merge...
merge into logDetail as Target
using preStatus as Source
on Target.L_Date=Source.L_Date
and Target.L_Time='00:00:00'
and Target.L_CardID=Source.L_CardID
when matched then
update set Target.L_Status=Source.L_Status,
Target.L_Time=Source.L_Time
when not matched then
insert (L_Date,L_Time,L_CardID,L_Status)
values(Source.L_Date,Source.L_Time,Source.L_CardID,Source.L_Status);
it said The MERGE statement attempted to UPDATE or DELETE the same row more than once
Any help is greatly appreciated.
A:
You don't appear to want to merge the tables, since CardID is not a primary key.
It looks like you want to retain the entries where Status = "COMING" even when there are new entries where stats = "BACK".
I suggest you do this in two steps, first do inserts of the preStatus data, then delete "ABSENT" rows where there exists "COMING" and "BACK" rows.
/* Insert new data */
insert logDetail
select * from preStatus
/* Delete Absent rows where there is a COMING or BACK row for the same item on the same day */
Delete logDetail
from logDetail ld1
where
/* Absent rows only */
ld1.time = '00:00:00'
and ld1.Status = 'ABSENT'
/* And there must be a COMING or BACK row for the same card on the same day */
and exists (
select 1 from logDetail ld2
where ld2.Date = ld1.Date
and ld2.CardID = ld1.CardID
and ld2.Time > '00:00:00'
and ld2.Status <> 'ABSENT'
)
To remove rows for the same Date, CardID, and same Status, but where there is a later Time:
Delete logDetail
from logDetail ld1
where
ld1.status in ('COMING', 'BACK')
/* COMING or BACK row only */
/* for the same card on the same day, with a later time*/
and exists (
select 1 from logDetail ld2
where ld2.Date = ld1.Date
and ld2.CardID = ld1.CardID
and ld2.Status = ld1.Status
and ld2.Time > ld1.Time
)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ and ode system: how to handle it?
I want to code a class to solve systems of ODEs with Euler method in C++ (I'm a beginner). If the equation is scalar, there's no problem, since I can store the solution in a vector or I can dinamiccaly allocate an array with double* sol = new double[N_points]
Things starts to get weird to me if I have to handle matrices, so my question is: **should I use some library as Eigen? Or should I struggle with pointers?
I'm looking for some good way/reference to be sure which is the correct/best method to handle such a situation.
A:
If you want to work with matrices you can do this with array of arrays, or use a simplified abstraction layer with an one dimensional array (or vector) to store the matrix data, like:
std::vector<double> matrix(row * columns);
To access an item, you can use simple arithmetic, like:
int index = rowIndex * totalColumns + columnIndex;
double item = matrix[index];
You can have a look at my DoubleMatrix library (not use it, just check out) to have an examples of this implementation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IF UPDATE in trigger returns true when no rows were affected
Why is the trigger executing the update(col1) block in the following:
USE tempdb
go
CREATE TABLE t1(id INT, col1 VARCHAR(10))
go
INSERT INTO dbo.t1( id, col1) VALUES(1,'aa'),(2,'sdf'),(3,'fg')
go
CREATE TRIGGER r_test ON t1 after UPDATE
AS
PRINT 'Trigger'
IF UPDATE(col1)
PRINT 'col updated'
GO
UPDATE t1 SET col1='werwer' WHERE id=4
output
col updated
I understand why the trigger executed but since id = 4 doesn't exist, shouldn't UPDATE(col1) be returning false?
A:
Because IF UPDATE(col1) only checks if col1 was referenced in the UPDATE statement. It does not check how many rows were affected, nor does it check if the value has actually changed.
To not get the trigger to fire when zero rows are affected:
CREATE TRIGGER dbo.r_test
ON dbo.t1 after UPDATE
AS
BEGIN
IF @@ROWCOUNT > 0
BEGIN
...
END
END
Note that MERGE may complicate this - @@ROWCOUNT can be non-zero even if no rows are updated, only inserted/deleted (more details here).
Instead you can:
CREATE TRIGGER dbo.r_test
ON dbo.t1 after UPDATE
AS
BEGIN
IF EXISTS (SELECT 1 FROM inserted)
AND EXISTS (SELECT 1 FROM deleted)
BEGIN
...
END
END
To determine if the value has changed:
IF EXISTS
(
SELECT 1
FROM inserted AS i
INNER JOIN dbo.t1 ON i.id = t1.id
WHERE i.col1 <> t1.col1
);
This is grossly simplified; NULLs will complicate this, as will columns with encrypted values.
Also, please always use the schema prefix.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What differences are there between labelling options that appear under /dev/disk/by-label and /dev/disk/by-partlabel?
I want to create a disk under CoreOS that is automatically mounted at /var/lib/docker
So I created a var-lib-docker.mount unit file to do it and decided to use the by-label path under /dev/disk.
Initially I found my partitions appear under the by-partlabel path.
It works great however.
In the process I found out that there is a program called e2label, and also under fdisk expert mode I can also create a partition label.
Having not found e2label initially I found I could label partitions with the word "DOCKER" in fdisk. But they actually come through to the path /dev/disk/by-partlabel and not /dev/disk/by-label
What are the differences between these? should one be favoured over the other?
A:
The ArchLinux wiki has (as always) good documentation on this issue. You wrote:
Having not found e2label initially I found I could label partitions
with the word "DOCKER" in fdisk. But they actually come through to the
path /dev/disk/by-label
I assume you meant "do NOT come through"? That could be explained by the fact that you created a partition label and your labeled disk should show up under /dev/disk/by-partlabel/ instead. Once you create a filesystem label (e.g. via e2label (tune2fs -L) for ext{2,3,4} file systems), the disk should show up under /dev/disk/by-label.
should one be favoured over the other?
partition labels are only available for GPT disks. For filesystem labels one would need some filesystem tool to apply a label to the partition. All major on-disk file systems seem to have this (tune2fs -L, jfs_tune -L, xfs_admin -L, reiserfstune -l) so unless it's something more exotic, file system labels should work just fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VLQ answer flag disputed, despite the answer's being in the wrong language. Why?
I recently came across an answer in the wrong language and thought "I'll save anyone else from having to see this!" I flagged it as VLQ believing it a good fit:
This content should not exist. Delete it. Now. It is not salvageable through editing.
I mean, maybe not "delete it now" like it's urgent...but definitely delete it.
I figure either
I'm wrong and the answer deserves (according to a mod or queue voters) to live on forever or
I should have used a custom flag saying "read the comments, where the
author says it's garbage"
...but can't figure out which it is.
A:
It wouldn't be obvious to many viewers that this answer wasn't just wrong. It wasn't obvious to me; I don't use Perl or Ruby, so I had to look up a few things to confirm the claims made in the comments.
At which point I did delete the answer.
VLQ is pretty hit & miss with stuff like this; if it isn't obvious to whoever is reviewing the flag, it probably won't seem very low quality. I would tend to recommend you just flag as "in need of moderator intervention" and type a succinct explanation, something like "author mistook this for a Perl question, answer is irrelevant and potentially slows down future readers".
A:
I have a differing, or possibly a clarifying, position... Please consider these three scenarios:
First scenario:
Somebody asks a programming question about an algorithm and I provide an answer using pseudocode.
Second scenario:
Somebody asks a programming question tagged vb-net about an algorithm and I provide an answer using pseudocode
Third scenario:
Somebody asks a programming question tagged vb-net about an algorithm and I provide an answer using C#
Now, of the above three scenarios, which are acceptable, and which should be deleted because they are Very Low Quality (aka unsalvageable junk)?
I'd argue that all of them are acceptable. The first scenario is obviously acceptable. Pseudocode is always an option for describing how one would construct an algorithm.
The second scenario is also acceptable. I might not have provided the OP a compilable solution to their problem, but I have provided them information they may use to construct one on their own. We do not delete answers that are incomplete or that contain syntax errors. As long as the answer attempts to help the OP with their issue, they are worth something.
Now, the third scenario... Should this be deleted? I would argue not, as an answer in another language is still a form of pseudocode. The OP would still have to read and understand the pseudocode (so, please hold your counter-examples of Brainfuck pseudocode, thanks) and then construct their solution in their guttural language of choice, but it is still equivalent to the second scenario.
I'd suggest judging the answer on the basis of whether or not the OP could use the information provided in the answer in their own language after translation, and voting appropriately. If the example relies on elements not available in the OP's platform (e.g., javascript pseudocode + jquery to answer a VB question), then that is worthy of a downvote, comment, and if truly egregious--a delete vote. But if that pseudocode-that-seriously-looks-like-C# answer contains what the OP needs, then toss 'em an upvote.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirecting Urls via PHP without htaccess
I want to redirect my urls but not with htaccess, only with php. I know that I have to use the header() function. But my question is how to catch the url.
For example, Wordpress catches urls like mysite.com/postname and redirects it to other urls, I think it is index.php?parameters=values.
But my question how to catch the url mysite.com/postname and redirect it to other. Which php script will catch it.
Or when wordpress catch the url, which php file redirects it to index.php
A:
You need to tell your HTTP server that the URL is handled by the PHP script.
You can't do this with PHP directly: If the server never runs the PHP script, then the PHP script can't do anything with the request!
This is most commonly done with mod_rewrite which is configured using Apache configuration. There are two basic places that you can put mod_rewrite directives.
The main Apache configuration files
A .htaccess file.
The former is recommended:
You should avoid using .htaccess files completely if you have access to httpd main server config file. Using .htaccess files slows down your Apache http server. Any directive that you can include in a .htaccess file is better set in a Directory block, as it will have the same effect with better performance.
… and you've rejected .htaccess so put the directives in your main configuration file.
This, of course, assumes you are using Apache HTTPD. You didn't say which HTTP server you were using.
This also assumes that when you rejected .htaccess you didn't mean mod_rewrite. Many people conflate the two since changes to mod_rewrite settings are the most common things that programmers (as opposed to System Administrators) want to do in an Apache configuration.
For example, Wordpress catches urls like mysite.com/postname and redirects it to other urls
Wordpress uses mod_rewrite directives in a .htaccess file.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSProj Conditionals for different DLLs triggered by build configurations
I'm attempting to modify my .csproj files to handle some native and (managed) wrapper assemblies based upon the targeted build configuration (specifically $(Platform)). A specific example (though not the only one) is I'm using Oracle.DataAccess which comes mutually exclusively targeting 32-bit or 64-bit, but not both. Additionally, it has dependencies on 32-bit and 64-bit (respectively) native DLLs. This example creates a problem for me. The reason I want this triggered based on the build configuration is because we are frequently having to switch back and forth for a variety of reasons.
Problem:
I include the native DLLs by having them in a project's root directory (as a linked file pointing to a lib folder), flagging them as Content with AlwaysCopy set. This results in them being copied to my bin folder as desired. I attempted to do this by having two ItemGroup blocks with Condition="'$(Platform)' == 'x86'" (and x64) but this seems to not work as I get build errors saying "The file ..\packages\OracleClient\64BitNativeDrivers\xxx.dll' could not be added to the project. There is already a file of the same name in this folder.", even after a very thorough cleaning of the solution's artifacts.
Code snippet:
<ItemGroup Condition="'$(Platform)' == 'x86'">
<Content Include="..\packages\OracleClient\32BitNativeDrivers\oci.dll">
<Link>oci.dll</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="..\packages\OracleClient\32BitNativeDrivers\oraociicus11.dll">
<Link>oraociicus11.dll</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="..\packages\OracleClient\32BitNativeDrivers\OraOps11w.dll">
<Link>OraOps11w.dll</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
<Content Include="..\packages\OracleClient\64BitNativeDrivers\oci.dll">
<Link>oci.dll</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="..\packages\OracleClient\64BitNativeDrivers\oraociicus11.dll">
<Link>oraociicus11.dll</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="..\packages\OracleClient\64BitNativeDrivers\OraOps11w.dll">
<Link>OraOps11w.dll</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
I've tried playing around with a few possibilities here but it seems I'm misunderstanding how to do this properly and I could really use some help.
Thanks!!
A:
Did you try putting the filter
Condition="'$(Platform)' == 'x86'"
on the <Content> tag ?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show an image preview before upload
In my HTML form I have input filed with type file for example :
<input type="file" multiple>
Then I'm selecting multiple files by clicking that input button.
Now I want to show preview of selected images before submitting form . How to do that in HTML 5?
A:
HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .
Here's a quick example that makes use of the FileReader class to read an image as DataURL and renders a thumbnail by setting the src attribute of an image tag to a data URL:
The html code:
<input type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById("files").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
Here's a good article on using the File APIs in JavaScript.
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />
<output id="list"></output>
A:
Here I did with jQuery using FileReader API.
Html Markup:
<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>
jQuery:
Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message
$("#fileUpload").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
Detailed Article: How to Preview Image before upload it, jQuery, HTML5 FileReader() with Live Demo
A:
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />
<output id="list"></output>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
External dictionary reading behavior in a class
I have found this behavior that I can not understand. I state that this is a simplification of the problem I'm having, since the dictionary in my script has a lot more items.
configuration = {
"video": {
"fullscreen": {
"user": None,
"default": False
}
}
}
class test():
fullscreen = configuration["video"]["fullscreen"]["user"]
def __init__(self):
print(configuration)
print(configuration["video"]["fullscreen"]["user"])
print(self.fullscreen)
if __name__ == "__main__":
configuration["video"]["fullscreen"]["user"] = True
t = test()
This is the result:
{'video': {'fullscreen': {'user': True, 'default': False}}}
True
None
Why in the third print the result is "None"?
A:
Ciao,
actually the explanations given so far to your question were not really totally clarifying to me the order of instructions execution in your more-than-legitimate question. I think I perfectly understood what you meant and it puzzled me too
The following example will show you that the class attribute user_conf [renamed to avoid focusing on the wrong point] is created before running configuration["video"]["fullscreen"]["user"] = "John" in the main(). In other words - at pure class attribute level - its value is set from the configuration blueprint. It will be only the class constructor - called after the main - to update that value later
configuration = {
"video": {
"fullscreen": {
"user": None,
"default": False
}
}
}
# correcting global variable blueprint
# configuration["video"]["fullscreen"]["user"] = "John"
class test():
print(configuration["video"]["fullscreen"]["user"])
user_conf = configuration["video"]["fullscreen"]["user"]
print(user_conf)
def __init__(self):
# printing modified global variable, all right
print(configuration)
print(configuration["video"]["fullscreen"]["user"])
print(self.user_conf)
self.user_conf = "Jack"
print(self.user_conf)
def main():
# modifying global variable later
# at this point the class attribute user_conf has already been assigned with the old value
configuration["video"]["fullscreen"]["user"] = "John"
test()
if __name__ == '__main__':
main()
Please notice that if you comment the value update in the main and uncomment these lines that I added:
# correcting global variable blueprint
# configuration["video"]["fullscreen"]["user"] = "John"
just after the configuration declaration you will have the output without any None that you were expecting to find, because the class attribute will be created by a "corrected" blueprint. In this case then you will get:
John
John
{'video': {'fullscreen': {'user': 'John', 'default':
False}}}
John
John
Jack
Another way to produce this tweaking the sample at point 6 here:
def outer():
configuration = {
"video": {
"fullscreen": {
"user": None,
"default": False
}
}
}
print("initial outer configuration:", configuration)
def inner():
nonlocal configuration
'''
configuration = {
"video": {
"fullscreen": {
"user": "John",
"default": False
}
}
}
'''
configuration["video"]["fullscreen"]["user"] = "John"
print("inner configuration:", configuration)
inner()
print("modified outer configuration:", configuration)
outer()
which would give:
initial outer configuration: {'video': {'fullscreen': {'user': None,
'default': False}}} inner configuration: {'video':
{'fullscreen': {'user': 'John', 'default': False}}} modified
outer configuration: {'video': {'fullscreen': {'user': 'John',
'default': False}}}
Hope this can solve better your doubt
Edit after the OP comment: as I openly declared it took me some time to figure out what is happening. Let's take this code:
configuration = {
"video": {
"fullscreen": {
"user": None,
"default": False
}
}
}
print("step 1 -> " + str(configuration))
# correcting global variable blueprint
# configuration["video"]["fullscreen"]["user"] = "John"
class test():
print("step 2 -> " + str(configuration))
user_conf = configuration["video"]["fullscreen"]["user"]
def __init__(self):
# printing modified global variable, all right
print("step 5 -> constructor reads the updated value: " + str(configuration))
def main():
# modifying global variable later
# at this point the class attribute user_conf has already been assigned with the old value
print("step 3 -> " + str(configuration))
configuration["video"]["fullscreen"]["user"] = "John"
print("step 4 -> main just updated the global variable: " + str(configuration))
test()
if __name__ == '__main__':
main()
Printing this will give you the following output:
step 1 -> {'video': {'fullscreen': {'user': None, 'default': False}}}
step 2 -> {'video': {'fullscreen': {'user': None, 'default':
False}}} step 3 -> {'video': {'fullscreen': {'user': None,
'default': False}}} step 4 -> main just updated the global
variable: {'video': {'fullscreen': {'user': 'John', 'default':
False}}} step 5 -> constructor reads the updated value:
{'video': {'fullscreen': {'user': 'John', 'default': False}}}
Now, if you read this answer you will easily understand that Python is executed top to bottom and executing a def block - in our case __init__(self) - doesn't immediately execute the contained code. Instead it creates a function object with the given name in the current scope which is actually entered only after calling test() from main(), i.e. only after you ask to instance an object from the test() class, which will trigger its constructor
IMPORTANT: in your case I realized that you are calling the class test() and test() is what you are calling from main(). Your main is calling a method actually, test(): so please replace class test() with def test() in the previous code and you will get a different and more understandable execution flow:
step 1 -> {'video': {'fullscreen': {'user': None, 'default': False}}}
step 3 -> {'video': {'fullscreen': {'user': None, 'default':
False}}} step 4 -> main just updated the global variable:
{'video': {'fullscreen': {'user': 'John', 'default': False}}}
step 2 -> {'video': {'fullscreen': {'user': 'John', 'default':
False}}}
After the first print all the def blocks are skipped and we enter the main(). The main() updates the global variable and then the test() function would work immediately on the updated value. Of course the constructor in this case would not be triggered [this is not anymore a class] and this explains the lack of step 5
-> are you sure you are making a good choice in defining and using your class in this way? [probably not]
-> isn't it better to declare test() as def instead that as class? [I really think so]
Have a good day
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Import node from one XML to another on PowerShell
I need to copy node with name "ProjectOptions" from default.xml to original.xml without modifying anything else:
Original.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<KEYS>
<KEY ObjectName="computername_user" RegObjectType="0">
<KEYS>
<KEY ObjectName="Desktop" RegObjectType="0">
<KEYS>
<KEY ObjectName="Settings" RegObjectType="0">
<KEYS>
<KEY ObjectName="PrinterDefault" RegObjectType="0">
<VALUES>
<VALUE ObjectName="PrinterOrientation" Value="2" ValueType="4" />
</VALUES>
</KEY>
<KEY ObjectName="ProjectOptions" RegObjectType="0">
<VALUES>
<VALUE ObjectName="ShowWelcomeMsg" Value="0" ValueType="4" />
</VALUES>
</KEY>
</KEYS>
</KEY>
</KEYS>
</KEY>
</KEYS>
</KEY>
</KEYS>
Default.xml
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<KEYS>
<KEY ObjectName="computername_user" RegObjectType="0">
<KEYS>
<KEY ObjectName="Desktop" RegObjectType="0">
<KEYS>
<KEY ObjectName="Settings" RegObjectType="0">
<KEYS>
<KEY ObjectName="PrinterDefault" RegObjectType="0">
<VALUES>
<VALUE ObjectName="PrinterOrientation" Value="2" ValueType="4"/>
</VALUES>
</KEY>
<KEY ObjectName="ProjectOptions" RegObjectType="0">
<VALUES>
<VALUE ObjectName="GSAddBatchOptionDialogRect" Value="381,203,981,629" ValueType="2"/>
<VALUE ObjectName="GSHeadNodeName" Value="" ValueType="2"/>
<VALUE ObjectName="GSIsAdvancedMode" Value="1" ValueType="4"/>
<VALUE ObjectName="GSRemoteSchedulerPlatform" Value="" ValueType="2"/>
<VALUE ObjectName="GSSchedulerName" Value="" ValueType="2"/>
<VALUE ObjectName="GSShowFrequentlyUsedBatchOptions" Value="1" ValueType="4"/>
<VALUE ObjectName="GSUserName" Value="" ValueType="2"/>
<VALUE ObjectName="ShowWelcomeMsg" Value="0" ValueType="4"/>
</VALUES>
</KEY>
</KEYS>
</KEY>
</KEYS>
</KEY>
</KEYS>
</KEY>
</KEYS>
I tried something like this
$xml = [xml](Get-Content "C:\Temp\original.xml")
$xmld = [xml](Get-Content "C:\Temp\default.xml")
$Child=$xml.KEYS.KEY.KEYS.KEY.KEYS.KEY.KEYS.KEY[1].VALUES.VALUE
$xml.DocumentElement.InsertAfter($XML.ImportNode($xmld.SelectSingleNode("//KEY[@ObjectName = 'ProjectOptions']"), $true), $Child)
$xml.Save("C:\Temp\save.xml")
But it ended with "The reference node is not a child of this node."
Please tell me where I went wrong.
Thanks.
A:
You try to insert the imported node under the DocumentElement node, but $Child is not a direct child element of that node. You need to call the InsertAfter() method on the parent node of $Child.
Change this:
$xml.DocumentElement.InsertAfter($XML.ImportNode($xmld.SelectSingleNode("//KEY[@ObjectName = 'ProjectOptions']"), $true), $Child)
into this:
$Child.ParentNode.InsertAfter($XML.ImportNode($xmld.SelectSingleNode("//KEY[@ObjectName='ProjectOptions']"), $true), $Child)
and the problem will disappear.
As a side note, you may want to use an XPath expression instead of dot-notation for selecting $Child:
$Child = $xml.SelectSingleNode('//VALUE[@ObjectName="ShowWelcomeMsg"]')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP Баг при записи файла
$fullcont3 = 'content/content1.txt';
$article3 = '';
if (file_put_contents($fullcont3, $article3) === TRUE) {
echo "TRUE";
} else { echo "FALSE"; }
// Возвращает FALSE но файл записывается
// Собственно вопрос в том , почему FALSE возвращает?
Думаю потому что , возвращает количество байтов записанных в файл , в данном случае возвратит 0 , а 0 === FALSE
A:
file_put_content Возвращает либо количество байтов (число), либо FALSE.
Он никогда не возвращает TRUE.
C учетом проверки на тождественность, первый If никогда не выполняется.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Toggle the GPS to "North up"
In GTA V, is there any way to toggle the GPS screen to be in a fixed position so that North is always up? I like to know which direction I am going without having to pause to look at the map, or to look at the angles of the shadows!
A:
If you look closely on the mini-map, there is a small 'N' which shows which direction the North is. It moves around all over the map border and is not always towards UP but, you can use it to align yourself towards North.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
help need for sql query, select latest 5 lists of each category
I am using MySQL, I have a database table with items and 5 categories(also one ID field, autoincr,PK) I have to select latest 5 items of each category, when I use group by it return latest one item of each category, how can I get top 5 items of each category in a single query ?
Thank you
A:
You properly going to hate this ...
(select * from items where category_id=1 order by add_date desc limit 5)
union
(select * from items where category_id=2 order by add_date desc limit 5)
union
(select * from items where category_id=3 order by add_date desc limit 5)
union
(select * from items where category_id=4 order by add_date desc limit 5)
union
(select * from items where category_id=5 order by add_date desc limit 5);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to bypass Asp.net control validation only for few control on button click?
I have an ASP.NET form that takes input from a user. There is a Save & Add button on the form to perform different functionalities.
The problem I'm having is that on the form I have a set of validators and when the Add button is pressed the form gets validated. There are 5 controls on the page but during Add button click , I need to validate only two controls. Only during Save button click, I should validate all controls.
How to ignore those 3 control validation during Add button click.
Any way around this?
A:
To skip some of the validations I suppose you might want to use ValidatorEnable method in jquery to enable/disable. Something like this:
Email:
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valEmail" ControlToValidate="txtEmail" runat="server"
ErrorMessage="*Required" ForeColor="Red" ValidationGroup="Group2" />
<br />
Enable Validation:
<input type="checkbox" id="CheckBox2 checked="checked" />
<br />
<asp:Button Text="Submit" runat="server" ValidationGroup="Group2" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#CheckBox2", function () {
var valEmail = $("[id*=valEmail]");
ValidatorEnable(valEmail[0], $(this).is(":checked"));
});
</script>
Here is the live Demo in case you want to test it before heading towards its implementation: https://www.aspsnippets.com/demos/642/
EDIT
To achieve this task using pure javascript and not jquery you can do something like this:
ValidatorEnable(document.getElementById('<%=yourValidator.ClientID%>'), false);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
mono Newbie. Installed but env vars not set.. maybe things missing
I'm just installing mono to learn how it all works.
I installed mono (mono-2.10.9-gtksharp-2.12.11-win32-0.exe) for the first time and just started to follow on through the Mono Basics page to verify the installation.
http://www.mono-project.com/Mono_Basics
I was surprised that the installer didn't set up the PATH env variable , but once I'd done that I was able to get the first example compiling/running.
But I'm getting compile errors on the second example. So am wondering if I am missing further environment variables/settings?
Are the environment variables used by mono documented anywhere?
I'm also just wondering if the installer is ok or should I be looking for another one...
The error messages are as follows:
C:\Users\Vida\Desktop\Learning\Mono>gmcs hello.cs -pkg:gtk-sharp-2.0
error CS2001: Source file `Files' could not be found
error CS2001: Source file
`(x86)/Mono-2.10.9/lib/mono/gtk-sharp-2.0/pango-sharp.dll' could not
be found
error CS2001: Source file
`(x86)/Mono-2.10.9/lib/mono/gtk-sharp-2.0/atk-sharp.dll' could not
be found
error CS2001: Source file
`(x86)/Mono-2.10.9/lib/mono/gtk-sharp-2.0/gdk-sharp.dll' could not
be found
error CS2001: Source file
`(x86)/Mono-2.10.9/lib/mono/gtk-sharp-2.0/gtk-sharp.dll' could not
be found
error CS2001: Source file
`(x86)/Mono-2.10.9/lib/mono/gtk-sharp-2.0/glib-sharp.dll' could not
be found
Compilation failed: 6 error(s), 0 warnings
A:
Sounds like some component is confused by the spaces in Program Files (x86) (which is presumably the installation directory.) Try setting the PATH using its short name (normally Progra~2) , or reinstall to a directory that doesn't have spaces. You can also try additionally setting the MONO_PATH environment variable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
android passing activity.this to method
I have an app with lots of activities and almost on each I am creating a table filling with sqlite data like this:
if (cursor != null) {
cursor.moveToFirst();
TextView data;
TableRow row;
int cnt = 0 ;
do {
row = new TableRow(myActivity.this);
row.setPadding(2,2,2,2);
if (cnt++ % 2 == 0)
row.setBackgroundColor(Color.WHITE);
for (int x = 0; x < cursor.getColumnCount(); x++) {
// arReport[i] += cursor.getString(x);
data = new TextView(myActivity.this);
if (x == 0) {
data.setTypeface(Typeface.DEFAULT_BOLD);
data.setGravity(Gravity.CENTER_HORIZONTAL);
}
data.setText(cursor.getString(x));
row.addView(data);
}
theView.addView(row);
} while (cursor.moveToNext());
theView.setShrinkAllColumns(true);
theView.setStretchAllColumns(true);
}
So I wanted to create a separate class with static method drawTable() which will create this table in each activity on call. However I need to pass activity name as a parameter to that method so I can do row = new TableRow(myActivity.this).. I was trying to replace myActivity.this with getActivity() or just this -- it didnt work. Please suggest what should I use to do that...
A:
You could create the separate class and pass your activity's context in the constructor
public class DbHadler {
Context context;
public DbHandler(Context context) {
this.context= context;
}
public void drawTable(Activity activity) {
//relevent code
Table row;
row = new Table(activity);
}
And then use this class in your activity like this
DbHandler db = new DbHandler(getApplicationContext());
or if fragment then,
DbHandler db = new DbHandler(getContext());
And then its method in your activity like this.
db.drawTable(this);
or if fragment then,
db.drawTable(getActivity());
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Having problems to find the right syntax to select XML info using LINQ-to-XML
I've been using : doc.Descendants("ipAddress") to obtain all IP Addresses from an XML file but now I am trying to obtain only the IP Address for each Network Adapter.
Here is the XML file portion:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<server xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="ServerInfo.xsd" id="57672acc-4ba7-4876-811a-1629eca853ed">
<networkAdapters>
<networkAdapter id="6ad45274-6077-4a46-9b5c-d4e7be712310" name="NVIDIA nForce 10/100/1000 Mbps Networking Controller">
<ipAddresses>
<ipAddress address="192.168.1.1" subnetMask="255.255.255.252" index="0" />
</ipAddresses>
</networkAdapter>
<networkAdapter id="eb872ba4-695e-451a-9505-90b6b0539833" name="TEAM : Command and Control">
<ipAddresses>
<ipAddress address="76.229.35.32" subnetMask="255.255.255.128" index="0" />
<ipAddress address="76.229.35.31" subnetMask="255.255.255.128" index="1" />
<ipAddress address="76.229.35.5" subnetMask="255.255.255.128" index="2" />
</ipAddresses>
</networkAdapter>
</networkAdapters>
</server>
var networkAdapters = doc.Descendants("networkAdapter")
.Select(n => new NetworkAdapter
{
networkAdapterId = new Guid((string)n.Attribute("id")),
serverId = server.serverId,
name = (string)n.Attribute("name")
}).ToList();
List<IpAddress> ipAddressList = new List<IpAddress>();
foreach (var networkAdapter in networkAdapters)
{
IpAddress item = new IpAddress();
//get the network adapter id
item.networkAdapterId = networkAdapter.networkAdapterId;
//need the code to loop through all ip addresses for this particular network adapter????
//{
//item.address = "attribute "address"
//item.subnetMask = "attribute subnetMask"
//item.index = "attribute index"
ipAddressList.Add(item);
//}
}
Any ideas?
Thank you
A:
// get networkAdapter element first
var networkElement = doc.Root
.Element("networkAdapters")
.Elements("networkAdapter")
.First(a => (string)a.Attribute("id") == networkAdapter.networkAdapterId.ToString());
// iterate over ipAddress elements
foreach(var address in networkElement.Element("ipAddresses").Elements("ipAddress"))
{
// you have to declare item here,
// otherwise you'll add the same item more then once to the list
var item = new IpAddress();
item.networkAdapterId = networkAdapter.networkAdapterId;
item.address = (string)address.Attribute("address");
item.subnetMask = (string)address.Attribute("subnetMask");
item.index = (int)address.Attribute("index");
ipAddressList.Add(item);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does Cantor's Proof (that R is uncountable) fail for Q?
Why doesn't the "diagonalization argument" used by Cantor to show that the reals in the intervals [0,1] are uncountable, also work to show that the rationals in [0,1] are uncountable?
To avoid confusion, here is the specific argument.
Cantor considers the reals in the interval [0,1] and using proof by contradiction, supposes they are countable. Since this set is infinite, there must be a one to one correspondence with the naturals, which implies the reals in [0,1] admit of an enumeration which we can write in the form x$_j$ = 0.a$_{j1}$ a$_{j2}$ a$_{j3}$... (for j $\in$ $\mathbb{N}$).
Now Cantor constructs a number x* where the jth digit of x* is (a$_{jj}$+2) mod 10 (I know there are other schemes; this is the one my professor used). The observation that x* $\neq$ x$_j$ $\forall$ j $\in$ $\mathbb{N}$, leads us to the conclusion that x* is not in this list, and hence the reals in [0,1] cannot be enumerated, and so [0,1] is not countable (which implies that the real numbers are not countable).
I asked my professor and she was unable to tell me why this same argument couldn't be used to prove that the rationals in [0,1] are also uncountable. It seems the argument would have to somehow show that the number you constructed using Cantor's method must be either a terminatingor repeating decimal, but I can't see how to prove this
Matt
A:
Why should the decimal expansion constructed from the diagonal of the list yield a rational number? (I.e., why would that decimal expansion be repeating?)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
unexpected end of file when I execute my shell script
I have 3 shell scripts
script1.sh
if [ $# -ne 3 ]
then
# RETURN INVALID USAGE
GetBatchCredentials_Result="Error"
GetBatchCredentials_Reason="Invalid usage: . $0 ApplicationId Alias Logfile"
else
# CONTINUE PROCESSING WITH PARAMETERSLT
RSLT=`/www/inf/xxxx/inf_service_account/2.0/scripts/script2.sh $1 $2 $3`
eval "$RSLT";
fi
script2.sh
# SET UP INFRASTRUCTURE CLASSPATH
. /www/inf/xxxx/inf_service_account/2.0/scripts/script3.sh
PROP="-Dcom.xxxx.env.location.pdc=ITC"
# CALL JAVA GetBatchCredentials TO RETRIEVE THE SERVICE ACCOUNT CREDENTIALS
$JAVA_HOME/bin/java $PROP com.xxxx.inf.serviceaccount.batch.GetBatchCredentials $1 $2 $3
script3.sh
#!/bin/ksh
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/inf-service-account-2.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf_crypto.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf_generics.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf_password_vault.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf-jmx-2.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf-utils-2.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf-env-2.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf-recovery-2.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf-throttle-2.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/inf-trans-2.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/javaee-api-6.0.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/db2jcc.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/db2jcc_license_cu.jar
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_service_account/2.0/dependencies/db2java.zip
export CLASSPATH
My lead wants me to combine all these 3 scripts into one, since there is no point in having 3 separate scripts here. These 3 scripts works fine separately, but I first tried to combine first 2 scripts and I am getitng unexpecetd end of file error when I execute this script:
script1+script2.sh
if [ $# -ne 3 ]
then
# RETURN INVALID USAGE
GetBatchCredentials_Result="Error"
GetBatchCredentials_Reason="Invalid usage: . $0 ApplicationId Alias Logfile"
else
#SET UP INFRASTRUCTURE CLASSPATH
. /www/inf/xxxx/inf_security_common/2.0/scripts/script3.sh
#CALL JAVA GetBatchCredentials TO RETRIEVE THE SERVICE ACCOUNT CREDENTIALS
RSLT='$JAVA_HOME/bin/java com.xxxx.inf.serviceaccount.batch.GetBatchCredentials $1 $2 $3'
eval "$RSLT";
fi
I am running the above scripts using the following script:
testScript.sh
. /www/inf/xxxx/inf_security_common/2.0/scripts/GetBatchCredentials.sh SampleBatchAppId xxxxAlias gbc.log
if [ "$GetBatchCredentials_Result" != "Success" ]
then
echo "Error obtaining FTP Credentials"
echo $GetBatchCredentials_Reason
ret=1
else
echo "Obtained FTP Credentials"
########### FTP User ID ################################
FTP_USR=$GetBatchCredentials_ID
########### FTP Password ###############################
FTP_PWD=$GetBatchCredentials_PW
echo "starting FTP" $FTP_USR $FTP_PWD
fi
Please help me resolve this error.
A:
I am not sure what exactly worked, but I deleted and retyped using vim command. And the new file is working. Here is my new file:
###############################################################################
if [ $# -ne 3 ]
then
# RETURN INVALID USAGE
GetBatchCredentials_Result="Error"
GetBatchCredentials_Reason="Invalid usage: . $0 ApplicationId Alias Logfile"
else
# SET UP INFRASTRUCTURE CLASSPATH
CLASSPATH=$CLASSPATH:/www/inf/xxxx/inf_security_common/2.0/inf-security-common-2.0.jar
export CLASSPATH
# TODO - This needs to be set internally.
PROP="-Dcom.xxxx.env.location.pdc=ITC"
# CALL JAVA GetBatchCredentials TO RETRIEVE THE SERVICE ACCOUNT CREDENTIALS
RSLT=`$JAVA_HOME/bin/java $PROP com.xxxx.inf.serviceaccount.batch.GetBatchCredentials $1 $2 $3`
eval "$RSLT";
fi
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use SQLJ with Eclipse?
There is not a plugin for SQLJ. So which files i have to import to project? How can i make the compiler understand SQLJ commands?
I am currently using JDBC.
A:
The new application development environment for DB2 called IBM Optim Data Studio permits to edit from Eclipse SQLJ files.
http://www-01.ibm.com/software/data/optim/data-studio/
This application is not open source, but it is free to use.
You can also use several products from IBM Rational that includes this feature.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fruit Trees and Pollination
I have a total of 7 fruit trees in my back yard. 3 are multi grafted varieties (Pear, Plum, Apple) which l was told that they will self pollinate each other to produce fruit. I have added three additional apple trees and one cherry tree as well.
My questions are
Will the single trees get pollinated from the multi grafted trees?
will the three different varieties of single apple trees pollinate each other as well?
Is it possible for the cherry tree to be pollinated by these other 6 trees or do I need to plant another cherry tree?
A:
Pollination works within a species (to a good enough approximation).
The "family" multi-grafted trees generally combine varieties of a single species selected so that they cross/self-pollinate, as you've been told. You apparently have to be quite careful with pruning them so that one graft doesn't dominate, BTW.
These are also perfectly capable of pollinating other trees of the same species that are in blossom at the same time (some apples flower much later than others, for example, and cross-pollination is unlikely if there's little overlap in the flowering). With plenty of different apples you shoudl be fine there.
The cherry may or may not be self fertile. Sour (acid/coking) cherries generally are while sweet cherries used not to be; modern self-fertile varieties do exist.
With some species, even if a tree is technically self-fertile, yields may be better with a pollination partner. This appears to be the case with the plum I have (Victoria, but it's a fussy variety). Because fruit trees are pollinated by bees, and bees travel quite a long way, if your neighbours have trees of the same species you're probably in luck.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to find and remove strings with case insensitive match?
In Java, I have a file contains lines like:
abc
cbd
CFG
...
I want to remove CFG from the file if any of the lines matchs a string, which could be 'cfg', 'Cfg', or other case insensitive variations.
If I read the file into a Set, how can I achieve this? It seems more feasible to do this by reading the file into a List.
A:
The following is a "lambda version" of the required code. Thanks to @Sam for the important point about re-raising any suppressed PrintWriter IOException.
Path in_file = Paths.get("infile");
Path out_file = Paths.get("outfile");
try (PrintWriter pw = new PrintWriter(out_file.toFile())) {
Files.lines(in_file)
.filter(line -> !line.equalsIgnoreCase("cfg"))
.forEach(pw::println);
if (pw.checkError()) {
throw new IOException("Exception(s) occurred in PrintWriter");
}
}
If you need to modify the file in place, then writing to it while reading from it is somewhat more difficult. You could read it all into memory first.
Path path = new Path("filename");
List<String> lines = Files.lines(path)
.filter(line -> !line.equalsIgnoreCase("cfg"))
.collect(Collectors.toList());
try(PrintWriter pw = new PrintWriter(path.toFile())) {
lines.forEach(pw::println);
if (pw.checkError()) {
throw new IOException("Exception(s) occurred in PrintWriter");
}
}
And finally, just in case, a non-lambda solution for compatibility with Java 7:
Path in_file = Paths.get("infile");
Path out_file = Paths.get("outfile");
try (BufferReader reader = Files.newBufferedReader(in_file);
PrintWriter pw = new PrintWriter(out_file.toFile())) {
String line;
while((line = reader.readline()) != null) {
if (!line.equalsIgnoreCase("cfg")) {
pw.println(line);
}
}
if (pw.checkError()) {
throw new IOException("Exception(s) occurred in PrintWriter");
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
apache camel "Jetty vs Servlet" in web application
In our project we are planning to use apache camel for web request routing / orchestration.
Its basically a web project talking to several other internal web-services to prepare the final response to the requester.
Can someone suggest, what is the best/standard way to consume the web requests in a camel web application ?
I believe its possible in camel with several options :
servlet-listenter + servlet component combination
Jetty component
spring web and xml (we want to avoid any spring dependencies)
any other way ???
It would be really helpful if some has done this before and can guide.
Any pointers like pros and cons are also well appreciated.
Note: As I mentioned above, we don't want to have any spring related dependencies in the project.
A:
Jetty is the simplest way to receive a request from some given URL.
from("jetty:http://localhost:{{port}}/myapp/myservice")
.process() // do something with the Exchange
This is easy to get running however you may end up with some tricky routing rules to differentiate between GETs, POSTs and so on. IMHO multiple paths of execution in a camel route (ie with splits, choices etc) can/will become a trap for the unwary.
Servlets are trickier as you need to write the Servlet implementation and register it in the Servlet container (eg via web.xml) and the result is the same - you get a HTTP request as an exchange.
web.xml
<web-app>
<servlet>
<servlet-name>CamelServlet</servlet-name>
<display-name>Camel Http Transport Servlet</display-name>
<servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
RouteBuilder
from("servlet:///hello?matchOnUriPrefix=true").process(new Processor() {
// do stuff
I dont think there's any advantage to this over the jetty component.
Camel Rest DSL is my pick. It's a simple DSL for describing HTTP endpoints with nice REST semantics, it's clear what the routing rules are and it's relatively succinct. This only works with 2.14 onwards though..
rest("/say")
.get("/hello").to("direct:hello")
.get("/bye").consumes("application/json").to("direct:bye")
.post("/bye").to("mock:update");
from("direct:hello")
.transform().constant("Hello World");
from("direct:bye")
.transform().constant("Bye World");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to count entries based on criteria
I have this column where I put the date when I performed some action, along with a hyperlink in it (=hyperlink("link", "action date"). I want to count how many of these actions were performed in the current month.
I can convert it to the month number just fine by using =MONTH(cell), but when I try to use COUNTIF(), it always gives 0
Formula I'm using:
=COUNTIF(MONTH(B5:B), "=month(now())")
I noticed the countif formula works if I only reference a single cell on the first argument, so if there is a way to iterate over all cells checking against the month and then adding those 1's, that would work too, but I can't conceive that formula in my head.
Thanks for the help!
Sample data:
Client 1 11 Jul 18
Client 2 12 Dec 18
Client 3 15 Aug 18
Client 4 15 Jan 19
Client 5 17 Jan 19
Client 6 18 Jan 19
A:
=ARRAYFORMULA(COUNTIF(MONTH(B5:B), "="&MONTH(TODAY())))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Undoing branch creation in Mercurial
How can I undo the creation of a branch in Mercurial? For example, if I issue the command
hg branch newbranch
How can I delete this branch if I decide I entered the wrong name? I'm guessing this must be pretty simple to do, but I have yet to figure it out. Thanks!
A:
If you haven't committed yet, you can simply do a clean reset as per the manual (http://www.selenic.com/mercurial/hg.1.html#commands):
hg branch -C
This will reset the working directory's branch name to the parent of the branch that you just created.
A:
if you haven't committed anything to it, it wasn't really created. so just issue another hg branch newname.
A:
If its already commited:
hg clone -b branch1 [-b branch2 [-b ..]] oldrepo newrepo, i.e. every branch except newbranch, will result in new repo without the newbranch.
If mq extension is enabled then hg strip
Look into editing history before making permanent changes in repository.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
merge sort program in c++ not working
I have written this program in c++ to implement the merge sort algorithm, but it seems to be giving a run-time error. The moment I enter the data of the array elements it stops responding. Now, I don't know what else to write, as stack overflow can't accept a question mostly code, so here is my code. Please someone tell me what is causing the error.
#include <iostream>
using namespace std;
void merge(int arr[], int left, int mid, int right)
{
int i, j, count = left, l[mid-left +1], r[right-mid];
for(i = 0; i <= mid-left; i++)
{
l[i] = arr[left + i];
}
for(j = 0; j <= right-mid-1; j++)
{
r[j] = arr[j + mid + 1];
}
i = j = 0;
while(i <= mid-left && j <= right-mid-1)
{
if(l[i] <= r[j])
{
arr[count] = l[i];
i++;
}
else if(r[j] < l[i])
{
arr[count] = r[j];
j++;
}
count++;
}
while(i <= mid-left)
{
arr[count] = l[i];
i++;count++;
}
while(j <= right-mid-1)
{
arr[count] = r[j];
j++;count++;
}
}
void mergesort(int arr[], int left, int right)
{
if(left > right) return;
int mid = (left + right)/2;
mergesort(arr, left, mid);
mergesort(arr, mid+1, right);
merge(arr, left, mid, right);
}
int main()
{
int n;
cout<<"No. of elements : ";
cin>>n;
int arr[n] ;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
mergesort(arr,0,n-1);
cout<<"sorted array : \n";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
Edit : Everyone i am using c++14 (GCC compiler) and variable sized array is not a problem in my compiler .I ave used it many times .The main thing i am asking is ,is there any problem in my algorithm usage.
A:
Your main problem was the condition you used for termination of merge sort. When you use if (left > right) and left and right are same, then mid is same as left. So the recursion never stops. Use the following condition.
void mergesort(int arr[],int left,int right)
{
if(left >= right) return ;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The difference between adding a char to a string vs a string to char
What is the performance difference between:
string s="";
//stk is std::stack<char>
while(!stk.empty()){
s+=stk.top();
stk.pop();
}
reverse(s.begin(),s.end());
and
while(!stk.empty()){
s=stk.top()+s;
stk.pop();
}
Why is the above more efficient? Can give an example if required.
LeetCode problem
A:
s+=stk.top(), which in this case is equivalent to s.push_back(stk.top()), has amortized constant time complexity. s=stk.top()+s, is essentially equivalent to s.insert(s.begin(), 1, stk.top()), which is linear in the length of s.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SensorSimulator throws error while connecting
I just started Android programming and I wanted to try some stuff with the SensorSimulator.
As soon as it hits the point, where it wants to connect I get the following error:
11-07 08:54:45.195: E/AndroidRuntime(1912): FATAL EXCEPTION: main
11-07 08:54:45.195: E/AndroidRuntime(1912): java.lang.RuntimeException: Unable to start activity ComponentInfo{fnt.android1/fnt.android1.ValuesActivity}: android.os.NetworkOnMainThreadException
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.os.Looper.loop(Looper.java:137)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.lang.reflect.Method.invoke(Method.java:525)
11-07 08:54:45.195: E/AndroidRuntime(1912): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-07 08:54:45.195: E/AndroidRuntime(1912): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-07 08:54:45.195: E/AndroidRuntime(1912): at dalvik.system.NativeStart.main(Native Method)
11-07 08:54:45.195: E/AndroidRuntime(1912): Caused by: android.os.NetworkOnMainThreadException
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-07 08:54:45.195: E/AndroidRuntime(1912): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-07 08:54:45.195: E/AndroidRuntime(1912): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-07 08:54:45.195: E/AndroidRuntime(1912): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.net.Socket.startupSocket(Socket.java:566)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.net.Socket.tryAllAddresses(Socket.java:127)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.net.Socket.<init>(Socket.java:177)
11-07 08:54:45.195: E/AndroidRuntime(1912): at java.net.Socket.<init>(Socket.java:149)
11-07 08:54:45.195: E/AndroidRuntime(1912): at org.openintents.sensorsimulator.hardware.SensorSimulatorClient.connect(SensorSimulatorClient.java:116)
11-07 08:54:45.195: E/AndroidRuntime(1912): at org.openintents.sensorsimulator.hardware.SensorManagerSimulator.connectSimulator(SensorManagerSimulator.java:220)
11-07 08:54:45.195: E/AndroidRuntime(1912): at fnt.android1.ValuesActivity.onCreate(ValuesActivity.java:26)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.Activity.performCreate(Activity.java:5133)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-07 08:54:45.195: E/AndroidRuntime(1912): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-07 08:54:45.195: E/AndroidRuntime(1912): ... 11 more
I'm sure it's connecting to the right IP and using the right port.
Here is my full code:
package fnt.android1;
import android.os.Bundle;
import android.app.Activity;
import android.hardware.SensorManager;
import android.view.Menu;
import org.openintents.sensorsimulator.hardware.Sensor;
import org.openintents.sensorsimulator.hardware.SensorEvent;
import org.openintents.sensorsimulator.hardware.SensorEventListener;
import org.openintents.sensorsimulator.hardware.SensorManagerSimulator;
public class ValuesActivity extends Activity implements SensorEventListener {
private SensorManagerSimulator mSensorManager;
private Sensor mLight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values);
mSensorManager = SensorManagerSimulator.getSystemService(this, SENSOR_SERVICE);
mSensorManager.connectSimulator();
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.values, menu);
return true;
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_FASTEST);
System.out.println("Event registered!");
}
protected void onPause() {
super.onPause();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
for(int i = 0; i < event.values.length; i++) {
System.out.println(event.values[i]);
}
}
}
A:
The logcat is saying that you are trying to run a network call on the main UI Thread. You should move long running operations to a separate Thead. You could use AsyncTask or a regular Thread to do so.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calling a Objective C function from C++ Code
I googled around and I find a million results to this subject. But none of the pages helps me. I think that I have a very common problem. I'm playing around with audio programming especially working with audio queues. The purpose of my program does not matter for explaining the problem. But in a nutshell: I get an error when I try to call an objective-c function from c++ code. So here is my code that contains the error:
AudioRecorder.h:
#import <Foundation/Foundation.h>
@interface AudioRecorder : NSObject {
}
-(void)setup;
-(void)startRecording;
-(void)endRecording;
-(void)playAlarmSound;
@end
And this is the implementation: AudioRecorder.mm:
#import "AudioRecorder.h"
#include <AudioToolbox/AudioToolbox.h>
#include <iostream>
using namespace std;
@implementation AudioRecorder
static const int kNumberBuffers = 3;
...
static void HandleInputBuffer (void *aqData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime,
UInt32 inNumPackets,
const AudioStreamPacketDescription *inPacketDesc ) {
AQRecorderState *pAqData = (AQRecorderState *) aqData;
if (inNumPackets == 0 &&
pAqData->mDataFormat.mBytesPerPacket != 0)
inNumPackets =
inBuffer->mAudioDataByteSize / pAqData->mDataFormat.mBytesPerPacket;
UInt32 size;
AudioQueueGetPropertySize ( inAQ, kAudioQueueProperty_CurrentLevelMeter, &size );
char* levelMeterData = new char[size];
AudioQueueGetProperty ( inAQ, kAudioQueueProperty_CurrentLevelMeter, levelMeterData, &size );
AudioQueueLevelMeterState* meterState = reinterpret_cast<AudioQueueLevelMeterState*>(levelMeterData);
cout << "mAveragePower = " << meterState->mAveragePower << endl;
cout << "mPeakPower = " << meterState->mPeakPower << endl;
delete levelMeterData;
[self playAlarmSound]; //<--- here I get the error: Use of undeclared identifier 'self'
if (pAqData->mIsRunning == 0)
return;
AudioQueueEnqueueBuffer ( pAqData->mQueue, inBuffer, 0, NULL );
}
...
-(void)playAlarmSound {
NSLog(@"Alarmsound....");
}
When I omit "[self playAlarmSound];" then everything works fine. So how do I call this Objective-C function from my C++ code?
A:
self only exists in Objective-C methods and that is a C style function. You need to pass self from an Objective-C method to the inUserData when you set up the callback, then cast it back to the correct type.
//This is an example for using AudioQueueNewInput
//Call this in an Objective-C method passing self to inUserData
AudioQueueNewInput (
const AudioStreamBasicDescription *inFormat,
AudioQueueInputCallback inCallbackProc,
// this is where you will pass (void*)self
void *inUserData,
CFRunLoopRef inCallbackRunLoop,
CFStringRef inCallbackRunLoopMode,
UInt32 inFlags,
AudioQueueRef *outAQ
);
And your original implementation
static void HandleInputBuffer (void *aqData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime,
UInt32 inNumPackets,
const AudioStreamPacketDescription *inPacketDesc )
{
AudioRecorder *ar_instance = (AudioRecorder*)aqData;
...
[ar_instance playAlarmSound];
...
}
A:
This is indeed a common problem. self doesn't work here because this is not a method of the AudioRecorder class, not because it's Objective-C code. You're in an Objective-C++ file, so all valid Objective-C code will work. [anAudioRecorder playAlarmSound] will work fine, provided you have a good reference to anAudioRecorder.
So how do we get a reference if we don't have access to self? The usual way is to use the void* aqData argument of this function as a pointer to your AudioRecorder object. When you registered this callback, you told it what the void* argument would be, in this case a pointer to your AQRecorderState object or struct, which you don't seem to use anyway. Instead you can use a pointer to self when you register so that you can use that object here.
Another option would be to use a shared AudioRecorder object, in which case you would call something like [AudioRecorder sharedInstance] (a class, not an instance, method) to get the AudioRecorder object you want. Because the other answer here elaborates on the first method, here's how to use the shared instance option: Add a static instance of AudioRecorder and a class method sharedInstance to your AudioRecorder object, like this:
static AudioRecorder* sharedMyInstance = nil;
+ (id) sharedInstance {
@synchronized(self) {
if( sharedMyInstance == nil )
sharedMyInstance = [[super allocWithZone:NULL] init];
}
return sharedMyInstance;
} // end sharedInstance()
Then, when you want to use the AudioRecorder from your callback, you can get the shared instance using [AudioRecorder sharedInstance]. This is a very useful paradigm if there's only going to be one AudioRecorder - it eliminates a lot of reference passing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
D3 Clock not appearing on production
Can't seem to figure this out for an hour now. I have a D3 clock which appears fine locally on my Rails project, however, doesn't on production.
I have done the following:
bundle install
rake assets:precompile RAILS_ENV=production
Any thoughts?
A:
Figured it out. Looks like I had CKEDITOR JS errors which for some reason wasn't running other JS files on production.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to sort items in a list using foreach C#
I need to sort the items I have in a list by age using foreach in ascending order, and so I have no idea how to. This is my code so far:
namespace ListProject
{
public struct FamilyMem
{
public string name;
public int age;
public FamilyMem(string name,int age)
{
this.name = name;
this.age = age;
}
}
class Program
{
static void Main(string[] args)
{
FamilyMem Jack = new FamilyMem("Jack", 15);
FamilyMem Tom = new FamilyMem("Tommy", 24);
FamilyMem Felix = new FamilyMem("Felix", 26);
FamilyMem Lukas = new FamilyMem("Lukas", 26);
FamilyMem Austin = new FamilyMem("Austin", 54);
FamilyMem Ben = new FamilyMem("Ben", 55);
List<FamilyMem> gambleList = new List<FamilyMem>();
gambleList.Add(Jack);
gambleList.Add(Tom);
gambleList.Add(Felix);
gambleList.Add(Lukas);
gambleList.Add(Austin);
gambleList.Add(Ben);
Console.WriteLine(gambleList.Count.ToString());
}
}
}
I also need a separate piece of code that will allow me to sort the names alphabetically. Thanks.
A:
You can't edit a collection while you're iterating over it with a foreach loop, so this much at least isn't possible. You can, however, use LINQ or some for loops. Use something like:
gambleList = gambleList.OrderBy(item => item.name).ToList();
The reason for the assignment, by the way, is that the OrderBy operation (unlike, for example, the Sort() method) does not sort the collection in place - it returns a reference to a sorted collection.
You could also use a standard for loop or recursive function to implement something like an Insertion Sort.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Updated to android studio 3.0.1, now JDBC .jar dependency isn't working
I updated from Android Studio 2.2.3 to 3.0.1. Now my .jar dependencies are broken somehow.
java.lang.ClassNotFoundException: org.sqlite.JDBC
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.DataAccessObjects.DataAccessObject.openConnection(DataAccessObject.java:56)
at com.DataAccessObjects.DataAccessObject.updateDb(DataAccessObject.java:35)
at com.DataAccessObjects.AuthTokenDao.createTable(AuthTokenDao.java:45)
at com.Services.Service.newDaosAtDb(Service.java:45)
at com.Services.ClearService.<init>(ClearService.java:19)
at com.Handlers.ClearHandler.<init>(ClearHandler.java:28)
at com.Server.run(Server.java:37)
at com.Server.main(Server.java:26)
Exception in thread "main" java.lang.NullPointerException
at com.DataAccessObjects.DataAccessObject.updateDb(DataAccessObject.java:37)
at com.DataAccessObjects.AuthTokenDao.createTable(AuthTokenDao.java:45)
at com.Services.Service.newDaosAtDb(Service.java:45)
at com.Services.ClearService.<init>(ClearService.java:19)
at com.Handlers.ClearHandler.<init>(ClearHandler.java:28)
at com.Server.run(Server.java:37)
at com.Server.main(Server.java:26)
Here are my dependencies in the module build.gradle
dependencies {
implementation files('libs/junit-4.12.jar')
implementation 'com.google.code.gson:gson:2.2.4'
implementation files('libs/sqlite-jdbc-3.7.2.jar')
}
It deals properly with junit and gson, because without them it complains. But whether or not I include the jdbc .jar, it reacts with the same error message.
EDIT1: I know that somehow it was the update that broke this. I have a computer with 2.2.3 installed, running code that as far as I'm aware is the same, with the exact same .jar file, and it doesn't have any problems. An interesting detail is that while 3.0.1 says "implementation files(...)", 2.2.3 says "compile files(...)"
EDIT2: Still pretty flabbergasted over here. I can instantiate an org.sqlite.JDBC object, and Android Studio recognizes that it's a valid class, but as soon as I call Class.forName("org.sqlite.JDBC"), suddenly it's not a valid class...
public void openConnection()throws SQLException{
try {
assert connection == null;
assert dbName.length()>0;
org.sqlite.JDBC hi = null; //valid code
Class.forName("org.sqlite.JDBC"); //ClassNotFoundException: org.sqlite.JDBC
connection = DriverManager.getConnection("jdbc:sqlite:" + dbName);
A:
I made a new project and moved all my code into it, and now it's working.
If you want my advice, never update Android Studio when you're working under tight time constraints. This took me all day.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linux Kernel Libraries
Is there an API/way to know what Linux Kernel headers replace what user space headers for instance: linux/string.h instead of string.h? All I found was this website:The Linux Kernal API but it didn't say what headers to include in my code in order to use the functions listed.
A:
while no API found, a good way for me is to use :
Documentation
and the following guide:
Kernel Guide
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Complete binary tree and Perfect binary tree definitions
I have few question about binary tree types.
COMPLETE BINARY TREE: A Binary Tree is complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible.
Almost every example for complete binary tree is given like that.One of the last nodes have only left child.
18
/ \
15 30
/ \ /
40 50 100
It's okay.
My question:
Is the following tree also a complete binary tree?
18
/ \
15 30
/ \
40 50
I know it's full binary tree also.
My second question:
If it is both full binary and complete binary tree can we say that it is also perfect binary tree? ( The last tree I wrote)
A:
1st Answer
Yes This tree can also be called as complete binary tree.
Explanation
Complete Binary Tree:
As you mentioned any tree in which all levels are completely filled and last level has keys as left as possible its considered binary tree. This condition satisfies for your example so its a complete binary tree.
Full Binary Tree:
Any binary tree in which all the nodes except leaf node has two children then its considered as full binary tree. 1st tree in question is not full binary tree but 2nd tree is full binary tree.
2nd Answer
No if tree is both full and complete that does not mean you can call it as a perfect binary tree.
A binary tree is considered perfect if it is full and all leaves are on the same level. In your example its not perfect binary tree.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Codeigniter : How can remove any error message for user
I have problem in link of my script by Codeigniter.
I have this URL :-
localhost/index.php/details/1
Its get me all details of product, by ID , But when i add any character in the end of link like this :
localhost/index.php/details/ggg
The user see some error message.
How can save my link, And hidden this message.
A:
Method 01
in config/routs.php
$route['404_override'] = 'Controller name';//this to avoid 404 Error
Method 02
in your controller check empty
$data['product'] = $this->Model_Name->get_product($id);
if(empty( $data['product']))
{
$this->empty_result();
}
else
{
//load relevent view
}
In controller at top create function call empty_result()
public function empty_result()
{
$this->load->view('template/header');
$this->load->view('template/right_sidebar');
$this->load->view('template/NothingFound',$data);//create a page to show empty or Nothing found
$this->load->view('template/foot');
}
In Model
public function get_product($id)
{
$query = $this->db->query("SELECT * FROM product WHERE id ='$id'");
$result = $query->result_array();
return $result;
}
In view (template/NothingFound.php)
create file call NothingFound.php
in that
<h1>No thing found title</h1>
<!--customize the view as you want. Add some images-->
EDIT 01
Method 03
Goto error/error_404.php
Edit the error message to display in your styles
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the difference between adding Java Script libraries as npm dependencies or simply including them in HTML?
Looking at npm starred packages I see that some projects like Grunt, lodash or underscore are avaliable.
I've always used these in the classic way:
<script src="js/lib/lodash.min.js"></script>
What makes it different and how would I use them obtained within the node_modules packages?
A:
On one hand, npm is a Node tool made to install packages for Node. Packages are collections of modules. And in Node, modules are loaded with a require call, which is a global function made available by Node.
On the other hand, <script> is the basic mechanism used in browsers to load JavaScript code.
This may seem mutually exclusive, but npm can be also used to install packages that are designed to run both in Node and in a browser. In this case we use Node's require to load a module from the package in Node, but we can use <script> or Browserify or RequireJS to load the same module in a browser. What method to use in the browser really depends on how the package was designed. You have to read the doc to know or read the source code if the doc is not good. I've designed a npm package that works this way. You can use Node's require to load it in Node and use RequireJS to load it in a browser.
npm can even be used to install packages that are designed to run only in a browser. In this case, npm is just a convenient delivery and dependency mechanism. I have another package designed this way. It comes with a prominent note that it is not made to run in Node. This is an accepted usage of npm and there are currently proposals (here and here) to make npm even better at handling this kind of scenario.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Copy List of Structures to Excel Range
Does anyone know how to copy a VB.Net list of structures to an Excel range? It's not hard to do with an array, but I can't get a list of structures to work.
Example:
Structure MyStruct
Dim MyField1 as String
Dim MyField2 as Integer
End Structure
Dim MyList As New List(Of MyStruct)
...populate list of structures...
Dim rng as Excel.Range = MySheet.Range("A1","B9")
rng.??? = MyList '*** This is where I get stuck. ***
A:
With custom structures, iterating is the only way. You can't expect excel to be clever enough to map a list of structures with multiple fields into rows and columns.
Dim oneMyStruct, i as Long
i = 1
For each oneMyStruct in MyList
rng.cells(i, 1) = oneMyStruct.MyField1
rng.cells(i, 2) = oneMyStruct.MyField2
i = i + 1
next oneMyStruct
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java's strange behavior while returning from finally block
Try this piece of code. Why does getValueB() return 1 instead of 2? After all, the increment() function is getting called twice.
public class ReturningFromFinally
{
public static int getValueA() // This returns 2 as expected
{
try { return 1; }
finally { return 2; }
}
public static int getValueB() // I expect this to return 2, but it returns 1
{
try { return increment(); }
finally { increment(); }
}
static int counter = 0;
static int increment()
{
counter ++;
return counter;
}
public static void main(String[] args)
{
System.out.println(getValueA()); // prints 2 as expected
System.out.println(getValueB()); // why does it print 1?
}
}
A:
After all, the increment() function is getting called twice.
Yes, but the return value is determined before the second call.
The value returned is determined by the evaluation of the expression in the return statement at that point in time - not "just before execution leaves the method".
From section 14.17 of the JLS:
A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.
Execution is then transferred to the finally block, as per section 14.20.2 of the JLS. That doesn't re-evaluate the expression in the return statement though.
If your finally block were:
finally { return increment(); }
then that new return value would be the ultimate result of the method (as per section 14.20.2) - but you're not doing that.
A:
See my comment.
It would return 2 if you had finally { return increment(); }.
The first return statement's expression is evaluated prior to the finally block. See Section §14.20.2 of the JLS.
If execution of the try block completes normally, then the finally block is executed, and then there is a choice:
If the finally block completes normally, then the try statement completes normally.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.
Calling getValue2 (as you have it now) twice would result in 1 followed by 3.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Accessing RDF/XML/OWL file nodes using Perl
I have a RDF/XML data which I'd like to parse and access the node.
It looks like this:
<!-- http://purl.obolibrary.org/obo/VO_0000185 -->
<owl:Class rdf:about="&obo;VO_0000185">
<rdfs:label>Influenza virus gene</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;VO_0000156"/>
<obo:IAO_0000117>YH</obo:IAO_0000117>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/VO_0000186 -->
<owl:Class rdf:about="&obo;VO_0000186">
<rdfs:label>RNA vaccine</rdfs:label>
<owl:equivalentClass>
<owl:Class>
<owl:intersectionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;VO_0000001"/>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;BFO_0000161"/>
<owl:someValuesFrom rdf:resource="&obo;VO_0000728"/>
</owl:Restriction>
</owl:intersectionOf>
</owl:Class>
</owl:equivalentClass>
<rdfs:subClassOf rdf:resource="&obo;VO_0000001"/>
<obo:IAO_0000116>Using RNA may eliminate the problem of having to tailor a vaccine for each individual patient with their specific immunity. The advantage of RNA is that it can be used for all immunity types and can be taken from a single cell. DNA vaccines need to produce RNA which then prompts the manufacture of proteins. However, RNA vaccine eliminates the step from DNA to RNA.</obo:IAO_0000116>
<obo:IAO_0000115>A vaccine that uses RNA(s) derived from a pathogen organism.</obo:IAO_0000115>
<obo:IAO_0000117>YH</obo:IAO_0000117>
</owl:Class>
The complete RDF/XML file can be found here.
What I want to do is to do the following:
Find chunk where it contains the entry <rdfs:subClassOf rdf:resource="&obo;VO_0000001"/>
Access the literal term as defined by <rdfs:label>...</rdfs:label>
So in the above example the code would go through second chunk and output:
"RNA vaccine".
I'm currently stuck with the following code. Where I couldn't
access the node. What's the right way to do it? Solutions other than using XML::LibXML
are welcomed.
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
use Carp;
use File::Basename;
use XML::LibXML 1.70;
my $filename = "VO.owl";
# Obtained from http://svn.code.sf.net/p/vaccineontology/code/trunk/src/ontology/VO.owl
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file( $filename );
foreach my $chunk ($doc->findnodes('/owl:Class')) {
my ($label) = $chunk->findnodes('./rdfs:label');
my ($subclass) = $chunk->findnodes('./rdfs:subClassOf');
print $label->to_literal;
print $subclass->to_literal;
}
A:
Take a look at the perlrdf.org website which includes links to a number of Perl packages for working with RDF.
Using these is likely much more flexible and less error prone that accessing RDF/XML using XPath since RDF/XML is not a canonicalized serialization i.e. the same data can be represented in varying different XML forms depending on the tool used to serialize it.
A:
Parsing RDF as if it were XML is a folly. The exact same data can appear in many different ways. For example, all of the following RDF files carry the same data. Any conforming RDF implementation MUST handle them identically...
<!-- example 1 -->
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="#me">
<rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Person" />
<foaf:name>Toby Inkster</foaf:name>
</rdf:Description>
</rdf:RDF>
<!-- example 2 -->
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/">
<foaf:Person rdf:about="#me">
<foaf:name>Toby Inkster</foaf:name>
</foaf:Person>
</rdf:RDF>
<!-- example 3 -->
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/">
<foaf:Person rdf:about="#me" foaf:name="Toby Inkster" />
</rdf:RDF>
<!-- example 4 -->
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="">
<rdf:Description rdf:about="#me"
rdf:type="http://xmlns.com/foaf/0.1/Person"
foaf:name="Toby Inkster" />
</rdf:RDF>
<!-- example 5 -->
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:ID="me">
<rdf:type>
<rdf:Description rdf:about="http://xmlns.com/foaf/0.1/Person" />
</rdf:type>
<foaf:name>Toby Inkster</foaf:name>
</rdf:Description>
</rdf:RDF>
<!-- example 6 -->
<foaf:Person
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/"
rdf:about="#me"
foaf:name="Toby Inkster" />
I could easily list half a dozen other variations too, but I'll stop there. And this RDF file contains just two statements - I'm a Person; my name is "Toby Inkster" - the OP's data contains over 50,000 statements.
And this is just the XML serialization of RDF; there are other serializations too.
If you try handling all that with XPath, you're likely to end up becoming a lunatic locked away in a tower somewhere, muttering in his sleep about the triples; the triples...
Luckily, Greg Williams has taken that mental health bullet for you. RDF::Trine and RDF::Query are not only the best RDF frameworks for Perl; they're amongst the best in any programming language.
Here is how the OP's task could be achieved using RDF::Trine and RDF::Query:
#!/usr/bin/env perl
use v5.12;
use RDF::Trine;
use RDF::Query;
my $model = 'RDF::Trine::Model'->new(
'RDF::Trine::Store::DBI'->new(
'vo',
'dbi:SQLite:dbname=/tmp/vo.sqlite',
'', # no username
'', # no password
),
);
'RDF::Trine::Parser::RDFXML'->new->parse_url_into_model(
'http://svn.code.sf.net/p/vaccineontology/code/trunk/src/ontology/VO.owl',
$model,
) unless $model->size > 0;
my $query = RDF::Query->new(<<'SPARQL');
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?super_label ?sub_label
WHERE {
?sub rdfs:subClassOf ?super .
?sub rdfs:label ?sub_label .
?super rdfs:label ?super_label .
}
LIMIT 5
SPARQL
print $query->execute($model)->as_string;
Sample output:
+----------------------------+----------------------------------+
| super_label | sub_label |
+----------------------------+----------------------------------+
| "Aves vaccine" | "Ducks vaccine" |
| "route of administration" | "intravaginal route" |
| "Shigella gene" | "aroA from Shigella" |
| "Papillomavirus vaccine" | "Bovine papillomavirus vaccine" |
| "virus protein" | "Feline leukemia virus protein" |
+----------------------------+----------------------------------+
UPDATE: Here's a SPARQL query that can be plugged into the script above to retrieve the data you wanted:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX obo: <http://purl.obolibrary.org/obo/>
SELECT ?subclass ?label
WHERE {
?subclass
rdfs:subClassOf obo:VO_0000001 ;
rdfs:label ?label .
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Incrementing a java.util.Date by one day
What is the correct way to increment a java.util.Date by one day.
I'm thinking something like
Calendar cal = Calendar.getInstance();
cal.setTime(toDate);
cal.add(Calendar.DATE, 1);
toDate = cal.getTime();
It doesn't 'feel' right.
A:
That would work.
It doesn't 'feel' right.
If it is the verbosity that bothers you, welcome to the Java date-time API :-)
A:
If you do not like the math in the solution from Tony Ennis
Date someDate = new Date(); // Or whatever
Date dayAfter = new Date(someDate.getTime() + TimeUnit.DAYS.toMillis( 1 ));
But more or less since finding this Q/A, I have been using JodaTime, instead, and have recently switched to the new DateTime in Java 8 (which inspired by but not copied from Joda - thanks @BasilBourqueless for pointing this out).
Java 8
In Java 8, almost all time-based classes have a .plusDays() method making this task trivial:
LocalDateTime.now() .plusDays(1);
LocalDate.now() .plusDays(1);
ZonedDateTime.now() .plusDays(1);
Duration.ofDays(1) .plusDays(1);
Period.ofYears(1) .plusDays(1);
OffsetTime.now() .plus(1, ChronoUnit.DAYS);
OffsetDateTime.now() .plus(1, ChronoUnit.DAYS);
Instant.now() .plus(1, ChronoUnit.DAYS);
Java 8 also added classes and methods to interoperate between the (now) legacy Date and Calendar etc. and the new DateTime classes, which are most certainly the better choice for all new development.
A:
Yeah, that's right. Java Date APIs feel wrong quite often. I recommend you try Joda Time. It would be something like:
DateTime startDate = ...
DateTime endDate = startDate.plusDays(1);
or:
Instant start = ...
Instant end = start.plus(Days.days(1).toStandardDuration());
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle sql tag every first duplicate with true and others with false
Being a beginner in SQL oracle, I am working on a table CATS with 4 varchar2 fields country, hair, color and firstItemFound.
I am trying to edit a sql request so each time I hit a new tuple name || country || color , I add an attribute 'true' if I did already find this tuple I add an attribute 'false'.
I thought about this :
step 1) Update (select distinct name, country, color from cats) tmp_cats set firstItemFound = true;
step 2) Update cats set firstItemFound = false where firstItemFound is null;
But 1) is not working because you can't update a non physical view. Does there is any work around ? Is it possible to do it in one operation instead of two ?
Here is my table values (firstItemFound column has null values) :
NAME |COUNTRY |COLOR |
-------|----------|-------|
France |Shorthair |Red |
Brazil |Longhair |Yellow |
France |Shorthair |Red |
France |Longhair |Brown |
France |Longhair |Black |
Brazil |Longhair |Yellow |
Brazil |Longhair |Black |
Brazil |Longhair |Brown |
Brazil |Longhair |Yellow |
Here is my wanted result :
country hair color firstItemFound
---------------------------------------------
France Shorthair Red true
France Shorthair Red false
France Longhair Brown true
France Longhair Black true
Brazil Longhair Yellow true
Brazil Longhair Yellow false
Brazil Longhair Yellow false
Brazil Longhair Black true
Brazil Longhair Brown true
A:
you can use row_number for making 1st item true
select *,case when rn=1 then true else false end as firstItemFound from
(select country,hair,colur, row_number()
over(partition by country,hair,colur order by country) rn from t
) t
or you can use cte expression
with t as (
select * from
(
select 'France' as country ,'Shorthair' as hair,'Red' as colur from dual
union all
select 'Brazil','Longhair','Yellow' from dual
union all
select 'France' ,'Shorthair','Red' from dual
)
) , t2 as
(
select country,hair,colur, row_number()
over(partition by country,hair,colur order by country) rn from t
)select t2.*, case when rn=1 then 'true' else 'false' end as firstItemFound from t2
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=65146824ed31dbbc6daa40676220cdf8
COUNTRY HAIR COLUR RN FIRSTITEMFOUND
Brazil Longhair Yellow 1 true
France Shorthair Red 1 true
France Shorthair Red 2 false
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why do the strings output using fprintf end up not being written to the output file if my program is terminated via CTRL-C?
Why does fprintf give different results in the following example programs?
Example 1:
int main(){
FILE *f;
char buf[512];
char name[128] = {"filename"};
f = fopen(name, "w");
fprintf(f, "asdas\n");
fprintf(f, "asdas\n");
while(1){}
return 0;
}
If I terminate this program using CTRL+C, I get an empty file named filename.
However, using
Example 2:
int main(){
FILE *f;
char buf[512];
char name[128] = {"wpa_supplicant.conf"};
f = fopen(name,"w");
while(1){
fprintf(f, "asdas\n");
}
return 0;
}
If I terminate this program using CTRL+C, I get file named filename, and it contains many lines with the string asdas.
Why are the strings not written to the file in the first example, but they are written to the file in the second example?
A:
In the second case, there are enough fprintf calls for the internal buffers to be flushed to disk.
With the first program, if you put a fflush(f) before the while loop, the strings will be written to the file.
#include <stdio.h>
int main(void) {
FILE *f = fopen("filename", "w");
if (!f) {
perror("Failed to open 'filename' for writing");
exit(EXIT_FAILURE);
}
fprintf(f, "asdas\n");
fprintf(f, "asdas\n");
if ( fflush(f) != 0 ) {
perror("Flushing output failed");
exit(EXIT_FAILURE);
}
while(1){}
return 0;
}
Output:
C:\...\Temp> cl file.c
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.31101 for x64
...
/out:file.exe
C:\...\Temp> file
^C
C:\...\Temp> type filename
asdas
asdas
Keep in mind:
Upon successful completion, fflush() shall return 0; otherwise, it shall set the error indicator for the stream, return EOF, and set errno to indicate the error.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Slice lines and save parameters into different files
I have a g.out file (pasted below).
This file consists of several FINAL OPTIMIZED geometries I would like to extract.
For a given FINAL OPTIMIZED GEOMETRY, these highlighted values are the ones I would like to extract:
I have managed in the below program to extract the first three: VOLUME and A, and B:
My code:
import os
import sys
import re
initial_pattern = '^ FINAL OPTIMIZED GEOMETRY - DIMENSIONALITY OF THE SYSTEM 3$'
middle_pattern = '^ CRYSTALLOGRAPHIC CELL '
end_pattern = '^ T = ATOM BELONGING TO THE ASYMMETRIC UNIT$'
VOLUMES = []
P0 = []
P2 = []
atomic_number = []
coord_x = []
coord_y = []
coord_z = []
with open('g.out') as file:
for line in file:
if re.match(initial_pattern, line):
print file.next()
print file.next()
print file.next()
volume_line = file.next()
print volume_line
aux = volume_line.split()
each_volume = aux[7]
print each_volume
VOLUMES.append(each_volume)
if re.match(middle_pattern, line):
print line
print file.next()
parameters_line = file.next()
aux = parameters_line.split()
p0 = aux[0]
p1 = aux[1]
p2 = aux[2]
p3 = aux[3]
p4 = aux[4]
p5 = aux[5] #
print p0
print p2
P0.append(p0)
P2.append(p2)
print file.next()
print file.next()
print file.next()
print file.next()
first_coord_line = file.next()
print first_coord_line
if re.match(end_pattern, line):
end_pattern = line
print end_pattern
all_coordinates = [first_coord_line:end_pattern]
for line in all_coordinates:
del('F ') # delete those that contain 'F '
aux2 = line.split()
coords = []
sys.exit()
#Template =
"""
some stuff
other stuff
p0 p2
3
A B C D
E F G H
I J K L
other stuff
some other stuff
"""
I am not able to extract the COORDINATES, because I cannot find the way to slice lines from first_coord_line to end_pattern, like in this pseudo-code:
if re.match(end_pattern, line):
end_pattern = line
print end_pattern
all_coordinates = [first_coord_line:end_pattern]
for line in all_coordinates:
del('F ') # delete those that contain 'F '
aux2 = line.split() # split lines
atomic_number = aux2[2]
coord_x = aux2[4]
coord_y = aux2[5]
coord_z = aux2[6]
Is there a way to achieve this pseudo-code?
In my code, VOLUMES, P0, P2, atomic_number, coord_x, coord_y coord_z are initialized with lists because before ending the for loop I would like to save in different files, named with the name of the "VOLUME.inp", this information:
#Template =
"""
some stuff
other stuff
p0 p2
3
A B C D
E F G H
I J K L
other stuff
some other stuff
"""
where p0 and p2 are the values extracted in my code (2nd and 3rd highlighted values in the screenshot), and A-L are the atomic_number and coord_x, coord_y, coord_z.
Is there a way to achieve this?
The g.out file:
more lines
more lines
more lines
FINAL OPTIMIZED GEOMETRY - DIMENSIONALITY OF THE SYSTEM 3
(NON PERIODIC DIRECTION: LATTICE PARAMETER FORMALLY SET TO 500)
*******************************************************************************
LATTICE PARAMETERS (ANGSTROMS AND DEGREES) - BOHR = 0.5291772083 ANGSTROM
PRIMITIVE CELL - CENTRING CODE 7/0 VOLUME= 119.823364 - DENSITY 2.770 g/cm^3
A B C ALPHA BETA GAMMA
6.28373604 6.28373604 6.28373604 46.646397 46.646397 46.646397
*******************************************************************************
ATOMS IN THE ASYMMETRIC UNIT 3 - ATOMS IN THE UNIT CELL: 10
ATOM X/A Y/B Z/C
*******************************************************************************
1 T 20 CA 0.000000000000E+00 0.000000000000E+00 0.000000000000E+00
2 F 20 CA -5.000000000000E-01 -5.000000000000E-01 -5.000000000000E-01
3 T 6 C 2.500000000000E-01 2.500000000000E-01 2.500000000000E-01
4 F 6 C -2.500000000000E-01 -2.500000000000E-01 -2.500000000000E-01
5 T 8 O -4.924094276183E-01 -7.590572381674E-03 2.500000000000E-01
6 F 8 O 2.500000000000E-01 -4.924094276183E-01 -7.590572381674E-03
7 F 8 O -7.590572381674E-03 2.500000000000E-01 -4.924094276183E-01
8 F 8 O 4.924094276183E-01 7.590572381674E-03 -2.500000000000E-01
9 F 8 O -2.500000000000E-01 4.924094276183E-01 7.590572381674E-03
10 F 8 O 7.590572381674E-03 -2.500000000000E-01 4.924094276183E-01
TRANSFORMATION MATRIX PRIMITIVE-CRYSTALLOGRAPHIC CELL
1.0000 0.0000 1.0000 -1.0000 1.0000 1.0000 0.0000 -1.0000 1.0000
*******************************************************************************
CRYSTALLOGRAPHIC CELL (VOLUME= 359.47009054)
A B C ALPHA BETA GAMMA
4.97568007 4.97568007 16.76591397 90.000000 90.000000 120.000000
COORDINATES IN THE CRYSTALLOGRAPHIC CELL
ATOM X/A Y/B Z/C
*******************************************************************************
1 T 20 CA 0.000000000000E+00 0.000000000000E+00 0.000000000000E+00
2 F 20 CA -5.491739570355E-17 -2.745869785177E-17 -5.000000000000E-01
3 T 6 C 3.333333333333E-01 -3.333333333333E-01 -8.333333333333E-02
4 F 6 C -3.333333333333E-01 3.333333333333E-01 8.333333333333E-02
5 T 8 O -4.090760942850E-01 -3.333333333333E-01 -8.333333333333E-02
6 F 8 O 3.333333333333E-01 -7.574276095166E-02 -8.333333333333E-02
7 F 8 O 7.574276095166E-02 4.090760942850E-01 -8.333333333333E-02
8 F 8 O 4.090760942850E-01 3.333333333333E-01 8.333333333333E-02
9 F 8 O -3.333333333333E-01 7.574276095166E-02 8.333333333333E-02
10 F 8 O -7.574276095166E-02 -4.090760942850E-01 8.333333333333E-02
T = ATOM BELONGING TO THE ASYMMETRIC UNIT
INFORMATION **** fort.34 **** GEOMETRY OUTPUT FILE
more lines
more lines
more lines
FINAL OPTIMIZED GEOMETRY - DIMENSIONALITY OF THE SYSTEM 3
(NON PERIODIC DIRECTION: LATTICE PARAMETER FORMALLY SET TO 500)
*******************************************************************************
LATTICE PARAMETERS (ANGSTROMS AND DEGREES) - BOHR = 0.5291772083 ANGSTROM
PRIMITIVE CELL - CENTRING CODE 7/0 VOLUME= 121.143469 - DENSITY 2.740 g/cm^3
A B C ALPHA BETA GAMMA
6.32229536 6.32229536 6.32229536 46.436583 46.436583 46.436583
*******************************************************************************
ATOMS IN THE ASYMMETRIC UNIT 3 - ATOMS IN THE UNIT CELL: 10
ATOM X/A Y/B Z/C
*******************************************************************************
1 T 20 CA 0.000000000000E+00 0.000000000000E+00 0.000000000000E+00
2 F 20 CA 5.000000000000E-01 -5.000000000000E-01 -5.000000000000E-01
3 T 6 C 2.500000000000E-01 2.500000000000E-01 2.500000000000E-01
4 F 6 C -2.500000000000E-01 -2.500000000000E-01 -2.500000000000E-01
5 T 8 O -4.927088991116E-01 -7.291100888437E-03 2.500000000000E-01
6 F 8 O 2.500000000000E-01 -4.927088991116E-01 -7.291100888437E-03
7 F 8 O -7.291100888437E-03 2.500000000000E-01 -4.927088991116E-01
8 F 8 O 4.927088991116E-01 7.291100888437E-03 -2.500000000000E-01
9 F 8 O -2.500000000000E-01 4.927088991116E-01 7.291100888437E-03
10 F 8 O 7.291100888437E-03 -2.500000000000E-01 4.927088991116E-01
TRANSFORMATION MATRIX PRIMITIVE-CRYSTALLOGRAPHIC CELL
1.0000 0.0000 1.0000 -1.0000 1.0000 1.0000 0.0000 -1.0000 1.0000
*******************************************************************************
CRYSTALLOGRAPHIC CELL (VOLUME= 363.43040599)
A B C ALPHA BETA GAMMA
4.98494429 4.98494429 16.88768068 90.000000 90.000000 120.000000
COORDINATES IN THE CRYSTALLOGRAPHIC CELL
ATOM X/A Y/B Z/C
*******************************************************************************
1 T 20 CA 0.000000000000E+00 0.000000000000E+00 0.000000000000E+00
2 F 20 CA -5.471726358381E-17 -2.735863179191E-17 -5.000000000000E-01
3 T 6 C 3.333333333333E-01 -3.333333333333E-01 -8.333333333333E-02
4 F 6 C -3.333333333333E-01 3.333333333333E-01 8.333333333333E-02
5 T 8 O -4.093755657782E-01 -3.333333333333E-01 -8.333333333333E-02
6 F 8 O 3.333333333333E-01 -7.604223244490E-02 -8.333333333333E-02
7 F 8 O 7.604223244490E-02 4.093755657782E-01 -8.333333333333E-02
8 F 8 O 4.093755657782E-01 3.333333333333E-01 8.333333333333E-02
9 F 8 O -3.333333333333E-01 7.604223244490E-02 8.333333333333E-02
10 F 8 O -7.604223244490E-02 -4.093755657782E-01 8.333333333333E-02
T = ATOM BELONGING TO THE ASYMMETRIC UNIT
INFORMATION **** fort.34 **** GEOMETRY OUTPUT FILE
more lines
more lines
more lines
Updated code:
Based on @nos flag's approach, the following code is capable of extracting the information. VOLUMES is a list of 2 elements.
The following lists are the result:
VOLUMES = ['119.823364', '121.143469']
P0 = ['4.97568007', '4.98494429']
P2 = ['16.76591397', '16.88768068']
Xs = ['0.000000000000E+00', '3.333333333333E-01', '-4.090760942850E-01', '0.000000000000E+00', '3.333333333333E-01', '-4.093755657782E-01']
Ys = ['0.000000000000E+00', '-3.333333333333E-01', '-3.333333333333E-01', '0.000000000000E+00', '-3.333333333333E-01', '-3.333333333333E-01']
Zs = ['0.000000000000E+00', '-8.333333333333E-02', '-8.333333333333E-02', '0.000000000000E+00', '-8.333333333333E-02', '-8.333333333333E-02']
ATOMIC_NUMBERS = ['20', '6', '8', '20', '6', '8']
The second part of this post was to write this information (P0, P2, ATOMIC_NUMBERS, Xs, Ys, Zs) in the two VOLUME.inp files. In other words, something like:
V_119.823364.inp file:
some stuff
other stuff
4.97568007 4.98494429
3
20 0.000000000000E+00 0.000000000000E+00 0.000000000000E+00
6 3.333333333333E-01 -3.333333333333E-01 -8.333333333333E-02
8 -4.090760942850E-01 -3.333333333333E-01 -8.333333333333E-02
other stuff
V_121.143469.inp file:
some stuff
other stuff
4.97568007 4.98494429
3
20 0.000000000000E+00 0.000000000000E+00 0.000000000000E+00
6 3.333333333333E-01 -3.333333333333E-01 -8.333333333333E-02
8 -4.093755657782E-01 -3.333333333333E-01 -8.333333333333E-02
other stuff
Based on @nos's atoms_per_frame and atoms_all_frames suggestion, I have tried the following code. I am finding difficulties in writing element-wise to the files, i.e.:
import os
import sys
import re
import glob
initial_pattern = '^ FINAL OPTIMIZED GEOMETRY - DIMENSIONALITY OF THE SYSTEM 3$'
middle_pattern = '^ CRYSTALLOGRAPHIC CELL '
end_pattern = '^ T = ATOM BELONGING TO THE ASYMMETRIC UNIT$'
global N_atom_irreducible_unit
N_atom_irreducible_unit = 3
VOLUMES = []
P0 = []
P2 = []
ATOMIC_NUMBERS = []
Xs = []
Ys = []
Zs = []
with open('g.out') as file:
passed_mid_point = False
for line in file:
if re.match(initial_pattern, line):
print file.next()
print file.next()
print file.next()
volume_line = file.next()
print volume_line
aux = volume_line.split()
each_volume = aux[7]
print each_volume
VOLUMES.append(each_volume)
if re.match(middle_pattern, line):
print line
print file.next()
parameters_line = file.next()
aux = parameters_line.split()
p0 = aux[0]
p1 = aux[1]
p2 = aux[2]
p3 = aux[3]
p4 = aux[4]
p5 = aux[5] #
print p0
print p2
P0.append(p0)
P2.append(p2)
print file.next()
print file.next()
print file.next()
print file.next()
if re.match(middle_pattern, line):
passed_mid_point = True
print 'line = ', line
if re.match(end_pattern, line):
passed_mid_point = False
elif passed_mid_point:
# parse the coordinates
print 'line2 =', line
terms = line.split()
print 'terms =', terms
if terms and terms[1] == 'T':
print terms[1]
atomic_number = terms[2]
print 'atomic_number = ', atomic_number
ATOMIC_NUMBERS.append(atomic_number)
x = terms[4]
print 'x =', x
Xs.append(x)
y = terms[5]
print 'y = ', y
Ys.append(y)
z = terms[6]
print 'z = ', z
Zs.append(z)
print 'VOLUMES = ', VOLUMES
print 'P0 = ', P0
print 'P2 = ', P2
print 'Xs = ', Xs
print 'Ys = ', Ys
print 'Zs = ', Zs
print 'ATOMIC_NUMBERS = ', ATOMIC_NUMBERS
# create the empty list of lists:
atoms_all_frames = [[] for _ in xrange(len(VOLUMES))]
print atoms_all_frames
for index_vol in range(len(VOLUMES)):
for index in range(len(ATOMIC_NUMBERS)):
atoms_per_frame = [ATOMIC_NUMBERS[index], Xs[index], Ys[index], Zs[index]]
atoms_all_frames[index_vol].append(atoms_per_frame)
# "atoms_all_frames" would be an appropriate list for looping
print atoms_all_frames
# Remove any existing V*.inp files, to clean first:
for f in glob.glob("V*.inp"):
os.remove(f)
# create the files:
for V in VOLUMES:
filename = "V_{}.d12".format(V)
print filename
# open them:
with open(filename,"a") as f:
# the following is a pseudo-code, because I cannot manage to
# find the way to write element-wise each string to the files:
for p0, p2, atoms_all_frames:
f.write("""some stuff
other stuff
%s %s
%s
%s %s %s %s
%s %s %s %s
%s %s %s %s
other stuff
some other stuff\n""" % p0 % p2 %N_atom_irreducible_unit %atoms_all_frames)
A:
There are many ways to do this. The essential thing is to distinguish whether you have passed the mid_pattern since the same coordinate pattern exists both before and after it, and only the ones after it is desired.
For example, you can
set a flag so we know mid_pattern has matched
branch out at the end_pattern matching
passed_mid_point = False
...
if re.match(middle_pattern, line):
passed_mid_point = True
# do what you need
...
if re.match(end_pattern, line):
passed_mid_point = False # so you can process a new frame
# do what you need after end pattern is matched
...
elif passed_mid_point:
# parse the coordinates
terms = line.split()
if terms and terms[1] == 'T':
x = float(terms[4])
y = float(terms[5])
z = float(terms[6])
Or, you can flag and match, something like this:
passed_mid_point = False
coord_patter = r' \d+ T '
...
if re.match(middle_pattern, line):
passed_mid_point = True
# do what you need
...
if re.match(end_pattern, line):
passed_mid_point = False # so you can process a new frame
# do what you need after end pattern is matched
...
if passed_mid_point and re.match(coord_pattern, line):
# parse the coordinates
terms = line.split()
if terms and terms[1] == 'T':
x = float(terms[4])
y = float(terms[5])
z = float(terms[6])
The coordinate matching can be done fully in regular expression as well
sci_num = r'-?\d+\.\d*E[+\-]\d+'
coord_pattern = r'\s+\d+\sT\s+\d+\s+[A-Z]+\s+(%s)\s+(%s)\s+(%s)' % (sci_num, sci_num, sci_num)
coord_re = re.compile(coord_pattern)
if coord_re.match(line):
x = float(coord_re.group(1))
y = float(coord_re.group(2))
z = float(coord_re.group(3))
For recording the data, it will be better if you keep track of the frame that the atom coordinates belong to. For example, you can create a atom_frames at the beginning. And keep appending list of atom coordinates to it where each list corresponds to a frame. Overall it looks something like this
atom_frames = []
for i in range(50): # here I assume 50 frames
current_frame = []
for a in atoms_in_this_frame:
current_frame.append(a) # a could be (x, y, z) of an atom
atom_frames.append(current_frame)
Here I just loop over the frame counts. In your case, you can create current_frame = [] when you hit the mid_pattern. And do atom_frames.append(current_frame) when you hit end_pattern. Hope it makes sense.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Логика работы при поиске внутри geoQuery
Мне нужно применять несколько логических операторов при запросе фильтра, например:
let result = ymaps.geoQuery(Collection);
result.search(filter).setOptions(optionSet);
на данном этапе используется фильтр следующего содержания:
properties.freq != 5555
я же хочу искать в пределах от 5500 до 5600.
Как правильно сконструировать фильтр с логикой:
properties.freq >= 5500 and properties.freq <= 5600
Спасибо за ответ, однако фильтр работает лишь внутри диапазона, если я хочу выбрать за пределами его, т.е. менее 5500, но более 5600 - фильтр не отрабатывает, для меня это странно. Есть идеи почему так?
result.search(function (x) {
return x.properties.get('freq') >= 5500 &&
x.properties.get('freq') <= 5600;
}).getLength()
возвратит 140
result.search(function (x) {
return x.properties.get('freq') >= 5600 &&
x.properties.get('freq') <= 5500;
}).getLength()
возвратит 0
A:
GeoQueryResult#search принимает фильтр вида <поле> <операция> <значение> или любую функию.
result.search(function (x) {
return x.properties.get('freq') >= 5500 &&
x.properties.get('freq') <= 5600;
}).setOptions(options)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirect all requests to index.php and clean the URL
I was wondering if it's possible to redirect all requests to files/directories that do not exist to index.php, and after that clean the url.
So when I go to www.example.com/test/1 I want it to be redirected (rewrote?) to www.example.com
I tried the following and it does correctly load index.php, but it still says www.example.com/test/1 in the URL bar...
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]
Of course I still want my css and js to load properly...
A:
Try this. If I understand, you want to use this as a way of redirecting a 404 not found?
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [R=301,L]
Or maybe this without index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ / [R=301,L]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting ERROR while WAR file deploying in tomcat7
I have spring mvc based application. That is running tomcat7 server. Recently i made a few changes in my application. I created war file for entire application again. And i try to redeploy the new war file in tomcat7 server. When i click on my domain name i am getting "the requested page not available".
Why this error coming. I given all the properties file values correctly. could you please help me?
This is the production application. I used Linux servers and MySQL DB. Tomcat7, spring mvc and spring jdbc.
A:
The problem happens due jdk version. In my production server have jdk 1.7 but in my local i have jdk 1.8. I created war file with jdk 1.8 version. That's why i am getting that error. now i changed jdk version and recreate war file and deployed in server. Now it's working fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can SSMS display empty space as a character?
Right now I'm working on a dataset where I would like to return records where a certain field is NOT NULL. The dataset is result of a table join.
My resulting set is still returning records where the field I told not to return NULL look empty. I'd like to see what the true value in these records are since they don't seem to be true NULL.
Is there a way to get Management Studio to show spaces as a character just so I can see what's in there if anything?
A:
Not directly.
You'll have to modify the query.
Use replace to turn spaces into something else?
REPLACE(MyCol, ' ', '#')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
getting oracle.jdbc.dbaccess.DBError.throwUnsupportedFeatureSqlException error
I'm getting the following error :
Exception in thread "main" java.sql.SQLException:
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:269)
at oracle.jdbc.dbaccess.DBError.throwUnsupportedFeatureSqlException(DBError.java:689)
at oracle.jdbc.driver.OracleConnection.createStatement(OracleConnection.java:3224)
and this is pointing to the following line of Code :
ResultSet resultSet = getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT ).executeQuery(Request.getEtat());
This is mostly because of some unsupported feature in my environment, so what is the problem exactly with my snippet of code ?
Thank you very much for help.
A:
ResultSet.HOLD_CURSORS_OVER_COMMIT is only supported with Oracle 10g 10.2.0 and higher with the Oracle JDBC driver 10.2.0 or higher. See http://docs.oracle.com/cd/E11882_01/java.112/e16548/overvw.htm#JJDBC28045 :
Feature | Server-Side Internal | JDBC OCI | JDBC Thin
...
JDBC 3.0 Holdable Cursors | 10.2.0 | 10.2.0 | 10.2.0
As you indicate you are using Oracle 9i, the feature doesn't work and an exception is thrown. And as the exception is SQLException and not SQLFeatureNotSupportedException, I assume you are using an old driver as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In crusader kings 2, what decides which titles I can revoke through plot?
When you press pick ambition sometimes you get an ambition to revoke a title. This is a great way to reorganize your empire, without having to get claims on the title or incurring tyranny. But I can't figure out what decides which titles can be revoked through amibition. Anyone got a clue? So far I've ruled out:
Having a claim on the title.
Ruler desiring title.
Title was granted by ruler.
Holder of title doing traitorous stuff.
A:
The "Revoke the County of ___" plot only requires that a count level vassal hold more than one county (or that a duke holds a county outside of his duchy) and that you not be incapable or an imbecile. BUT meeting those requirements does not ensure that the plot will show up. There is also an apparently random element in which plots appear and that random element is affected by a number of personality traits and other factors. So a "Content" character is very unlikely to see this plot. And a "Kind" or "Slow" character is somewhat unlikely to see it. But an "Ambitious," "Decietful," "Envious" character who meets the basic requirements will almost certainly see it. The chances of it appearing are also affected by your opinion of the target. If you hate them (according to the game's calculation of your opinion) then it is more likely that you will have this plot available.
At least that is how I read the files. I'd welcome anyone who has more insight into this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Passing dictionary as parameter to a function
So, I am working on a project in which the user gives inputs in the json file and the parser reads data from the json file and then creates a data structure to which gets updated to the inputs mentioned in the data file.
My json file(input_file.json5) looks like this:
{
"clock_frequency": 25000,
"Triggering_Mode": "positive_edge_triggered",
"Mode": "Offline",
"overshoot": 0.05,
"duty_cycle": 0.5,
"amplitude/high_level": 1,
"offset/low_level": 0
}
The data structure(data_struc.py) looks like this:
Parameters={
"Global_parameters": {
"frequency": 3000,
"Triggering_Mode": "positive_edge_triggered"
},
"Executor_param": {
"Mode": "Offline"
},
"Waveform_Settings": {
"overshoot": 0.05,
"duty_cycle": 0.5,
"amplitude/high_level": 1,
"offset/low_level": 0,
}
}
The code for the parser is:
import json5
from data_struc import Parameters
class Parser(object):
def read_input_file(self, path_name, file_name):
input_file = open(path_name + file_name + '.json5')
data = json5.load(input_file)
print(Parameters['Global_parameters'])
parameters = self.parse_parameters(data)
input_file.close()
return parameters
def parser_parameters(self, data):
parameter = {
"Global_parameters": {
"frequency": data[clock_frequency]
"Triggering_Mode": data[Triggering_Mode]
}
}
return parameter
I want to pass data as a parameter to the function and I want to update the contents of the data structure using the value of the data(passed as dictionary) to the function. How do I implement the function parser_parameters?
A:
Here is a one-liner to map the data to a schema if you can change the schema, you could also just go and grab the keys instead of creating a list of items to match. This formats the data to the schema based on matching keys:
EDIT: added 'Data' tag to the schema and output for nested list data
schema = {
'Global_parameters': [
'clock_frequency', # I noticed you had this as just 'clock' in your desired outuput
'Triggering_Mode'
],
'Executor_param': [
'Mode'
],
'Waveform_Settings': [
'overshoot',
'duty_cycle',
'amplitude/high_level',
'offset/low_level'
],
'Data': {
'Packet'
}
}
data = {
"clock_frequency": 25000,
"Triggering_Mode": "positive_edge_triggered",
"Mode": "Offline",
"overshoot": 0.05,
"duty_cycle": 0.5,
"amplitude/high_level": 1,
"offset/low_level": 0,
"Packet": [
{"time_index":0.1, "data":0x110},
{"time_index":1.21, "data":123},
{"time_index":2.0, "data": 0x45}
]
}
# "one line" nested dict comprehension
data_structured = {k0: {k1: v1 for k1, v1 in data.items() if k1 in v0} # in v0.keys() if you are using the structure you have above
for k0, v0 in schema.items()}
import json
print(json.dumps(data_structured, indent=4)) # pretty print in json format
Output:
{
"Global_parameters": {
"clock_frequency": 25000,
"Triggering_Mode": "positive_edge_triggered"
},
"Executor_param": {
"Mode": "Offline"
},
"Waveform_Settings": {
"overshoot": 0.05,
"duty_cycle": 0.5,
"amplitude/high_level": 1,
"offset/low_level": 0
},
"Data": {
"Packet": [
{
"time_index": 0.1,
"data": 272
},
{
"time_index": 1.21,
"data": 123
},
{
"time_index": 2.0,
"data": 69
}
]
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Stretching a WPF Canvas Horizontally
How do I make a Canvas stretch fully horizontally with variable width? This is the parent Canvas, so it has no parents, only children.
XAML Source: it displays in blend
http://resopollution.com/xaml.txt
A:
Use a Grid as the top level element in your UI - it'll stretch to fill its container. Then put a Canvas with HorizontalAlignment="Stretch" inside the Grid and it'll behave the way you want.
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Canvas Background="Blue"/>
</Grid>
That worked for me. The key is your top level UI element. While a Grid fills all available space by default, Canvases take up only as much room as their contents demand.
A:
I'm guessing you've tried
canvas.HorizontalAlignment = HorizontalAlignment.Stretch
If this doesn't work, then what you could do is bind the Width and Height properties of the canvas to the ActualWidth and ActualHeight properties of the containing window.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OCaml compilation with corebuild
I currently have a project (Go to Python compiler) with the following files
ast.ml
parser.mly
lex.mll
weeder.ml
prettyPrint.ml
main.ml
Here are the dependencies:
parser: ast
lexer: parser, Core, Lexing
weeder: ast
prettyPrint: ast
main: ast, lex, parser, weeder, prettyPrint
I try to compile doing the following which should work according to the documentation I read:
$ menhir parser.mly
> Warning: you are using the standard library and/or the %inline keyword. We
recommend switching on --infer in order to avoid obscure type error messages.
$ ocamllex lex.mll
> 209 states, 11422 transitions, table size 46942 bytes
$ ocamlbuild -no-hygiene main.native
> File "parser.mli", line 77, characters 56-59:
Error: Unbound type constructor ast
Command exited with code 2.
Compilation unsuccessful after building 6 targets (2 cached) in 00:00:00.
ast.ml contains a list of type declarations in which I have a
type ast = ...
I spent a few hours now reading doc for ocamlfind, corebuild and ocamlopt and nothing. At some point it compiled by what seemed like a mere coincidence and never worked again. I'm open to using any tool.
Here is what is in parser.mly
%{
open Ast
exception ParserError of string
let rec deOptionTypeInList tupleList =
match tupleList with
| [] -> []
| (a, Some t)::tl -> (a, t)::(deOptionTypeInList tl)
| _ -> raise (ParserError "no type given in type declaration")
%}
[ ... long list of tokens ... ]
%type <ast> prog (* that seems to be the problem *)
%type <string> packDec
%type <dec> dec
%type <dec> subDec
[...]
%start prog
[ ... rules ... ]
And here is the line, the very last, that is refereed to in the error message.
val prog: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (ast)
A:
The open Ast construct will not be exported to the .mli file where the type of symbols are mentioned. Try using
%type <Ast.ast>
Edit: also, your build commands are weird. You should not call ocamllex and menhir manually, and consequently not need -no-hygiene. Remove all generated files and just do
ocamlbuild -use-menhir main.byte
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirect to 404 if .php extension is requested
When a user requests a page that ends with .php, I want to send them a 404 error even if the page exist. Is that possible to do with .htaccess/mod_rewrite??
http://mysite.com/whatever.php
A:
Haven't tested this, but it's something like:
RewriteRule \.php$ - [R=404]
Note: The Added Bytes mod_rewrite cheat sheet is a useful resource to have handy.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Color coded table plot based on the values in a pandas dataframe
I have a dataframe df containing string values
a b c d
b c d a
I would like to produce a pdf plot based on the data in the df, with 4 cols and 2 rows, where each cell in the table plot has a color depending on the value in the df, a=blue, b=red, c=yellow, d=green.
Like this
Thanks in advance!
A:
You can do in this way:
from matplotlib import colors as c
color_map = {'a':1,'b':2,'c':3, 'd':4}
cMap = c.ListedColormap(['g','b','y','r'])
df = df.replace(color_map)
fig, ax = plt.subplots()
ax.pcolor(df,cmap=cMap)
plt.show()
And If you want to remove the ticks, add plt.xticks([]) and plt.yticks([])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Updating multiple rows at once
Is it possible to update many rows at a same time?
Following query returns information of current department, an employee is working on.
SELECT a.empID, a.deparmentID
FROM customer a
INNER JOIN (
SELECT f.empID, max(f.myDate) md
FROM customer f
GROUP BY f.empID
) z ON z.empID = a.empID AND z.md = a.myDate
For example,following is the sample of my table:
empID deparmentID myDate
1 1 2011-01-01
2 1 2011-02-10
3 2 2011-02-19
1 2 2011-03-01
2 3 2011-04-01
3 1 2011-05-10
1 3 2011-06-01
So the above query will return,
empID departmentID
1 3
2 3
3 1
Now based on these return values, I want to update my table at one go.
Currently I am updating these values one at a time using for loop(very slow in performance),
my query for updating is :
for row in somerows:
UPDATE facttable SET deparment = row[1] WHERE empID = row[0]
...
but I want to know if it is possible to update all these values at once without using loop.
EDIT:
I have a single table. And I need to query the same table. This table does not have relation to any other tables.
The table structure is:
Table Name : Employee
Fields: EmpID varchar
DeptID varchar
myDate date
A:
you can try this
UPDATE mytable
SET myfield = CASE other_field
WHEN 1 THEN 'value1'
WHEN 2 THEN 'value2'
WHEN 3 THEN 'value3'
END
WHERE id IN (1,2,3)
This is just an example, you can extend it for your case.
Check the manual for more info
A:
Can you try this?
UPDATE customer c
SET depatmentID =
( SELECT a.deparmentID
FROM customer a
INNER JOIN
( SELECT empID
, max(myDate) AS md
FROM customer
GROUP BY empID
) AS z
ON z.empID = a.empID
AND z.md = a.myDate
WHERE a.empID = c.empID
)
or this:
UPDATE customer AS c
SET depatmentID = a.derpmentID
FROM customer a
INNER JOIN
( SELECT empID
, max(myDate) AS md
FROM customer
GROUP BY empID
) AS z
ON z.empID = a.empID
AND z.md = a.myDate
WHERE a.empID = c.empID
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Natbib: Multiple citations with page numbers in one bracket
I'm using natbib with bibliography style "apalike". I can cite two different papers in one bracket; for instance
\citep{adams03,collier09}
gives me
(Adams and Fournier, 2003; Collier et al., 1990).
I can also give page numbers for one source at a time; for instance
\citep[p.3]{adams03}
gives me
(Adams and Fournier, 2003, p.3).
My Question: What if I have page numbers for both sources? Is there a standard way to produce an output like
(Adams and Fournier, 2003, p.3; Collier et al., 1990, p.5)?
I'm not very keen on editing the bibstyle files myself if there is an easier way.
Any help is much appreciated!
A minimal example:
\documentclass{article}
\usepackage[american]{babel}
\usepackage[utf8]{inputenc}
\usepackage{natbib}
\begin{document}
\citep{adams03,collier09}
\citep[p.3]{adams03}
I would like to have something like (Adams and Fournier, 2003, p.3; Collier et al., 1990, p.5).
\bibliography{bibliography}{}
\bibliographystyle{apalike}
\end{document}
A:
It can be automatized, but the basic is like this:
\begin{filecontents*}{\jobname.bib}
@article{adams03,
author={A. Adams and F. Fournier},
title={?},
journal={?},
year=2003,
}
\@article{collier09,
author={C. Collier and S. Someone and T. Tomeone and V. Vomeone},
title={?},
journal={?},
year=2009,
}
\end{filecontents*}
\documentclass{article}
\usepackage[american]{babel}
\usepackage[utf8]{inputenc}
\usepackage{natbib}
\begin{document}
\citep{adams03,collier09}
\citep[p.~3]{adams03}
(\citeauthor{adams03}, \citeyear{adams03}, p.~3; \citeauthor{collier09}, \citeyear{collier09}, p.~5).
\bibliography{\jobname}
\bibliographystyle{apalike}
\end{document}
A better version, with a syntax slightly different from \citep, but easier to manage for multiple citations:
\begin{filecontents*}{\jobname.bib}
@article{adams03,
author={A. Adams and F. Fournier},
title={?},
journal={?},
year=2003,
}
\@article{collier09,
author={C. Collier and S. Someone and T. Tomeone and V. Vomeone},
title={?},
journal={?},
year=2009,
}
\end{filecontents*}
\documentclass{article}
\usepackage[american]{babel}
\usepackage[utf8]{inputenc}
\usepackage{natbib}
\usepackage{xparse}
\ExplSyntaxOn
\makeatletter
\NewDocumentCommand{\multicitep}{m}
{
\NAT@open
\mjb_multicitep:n { #1 }
\NAT@close
}
\makeatother
\seq_new:N \l_mjb_multicite_in_seq
\seq_new:N \l_mjb_multicite_out_seq
\seq_new:N \l_mjb_cite_seq
\cs_new_protected:Npn \mjb_multicitep:n #1
{
\seq_set_split:Nnn \l_mjb_multicite_in_seq { ; } { #1 }
\seq_clear:N \l_mjb_multicite_out_seq
\seq_map_inline:Nn \l_mjb_multicite_in_seq
{
\mjb_cite_process:n { ##1 }
}
\seq_use:Nn \l_mjb_multicite_out_seq { ;~ }
}
\cs_new_protected:Npn \mjb_cite_process:n #1
{
\seq_set_split:Nnn \l_mjb_cite_seq { , } { #1 }
\int_compare:nTF { \seq_count:N \l_mjb_cite_seq == 1 }
{
\seq_put_right:Nn \l_mjb_multicite_out_seq
{ \citeauthor{#1},~\citeyear{#1} }
}
{
\seq_put_right:Nx \l_mjb_multicite_out_seq
{
\exp_not:N \citeauthor{\seq_item:Nn \l_mjb_cite_seq { 1 }},~
\exp_not:N \citeyear{\seq_item:Nn \l_mjb_cite_seq { 1 }},~
\seq_item:Nn \l_mjb_cite_seq { 2 }
}
}
}
\ExplSyntaxOff
\begin{document}
\citep{adams03,collier09}
\citep[p.~3]{adams03}
\multicitep{adams03, p.~3; collier09, p.~5}.
\multicitep{adams03, p.~3; collier09, p.~5}.
\multicitep{adams03; collier09, p.~5}.
\multicitep{adams03; collier09, p.~5}.
\bibliography{\jobname}
\bibliographystyle{apalike}
\end{document}
Different keys are separated by a semicolon, a postnote is separated from the key by a comma (if a comma is in the postnote, place it between braces). You can actually use it for a single citation, like
\multicitep{adams03, p.~3}
A:
Also consider the \citealp syntax described at http://merkel.texture.rocks/Latex/natbib.php
You still need to bring your own parentheses and semicolons, but the syntax is slightly more compact than above (modified code below):
\begin{filecontents*}{\jobname.bib}
@article{adams03,
author={A. Adams and F. Fournier},
title={?},
journal={?},
year=2003,
}
\@article{collier09,
author={C. Collier and S. Someone and T. Tomeone and V. Vomeone},
title={?},
journal={?},
year=2009,
}
\end{filecontents*}
\documentclass{article}
\usepackage{natbib}
\begin{document}
\citep{adams03,collier09}
\citep[p.~3]{adams03}
(\citeauthor{adams03}, \citeyear{adams03}, p.~3; \citeauthor{collier09}, \citeyear{collier09}, p.~5).
(\citealp[p.~3]{adams03}; \citealp[p.~5]{collier09}).
\bibliography{\jobname}
\bibliographystyle{apalike}
\end{document}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error sending json in POST to web API service
I'm creating a web service using Web API. I implemented a simple class
public class ActivityResult
{
public String code;
public int indexValue;
public int primaryCodeReference;
}
And then I have implemented inside my controller
[HttpPost]
public HttpResponseMessage Post(ActivityResult ar)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
But when I call the API passing in POST the file json:
{"code":"XXX-542","indexValue":"3","primaryCodeReference":"7"}
I obtain the following error message:
{
"Message": "The request entity's media type 'text/plain' is not supported for this resource.",
"ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'ActivityResult' from content with media type 'text/plain'.",
"ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
"StackTrace": " in System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n in System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n in System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}
What am I doing wrong?
A:
In the HTTP request you need to set Content-Type to: Content-Type: application/json
So if you're using fiddler client add Content-Type: application/json to the request header
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Storing parameters in a class, and how to access them
I'm writing a program that randomly assembles mathematical expressions using the values stored in this class.
The operators are stored in a dictionary along with the number of arguements they need.
The arguements are stored in a list. (the four x's ensure that the x variable gets chosen often)
depth, ratio, method and riddle are other values needed.
I put these in a class so they'd be in one place, where I can go to change them.
Is this the best pythonic way to do this?
It seems that I can't refer to them by Params.depth. This produces the error 'Params has no attribute 'depth'. I have to create an instance of Params() (p = Params()) and refer to them by p.depth.
I'm faily new to Python. Thanks
class Params(object):
def __init__(self):
object.__init__(self)
self.atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x']
self.operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2}
self.depth = 1
self.ratio = .4
self.method = ''
self.riddle = '1 + np.sin(x)'
A:
What you have there are object properties. You mean to use class variables:
class Params(object):
atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x']
operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2}
depth = 1
ratio = .4
method = ''
riddle = '1 + np.sin(x)'
# This works fine:
Params.riddle
It's fairly common in Python to do this, since pretty much everyone agrees that Params.riddle is a lot nicer to type than Params['riddle']. If you find yourself doing this a lot you may want to use this recipe which makes things a bit easier and much clearer semantically.
Warning: if that Params class gets too big, an older, grumpier Pythonista may appear and tell you to just move all that crap into its own module.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Какая разница между оператором !! (not not) и простым if блоком без ничего?
Есть такой код:
const a = 4;
if(!!a){
console.log("not not");
}
if(a){
console.log("truish");
}
Выведет с начало not not потом truish.
Какая разница между двумя этими подходами ?
Этот вопрос не про то как работает оператор !! (или not not) а какая разница между двумя этими подходами наверху.
A:
!! - преобразует выражение (переменную) в логический тип явно,
то есть в вашем примере
console.log(a) //4
console.log(!!a) //true
с точки зрения вашего примера особо разницы нет.
Но если написать:
if(a === true) //так не сработает
if(!!a === true) //так сработает
фактически !!a === Boolean(a)
интересная особенность
'0' == 0 // true
!!'0' == !!0 // false
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Geary mail is not logging in my Gmail account
When I am trying to sign in my Gmail with existing Geary mail in Freya. It's failed to login. And I don't know the problem. But the username and password both are right.
A:
The simple workaround would be:
Loginto your gmail account
Click on the link : Enable access for less secure apps
Turn ON
Now login to geary. It will work now.
Don't get panic with the word "less secure"
See Gmail: Geary doesn't meet modern security standards
A:
First, use two-factor authorization for your Google account. This will require you to have your phone each time you want to sign in to Google, but it's a really good idea to be vigilant about your Google credentials.
Next, you'll notice that because you have set up two-factor authorization, you won't be able to drop the security level in the link above. Instead, set up an app password for Geary.
https://support.google.com/accounts/answer/185833
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Faltings height of a CM abelian variety
Let A be a CM abelian variety, say simple of dimension g, with $End(A) = O_K$, where $K$ is a CM field
of degree $2g$.
Is there an upper bound for the Faltings height $h(A)$ in terms of the discriminant $d_K$ of $K$?
A:
Fix an $A$ with CM by $K$, and for each $D$, let $A_D$ be the quadratic twist of $A$ by $K(\sqrt{D})/K$. Also let $$h_{sf}(D)=\min(h(Dd^2):d\in K^*)$$ denote the "square-free height" of $D$. Then
$$
h_{\text{Faltings}}(A_D) \gg h_{sf}(D),
$$
which shows that there is no upper bound of the sort that you want, since $K$ is fixed, while $h_{sf}(D)$ can be arbitrarily large.
Or do you mean to take the semi-stable Faltings height, i.e., the height obtained after going to a field where $A$ has semi-stable reduction. For CM abelian varieties, this would be a field where $A$ has everywhere good reduction, so the Faltings height comes entirely from the archimedean places. In this case, you can use the fact that the Faltings height is more-or-less equal to the height of the associated point in moduli space. (At least, equal enough to talk about boundedness.) For a principally polarized CM abelian variety, the moduli point is essentially given by the periods, which are more-or-less a basis for $\mathcal{O}_K$ over $\mathbb{Z}$. So it seems that one might well be able to get a bound in terms of $\hbox{Disc}(K)$.
You might try looking first at the case of elliptic curves, where the relation between the Faltings height and the periods is very explicit.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ / CLI: Add item to managed collection
I have created a collection in CLI:
List<MyClass>^ list = gcnew List<MyClass>();
MyClass is class from c#.
I try to add new item to collection:
MyClass^ item = gcnew MyClass();
list->Add(item);
In this case I have error: function Add cannot be called with the given argument list.
How to avoid this, I don`t know:(
Please, help!
A:
You need List<MyClass^>^ list; (note the additional ^).
This is because MyClass is a reference type, and you can only have references of it (using ^ and created with gcnew or via c# code).
List<MyClass^>^ list = gcnew List<MyClass>();
MyClass^ item = gcnew MyClass();
list->Add(item);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cannot display a Unicode character (Emoji) in an Android TextView with large text: "Font size too large to fit in cache"
I'm trying to display a single Unicode character (an emoji) in a TextView, with a large(r) text size:
mEmojiTextView = (TextView) findViewById(R.id.emoji_text_view);
mEmojiTextView.setTextSize(200);
mEmojiTextView.setText("\uD83D\uDE01");
The character does not appear on the screen, and I get this error in logcat:
E/OpenGLRenderer﹕ Font size too large to fit in cache. width, height = 545, 513
The largest size that works is
mEmojiTextView.setTextSize(150);
and the Emoji character appears. It's not like it's full screen or anything, at this text size there is enough space on the screen for about 6 emoji characters.
I'm running the test on a LG Nexus 5 phone, with 1080 x 1920 resolution, running Android 5.1.1. I'm using minSdkVersion 11 and targetSdkVersion 23
I tried many workarounds found on StackOverflow and elsewhere:
mEmojiTextView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
<TextView android:layerType="software" ... />
<activity android:hardwareAccelerated="false" ... />
Nothing works.
Is there a way I can get it to work?
A:
It's an android issue Issue with emoji with 200sp size
No way to fix it at the moment, just don't set size more than 199 if you have emoji in TextView
|
{
"pile_set_name": "StackExchange"
}
|
Q:
semantic ui Form validation issue
I tried to use the 'Semantic Form Validation' plugin to validate input length, like this:
$('.ui.form').form({
fields: {
firstname: {
identifier: 'firstname',
rules: [{
type: 'empty',
prompt: 'Please enter your name'
}]
},
lastname: {
identifier: 'lastname',
rules: [{
type: 'empty',
prompt: 'Please enter your name'
}]
},
username: {
identifier: 'username',
rules: [{
type: 'minLength[3]',
prompt: 'Please enter a username'
}]
},
password: {
identifier: 'password',
rules: [{
type: 'minLength[6]',
prompt: 'Please enter a password'
}]
},
terms: {
identifier: 'terms',
rules: [{
type: 'checked',
prompt: 'You must agree to the terms and conditions'
}]
}
}
});
Every single line works just fine but it will not validate minLength rule and keep getting error on it. It says
Form: There is no rule matching the one you specified minLength
A:
I have been having the same issue today. I tried loads of variations. Then I went and looked for any reference to minLength in the semantic.js source code (and there is nothing there!..). Then I stumbled across function called length
length .. // is at least string length
length: function(value, requiredLength) {
return (value !== undefined)
? (value.length >= requiredLength)
: false
;
},
// so thought i would give that a try and it worked as you would expect..
password: {
identifier: 'password',
rules: [{
type: 'length[6]',
prompt: 'Please enter a password'
}]
},
// I am using version Semantic UI - 2.0.0.
I am still struggling a bit with this features of semantic ui , I cant get the shorthand syntax to work and also cant find a way to have multiple criteria per field.. any suggestions?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WSO2 ESB - How process messages one by one (in series) from messages store
I try use sample process and scheduler process to do it. But they are work by fixed intervals and don't wait finish previous message.
A:
A forwarding message processor (class ScheduledMessageForwardingProcessor) wait for the http response before dequeueing next message in the store, if the response is OK.
In case of error, 404 for exemple, it rollback JMS transaction and continue with the same message again and again.
The interval used in the ScheduledMessageForwardingProcessor's definition is the interval use by the MP to dequeue next message after a response.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
redirect_to method propagates DELETE http action throughout nested routes
The above is the result of deleted comment. Notice that as you delete a comment, the comment's parent post is also deleted through redirect_to
Started DELETE "/posts/19/comments/30" for 127.0.0.1 at 2012-12-03 01:10:43 -0800
Processing by CommentsController#destroy as JS
Parameters: {"post_id"=>"19", "id"=>"30"}
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = ? LIMIT 1 [["id", "30"]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "19"]]
CACHE (0.0ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = ? LIMIT 1 [["id", "30"]]
(0.0ms) begin transaction
SQL (0.2ms) DELETE FROM "comments" WHERE "comments"."id" = ? [["id", 30]]
(7.7ms) commit transaction
Redirected to http://localhost:3000/posts/19
Completed 302 Found in 13ms (ActiveRecord: 8.4ms)
Started DELETE "/posts/19" for 127.0.0.1 at 2012-12-03 01:10:43 -0800
Processing by PostsController#destroy as JS
Parameters: {"id"=>"19"}
Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "19"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
CACHE (0.0ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "19"]]
(0.0ms) begin transaction
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 19
SQL (0.2ms) DELETE FROM "posts" WHERE "posts"."id" = ? [["id", 19]]
(1.1ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 6ms (ActiveRecord: 1.7ms)
Started DELETE "/" for 127.0.0.1 at 2012-12-03 01:10:43 -0800
Processing by PagesController#home as JS
Rendered pages/home.html.haml within layouts/application (0.1ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Completed 200 OK in 40ms (Views: 39.3ms | ActiveRecord: 0.2ms)
routes.rb
resources :posts do
member do
put "soft_destroy"
end
resources :comments do
member do
get "reply"
post "create_reply"
put "soft_destroy"
end
end
end
comments controller
def destroy
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to @post
end
delete link on view file
= link_to "delete", [@post, comment], method: :DELETE, remote: true
Post model
has_many :comments, dependent: :destroy
accepts_nested_attributes_for :comments
Comment model
belongs_to :post
Is there a reason why DELETE html verb propagates on posts controller as well? Rather than just calling show action?
A:
The problem was caused by delete link on view file
= link_to "delete", [@post, comment], method: :DELETE, remote: true
For some reason, ajax request with method DELETE seems to propagate beyond the first DELETE request.
I removed remote: true and it now makes a GET request rather than DELETE request to the post.
= link_to "delete", [@post, comment], method: :DELETE
I still don't understand why this is happening though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make a request SELECT on an oracle db with parameters ? C#
I want do the folowing request :
SELECT nom_projet, version_projet, version_build FROM analyses WHERE nom_projet=:Variable1 and version_projet=:Variable2 and version_build=:Variable3";
I dont understand why it doesn't work because i have done the same code for a request INSERT and this one works perfectly.
Code C#
public Boolean VerifierVersionDejaPresnte(ParseurXML.DonneesGblobale donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT nom_projet, version_projet, version_build FROM analyses WHERE nom_projet=:Variable1 and version_projet=:Variable2 and version_build=:Variable3"
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new OracleParameter("Variable1",donneGblobale._nom));
cmd.Parameters.Add(new OracleParameter("Variable2",donneGblobale._version));
cmd.Parameters.Add(new OracleParameter("Variable3",donneGblobale._build));
OracleDataReader reader = cmd.ExecuteNonQuery();
if(reader.HasRows)
return true;
return false;
}
A:
You are calling ExecuteNonQuery while you should call ExecuteReader.
ExecuteNonQuery is used for Insert,Update and Delete commands.
OracleDataReader reader = cmd.ExecuteReader();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Session Variable behaving different on Visual Studio and Server
I want a certain segment of code to be executed only once per session, so if the user navigates to the page containing this code while within the same session, I don't want this segment to be executed. The code lives in a default page that is called right after login, and user can navigate to this default page from other pages.
My Solution:
if (Session["MySessionName"] == null && ConditionTwo) //initially MySessionName won't exist so the if condition resolves to true
{
//Assign Value to MySessionName so the if condition resolves to false next time
Session["MySessionName"] = "MySessionValue";
//Do Something
}
My Problem:
This works fine on visual studio, after deploying to test server this solution doesn't seem to work all the time. If I log out and log back in, the condition Session["MySessionName"] == null returns false and the code segment won't be executed. However if I close the browser, reopen, and log in, it works fine. I have checked if the logout did a proper session dispose and it does.
I also tried,
HttpContext.Current.Session["MySessionName"] = "MySessionValue";
//and
Session.Add("MysessionName", true);
but result was the same.
A:
If you are using forms authentication, you need to call FormsAuthentication.SignOut().
In addition, on logout you need to call Context.Session.Abandon() to terminate the current session.
I also make sure that I always explicitly clear any sensitive or user-related values from the session state prior to abandoning the session.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML 5 Autoplay Google Chrome Android Not Playing
I'm trying to play automatically a video when the user open the page on browser. On my laptop autoplay works on all browsers, but on android it doesn´t work on Google Chrome and in Iphone it doesn't works in safari. I already did a search and google chrome in android doesn't support html5 video tag so i used some javascript but it doesn't work too.
Why? What should i do?
Here's my code
<video id="video" autoplay autobuffer controls="controls" allowFullScreen >
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm" webView.mediaPlaybackRequiresUserAction = NO;>
<source src="video.theora.ogv" type="video/ogg">
<source src="video.flv" type="video/flv">
<source src="video.vob" type="video/vob">
<source src="video.mov" type="video/mov">
</video>
<script type="text/javascript">
var video = document.getElementById('video'); video.addEventListener('video',function(){
video.play();
});
video.addEventListener("domready", function(){ video.play();
});
video.addEventListener("ended", function(){
window.location = "http://www.google.com"
});
</script>
A:
Muted autoplay for video is supported by Chrome for Android as of version 53. Playback will start automatically for a video element once it comes into view if both autoplay and muted are set, and playback of muted videos can be initiated progamatically with play(). Previously, playback on mobile had to be initiated by a user gesture, regardless of the muted state.
<video autoplay muted>
<source src="video.webm" type="video/webm" />
<source src="video.mp4" type="video/mp4" />
</video>
A:
I was also trying to autoplay videos on android chrome and found this:
On Android, html5 video autoplay attribute does not work
&num1 [email protected]
Yes. It is as design. "autoplay" is disabled for Chrome for Android.
Apparently it's intentional.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UMD modules in a Chrome Extension
The UMD module definition is approximately this:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'b'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('b'));
} else {
// Browser globals
factory((root.commonJsStrict = {}), root.b);
}
}(this, function (exports, b) {
//use b in some fashion.
// attach properties to the exports object to define
// the exported module properties.
exports.action = function () {};
}));
The issue is that Chrome Extensions don't support any of these methods of exporting the module:
define doesn't exist
exports doesn't exist
this isn't bound to window
For this reason, it seems that UMD modules fail in Chrome Extension environments. Is there any workaround to get a UMD module to correctly export into the window object in a Chrome Extension?
A:
As @wOxxOm has correctly pointed out, the Chrome Extension environment is the same as the browser, and this is indeed bound to window, so UMD modules can and should work with extensions.
It turns out the actual problem is that babel was producing a bundle with this replaced by undefined, which is the problem outlined and resolved in this issue: How to stop babel from transpiling 'this' to 'undefined' (and inserting "use strict").
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Parse multiple URLs and extract data
I need to parse a HTML page, get all the URLs meeting my requirement.
Now, I need to parse each of the extracted URLs to get the data that I want, if the page title matches something and save them to multiple files based on their names.
I have done part 1 in the following way.
pattern=re.compile(r'''class="topline"><A href="(.*?)"''')
da = pattern.search(web_page)
da = pattern.findall(soup1)
col_width = max(len(word) for row in da for word in row)
for row in da:
if "some string" in row.upper():
bb = "".join(row.ljust(col_width))
print >> links, bb
I'd truly appreciate any help.
Thank you.
A:
First of all, do not parse HTML with regex. You've actually marked the question with BeautifulSoup tag, but you are still using regular expressions here.
Here's how you can get the links, follow them and check the title:
from urllib2 import urlopen
from bs4 import BeautifulSoup
URL = "url here"
soup = BeautifulSoup(urlopen(URL))
links = soup.select('.topline > a')
for a in links:
link = link.get('href')
if link:
# follow link
link_soup = BeautifulSoup(urlopen(link))
title = link_soup.find('title')
# check title
.topline > a CSS selector would find you any tag with topline class and get the a tag right beneath.
Hope that helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Responsive CSS isn't working properly?
Here's the site: Website
There are some navigation arrows I'm trying to hide in mobile view.
Here's the HTML...
<div id="nav_arrow">
<a href="index.html"><img src="images/icons/arrow_left.png" width="60" height="44"></a>
</div>
Here's the CSS...
#nav_arrow { display: none; }
The media query appears to be typed out correctly. The style works when the phone (iPhone 5) is held vertically. But, when I hold it in a landscape view, the arrows show up. I'm trying to not have them display unless the site is pulled up in tablet view or larger?
Any ideas?
Update 1
This is the section of CSS where I have the media query...
@media only screen and (max-width: 480px) {
#nav { display:none;}
#secondary-nav { display:none; }
#footer-social { float:left; }
.jcarousel-skin-tango .jcarousel-next-horizontal { right:0; }
.jcarousel-skin-tango .jcarousel-prev-horizontal { right: 43px;}
.jcarousel-skin-tango .jcarousel-item { width: 300px !important; }
.jcarousel-skin-tango .jcarousel-item-horizontal {margin-right: 20px;}
#latest-projects .block, #latest-posts .block, .programs .block { width:295px; height:inherit; }
#latest-projects .stack, #latest-posts .stack, .programs .stack { width:295px; height:274px; }
#latest-projects .block img, #latest-posts .block img, .programs .block img { width:283px; height:262px; }
#latest-projects .block .mask, #latest-posts .block .mask, .programs .block .mask { width:283px; height:261px; }
.nav-projects .viewall { display:none;}
#clients .block { width:298px;}
#clients .block img { width:298px;}
#info-block ul li > div { height: 85px; width: 270px; }
#latest-projects .block iframe, #latest-posts .block iframe, .programs .block iframe { width:283px; height:262px; }
.fix-fish-menu select { display:block; }
#menu { float: none; }
#clients .columns { padding-bottom:20px; }
.ribbon-front { left: 1px; }
.ribbon-edge-topleft, .ribbon-edge-bottomleft { display:none; }
#footer-social li { margin-right: 5px; margin-left: 0px; }
#top-panel .columns { margin-bottom:20px;}
#contacts-form input[type=text], #contacts-form input[type=password], #contacts-form input[type=email] { width:130px;}
#contacts-form textarea { width: 290px; }
#contact-info li { width:275px; }
#latest-posts .mejs-container {width:265px !important;}
#latest-posts .block .text { height: 200px;}
#latest-posts .block { width:295px; height:274px; }
#nav_arrow { display: none; }
.link-icon { background-position: top: 100px; right: 100px; bottom: 100px; left: 60px; }
The specific tag is on the bottom. Second to last.
A:
Are you sure you are using the right mediaquery?, have you tried the orientation property:
@media only screen and (min-device-width : 320px) and (max-device-width : 568px) and (orientation : landscape) {}
or maybe device-aspect-ratio would be more accurate for iphone 5:
@media screen and (device-aspect-ratio: 40/71) and (orientation : landscape) {}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Controls added dynamically don't persist
I have this panel...
<asp:Panel ID="panSumarios" runat="server" style="border:0px solid red;width:100%" ViewStateMode="Enabled"></asp:Panel>
...inside a div associated to a ModalPopupExtender.
Then, on a button click, I add some controls (textboxes) dinamically to this panel. When I close (confirm) the ModalPopupExtender, I try to access this textboxes with no luck. They don't exist. It seems they do not persist after postback (when I confirm ModalPopupExtender).
Any ideas?
Thanks in advance.
A:
there are a few things going on here. the biggest is confusing html controls with webforms server controls. another factor, if the added controls are web forms server controls, is when the dynamic controls are added.
dynamic webforms server controls must be created in the Init event to be properly wired to viewstate. they must also be created on every request.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Copying arrays to slices in Go
Please can you help me understand how generating a slice from an array works. Why are ID1 and ID2 not the same?
a := [2]string{"a", "b"}
b := [2]string{"c", "d"}
var z [2][2]string
z[0] = a
z[1] = b
fmt.Printf("%s\n", z)
var id [][]string
for _, t := range z {
temp := t[:]
id = append(id, temp)
}
fmt.Printf("\nid1 = %s", id)
var id2 [][]string
for _, t := range z {
temp := t
id2 = append(id2, temp[:])
}
fmt.Printf("\nid2 = %s", id2)
[[a b] [c d]]
id1 = [[c d] [c d]]
id2 = [[a b] [c d]]
A:
Because the for range loop has a single iteration variable which is reused in each iteration. Spec: For statements: For statements with for clause
Variables declared by the init statement are re-used in each iteration.
So in your first loop:
for _, t := range z {
temp := t[:]
id = append(id, temp)
}
There is a single t, and you slice the same t array, so each temp slice you append, it will point to the same backing array, which is t, and it is overwritten in each iteration, so its value will be the value of the last iteration: [c d].
In your second loop:
for _, t := range z {
temp := t
id2 = append(id2, temp[:])
}
Also there is a single t iteration variable, but you make a copy of it: temp := t, and you slice this copy, which is detached from t, and you append a slice that has the copy as its backing array, which will not be overwritten in each iteration.
A:
This is the problematic assignment. It is not what it seems:
temp := t[:]
Here, t is an array and the loop variable. That means at each iteration, the contents of the current array is copied onto t. At the first iteration, t=[]string{"a","b"}, and a slice is created to point to this array and assigned to temp. At the second iteration t is overwritten to become []string{"c","d"}. This operation also overwrites the contents of the first slice. So, you end up with the {{"c","d"},{"c","d"}}. The important point here is that contents of t gets overwritten, and t is shared between the two slices.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP: Pull values foreach() nested array, run function, return a 2nd level nested array
I've got an array that looks like this:
Array
(
[0] => Array
(
[id] => abc
[name] => Charlotte
[state] => NC
)
[1] => Array
(
[id] => def
[name] => Tampa
[state] => FL
)
)
What I am trying to do is pull two of the values from each nested array ('id' and 'name'), run a function on them, and return an array that is then nested. So, for each 'id' and 'name,' pass that to "function work($id,$name)," which returns an array, such that the resulting array looks like this:
Array
(
[0] => Array
(
[id] => abc
[name] => Charlotte
[state] => NC
[restaurants] => Array (
[rname] => Good Burger
[rname] => McD
)
)
[1] => Array
(
[id] => def
[name] => Tampa
[state] => FL
[restaurants] => Array (
[rname] => BK
[rname] => White Castle
)
)
)
My searches on here found a few ways of pulling the values from the original arrays (foreach() loop), but I am unsure of the best way to pass these values to a function (array_walk doesn't appear to be an option in this case?), and especially of how to return a nested array into another nested array.
Am glad to provide clarification is need be.
A:
foreach ($array as $key => $value){
$array[$key]['restaurants'] = work($value['id'],$value['name']);
}
function work($id,$name){
$results = array();
///process data
return $results;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using %matplotlib notebook after %matplotlib inline in Jupyter Notebook doesn't work
I am using Jupyter Notebook for plotting piechart figures.
In first cell with my code I have a magic command %matplotlib inline and after this magic command I run my code, everything works fine and my figure renders.
But in second cell when I set %matplotlib notebook for interactive plotting my figure won't render after running this second cell.
I need to restart kernel and run cell with %matplotlib notebook again and cannot run %matplotlib inline command before that.
Here is my code for first cell with %matplotlib inline, which renders fine:
import matplotlib.pyplot as plt
%matplotlib inline
labels = "No", "Yes"
sizes = [100, 50]
fig, ax = plt.subplots(figsize=(6, 6))
_, texts, autotexts = ax.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',
shadow=False, startangle=90)
ax.axis('equal')
After that I have second cell with same code, just %matplotlib inline is changed to %matplotlib notebook. Figure won't render after I run this cell and I need to restart kernel and run this cell again.
Why?
A:
You just have the wrong order of your commands. A backend should be set before importing pyplot in jupyter. Or in other words, after changing the backend, pyplot needs to be imported again.
Therefore call %matplotlib ... prior to importing pyplot.
In first cell:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])
In second cell:
%matplotlib notebook
#calling it a second time may prevent some graphics errors
%matplotlib notebook
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])
A:
Edit: turns out that you can in fact change backends dynamically on jupyter. Still leaving the answer here because I think it's relevant and explains some matplotlib magic that can pop out sometimes.
The magic command, as seen in the source code, is calling matplotlib.pyplot.switch_backend(newbackend) to change the backend. As stated in matplotlib's docs:
matplotlib.pyplot.switch_backend(newbackend)
Switch the default backend. This feature is experimental, and is only expected to work switching to an image backend. e.g., if you have a bunch of PostScript scripts that you want to run from an interactive ipython session, you may want to switch to the PS backend before running them to avoid having a bunch of GUI windows popup. If you try to interactively switch from one GUI backend to another, you will explode..
So you really have to restart the kernel each time you switch backends, because matplotlib has a problem to switch the backend after being used.
This problem is mainly due to incompatibilities between different main-loops of the GUI backend. Because normally each backend is also taking care of threads and user input you can't run Qt and Tkinter side-by-side. So that limitation is carried over to jupyter.
Also see this question: How to switch backends in matplotlib / Python
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to convert 'MS.Internal.Data.CollectionViewGroupInternal' to use?
I reference this way, and create my DataGrid.
But I need to use parameter when I invoke Command.
I see that is a MS.Internal.Data.CollectionViewGroupInternal type, and I don't know how to convert it.
The 'MS.Internal.Data.CollectionViewGroupInternal' have items and it's name, how can I get it? Or, I can bind my parameter to CommandParameter, maybe like SelectedItem of DataGrid, because I have a DependencyProperty for click Expander.
public class ExpanderDataGrid : DataGrid
{
public string SelectedExpanderName
{
get
{
return (string)GetValue(SelectedExpanderNameProperty);
}
set
{
SetValue(SelectedExpanderNameProperty, value);
}
}
public static readonly DependencyProperty SelectedExpanderNameProperty = DependencyProperty.Register("SelectedExpanderName",
typeof(string), typeof(ExpanderDataGrid),
new FrameworkPropertyMetadata("",
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}
A:
I find the answer from here.
I can cast that to CollectionViewGroup, and got it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
An inequality about a continuous function.
Let $\Omega \subset \Bbb R ^2$ be bounded and closed, and let $g : \Omega \to \Bbb [0, \infty)$ be continuous. Let $g(x_0,y_0)=\max \limits_{\Omega} g(x,y)$. Show that:
$\exists \rho_{x_0},\rho_{y_0}>0$, $\forall(x,y)\in \Omega,|x-x_0|<\rho_{x_0},|y-y_0|<\rho_{y_0}$, then $g(x,y_0)\geq g(x,y)$.
In fact, I think the $\Omega$ is bounded and closed is not necessary. All of the above is my guess, I really don't know whether it is right. Thanks for any answer or advice.
A:
It is not true. The strict inequality is trivially false by taking $x=x_0$, $y=y_0$. The non-strict one is not true either. Consider $g(x,y)=-(x-y)^2$ and $(x_0,y_0)=(0,0)$. Then
$$
g(x,y_0)=-x^2<g(x,x)=0
$$
for all $x\ne x_0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP: new array from several arrays
I'm teaching myself PHP and I have the following question about arrays:
I have:
$names = array('John', 'Alice', 'Tom');
$cities = array('London', 'NY', 'Boston');
$years = array('1999', '2010', '2012');
$colors = array('red', 'blue', 'green');
I want to have a new array with these elements (three subarrays):
John London 1999 red
Alice NY 2010 blue
Tom Boston 2012 green
I'm doing
$newArray = array($names,$cities, $years,$colors);
But this shows all the names, cities and so all together :( Please show me how to achieve this.
Thanks a lot!
A:
To get output like this --
John London 1999 red
Alice NY 2010 blue
Tom Boston 2012 green
You have to do following
$result = array();
foreach($names as $key=>$value){
$result[]='<pre>'.$value.' '.$cities[$key].' '.$years[$key].''.$colors[$key].'</pre>';
}
Then implode the generated array
$output=implode('',$result);
echo $output;
A:
If You want the three list to be arrays with each value an element in a sub array, do this:
$names = array('John', 'Alice', 'Tom');
$cities = array('London', 'NY', 'Boston');
$years = array('1999', '2010', '2012');
$colors = array('red', 'blue', 'green');
$final_array = array();
foreach($names as $count => $name){
array_push($final_array,array($name,$cities[$count],$years[$count],$colors[$count]));
}
var_export($final_array);
This gives an output of:
array (
0 =>
array (
0 => 'John',
1 => 'London',
2 => '1999',
3 => 'red',
),
1 =>
array (
0 => 'Alice',
1 => 'NY',
2 => '2010',
3 => 'blue',
),
2 =>
array (
0 => 'Tom',
1 => 'Boston',
2 => '2012',
3 => 'green',
),
If you want the result to be an array of strings use Mihai's answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does absolute integrability imply integrability?
I am quite confused about the notion of integrability. In the context of an introduction to complex analysis and Fourier transforms, I am told that if $f$, a complex or real valued function, satisfies the following:
$$ \int_{-\infty}^{\infty} \lvert f(x) \rvert dx<\infty$$
then it is absolutely integrable. However, does this also imply that $f$ is integrable? What can we conclude about $f$ given the above condition on its absolute value (or modulus). I have no notions of Lebesgue integrability.
A:
Absolutely integrable and Lebesgue integrable are the same. If you want an example of a function which is absolutely integrable but not Riemann integrable, consider $f(x) = \begin{cases} e^{-x^2} & for \ x\in\mathbb{Q} \\ -e^{-x^2} & for \ x\notin\mathbb{Q} \end{cases}$. This function is not Riemann integrable (it's not continuous almost everywhere), but it's absolute value is just $e^{-x^2}$ which has integral $\sqrt\pi$.
A:
A function $f$ is Lebesgue integrable iff its integral exists and $|\int f| <\infty$. However, an equivalent definition is the one you have give above.
For $f$ with a defined (Lebesgue) integral by definition we have $\int f = \int f^+ - \int f^-$. If $f$ is in addition integrable it then $\int f^+ <\infty$ and $\int f^- < \infty$ so $\int f^+ + \int f^- = \int |f| < \infty$ so where I have used the fact that $|f| =f^+ + f^ - $. Thus $|f|$ is integrable as all non-negative functions have a defined integral.
Conversely $|f|$ is integrable then $f^+ \leq |f|$ and $f^- \leq |f|$ so $ \int f^+ < \int |f| < \infty $ and $ \int f^- < \int |f| < \infty $ which implies both the negative and positive parts of $f$ are finite and the integral is thus just the difference of two positive real numbers, so is finite. Thus $f$ is integrable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to snoop on "docker pull" requests from Docker for Mac while it's querying a local registry running on macOS?
(I'm using Docker for Mac Version 2.0.0.3 (31259) which has docker-engine 18.09.2.)
I'm trying to do this:
run a docker-registry process directly on my mac on port 8080 (it's not really docker-registry, but something that looks like registry, so it shouldn't matter) without HTTPS
run a mitmproxy on my mac directly on port 5000 (to intercept requests)
configure docker-engine to use mitmproxy so I can snoop on the requests
initiate a docker pull to my local registry so triggers some requests on my registry which I can monitor on mitmproxy.
Situation 1: no proxy set on docker-engine
So as I said earlier, I have a server that mimics the docker-registry v2 API running directly on my MacOS on port 8080. So I added host.docker.internal:8080 as an insecure registry:
Everything works (docker-engine can hit my local registry) fine if I don't set a proxy for docker-engine.
For example, I can do docker pull host.docker.internal:8080/busybox and the requests come to my proxy:
Situation 2: set proxy for docker-engine, pull image from docker hub
When I point the docker-engine to mitmproxy (host.docker.internal:5000) and do a docker pull library/mysql, that works fine too (I can see the requests made to index.docker.io)
Situation 3: set proxy for docker-engine, pull image from docker hub
So when I combine Situation #1+#2, which is pointing docker-engine to mitmproxy on my laptop as a proxy AND then trying to use docker pull host.docker.internal:8080/busybox which has worked before, it is failing:
Server connection to ('host.docker.internal', 8080) failed: Error connecting to "host.docker.internal": [Errno 8] nodename nor servname provided, or not known
The error my proxy sees is that it cannot find host.docker.internal. I can't tell if this is because mitmproxy is running on my Mac host OS (and not inside docker VM) and that's why it can't resolve the host.
I'm basically not able to use mitmproxy (on my Mac host OS) to snoop on docker-engine requests as well as run a registry (on my Mac host OS) at the same time.
I tried moving the registry into a container too and changed the hostname to gateway.docker.internal, but no luck there either.
Any ideas how to achieve this?
A:
Have you tried adding 127.0.0.1 host.docker.internal to your mac's /etc/hosts?
It seems to work for me.
The Docker VM resolves host.docker.internal:5000 to 192.168.65.2:5000 which connects it to the mitm proxy runnning on the Mac,
The mitm proxy doesn't know how to resolve host.docker.internal, hence the nodename nor servname provided, or not known error,
By adding the entry to /etc/hosts, you tell mitm to actually connect to the localhost to reach the registry.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.