diff --git "a/stackexchange/test.jsonl" "b/stackexchange/test.jsonl" new file mode 100644--- /dev/null +++ "b/stackexchange/test.jsonl" @@ -0,0 +1,3029 @@ +{"text": "Q:\n\nIs it possible to draw these charts with nvd3 or similar?\n\nIn a project I'm working on right now, which requires showing lots of charts, we've been using nvd3 javascript library quite successfully so far.\nOne of the new features we are adding now requires us to render this kind of chart:\n\nWhich is supposed to be a distribution chart (A + B + C + D = 100%). I don't know how to call that kind of chart.\nAs far as I know there's no way to draw that chart using nvd3, but I may be wrong.\nDoes anyone know a way to draw that kind of chart using nvd3 or any other library?\nThanks in advance.\nUPDATE: I've learned that this kind of chart is called \"rose chart\", \"polar area chart\" or \"coxcomb chart\".\n\nA:\n\nHere is a few samples similar to you requirement that might help get and idea. It uses the d3.js framework\n\nD3 Pie charts with grid lines\nCreating a Polar Area Diagram (Radial Bar Chart)\nSmooth Transitioning of Polar Area Diagram\n\nAnd here's a The Big List of D3.js Examples\nHope it helps\n\n"} +{"text": "Q:\n\nHow can padding be disambiguated from data, when encrypting using a block cipher?\n\nHow can padding be disambiguated from data, when encrypting using a block cipher?\n\nI'm by no means an expert in cryptography, but rather a programmer with a keen interest.\nSuppose, I've X bytes of data, message M, that I want to encrypt using an N-byte block cipher, where N >> X.\nHow can M be padded using N-X bytes of padding O, such that there would be no ambiguity between decrypting the padded message M\u00b4 and the (concatenated) message M|O?\nHow is this done in practice? Normally, when encrypting using a block cipher, I don't see a header being output describing the original length of the message M?\n\nA:\n\nThe usual padding for block ciphers (\"PKCS#7 padding\") is not a sequence of zeroes, but a sequence of P = N - (X % N) bytes each with value P.\nIf the message is a multiple of the block size, then a full block of padding is added (where each byte value is the block size).\nFor example, is the message is 15-byte long and the block size is 16 bytes, than one byte of padding will be added, and the value of the byte is 1. If the message is 14-byte long, two bytes with value 2 will be added. If the message is 16-byte long, sixteen bytes with value 16 will be added.\nWith these rules, the padding is unambiguous.\n\n"} +{"text": "Q:\n\nFeasability of Angular2 in Salesforce (through VF page)\n\nI've used Angular 1.x in Salesforce with quite a bit of success, but I was wondering if anyone has been able to work with Angular2. \nI was able to get a very simple hello world to load, but only if I don't include the SF header (otherwise there seem to be script name-spacing conflicts).\nI still don't know much about the framework in general, but it seems like there are a lot more dependancies (which may be an issue).\nJust want to know if anyone out there has actually used Angular 2 in a real project and if so: \n\nwhat does the basic configuration looks? (structure, dependancies, VF\nsetup, etc) \nwhat issues/concerns/challenges should be considered.\n\nA:\n\nIf you're still interested in creating an Angular 2 app on the Salesforce platform I may have a solution for you. I myself love Angular 2 and everything it brings to the table. My company also works exclusively on Salesforce, so I wanted to figure out a way to marry the two.\nWhat I ended up doing was create a boilerplate to make it easier to get started with Angular 2 on Salesforce. The boilerplate itself is available on Github at https://github.com/iDev0urer/salesforce-angular2-boilerplate and allows you to develop your application locally using the REST and SOAP API's to manipulate data. It also provides an easy way to deploy your app to Salesforce using gulp deploy.\nPlease check it out and give me feedback!\n\n"} +{"text": "Q:\n\nHow can I find the word starting at a specific character position and not word postion in a string?\n\nStr=\"I love chocolate pudding\"\npos=7\ndef getWordatPos(pos):\n xxx\n\nI need to return the word at the pos 7 which is chocolate. Is there anyway to do that? I know it is easy if chocolate is at index 2 but I need it at the character position.\n\nA:\n\nYou can try.\nStr=\"I love chocolate pudding\"\npos=7\n\nans=Str[pos:].split()[0]\n\nOutput\n\"chocolate\"\n\nStr[pos:] return 'chocolate pudding', Then I split them using split which return ['chocolate','pudding'] and I extracted 1st-word using indexing.\nIf pos=8 the output would be 'hocolate'.\n\n"} +{"text": "Q:\n\nPythagorean Triple finder\n\nWould like some feedback on a code style exercise motivated by this PythagTriple algorihtm. I started with the Rosetta Code - \"efficient C\" solution (not the naive one) and refactored it heavily into modern C++17. \nIt doesn't quite match their \"Task spec\". That that was not the focus. However, it could very easily be adopted to do so - just a few changes in main().Performance appears very similar to the C code I started with and the generated ASM seems reasonable. \nBut the main focus here is style, ease of readability, maintenance and correctness. \nSpecific feedback points I am looking for:\n\nUse of the lambda to process each triple\nWay of constraining the template to prevent unsuitable lambda's being passed. (C++20 concepts needed to do it cleanly?)\nUse of initialisers for static data. Also is there a way to get away from the {{ .. {{ .. {},{},{} .. }} .. }} craziness? 4 extra opening and closing braces. \nUse of specific type for vec3 and a using alias for trans\nBody of the transform() function. Is there a map() ... splat way? \nGeneral function signatures / use of const, constexpr, attributes etc\nUse of \"by value\" vs \"by ref\" semantics for triples / tranforms etc. There are some \"arguably redundant\" const T&s in there which were just as fast as \"by value\" (probably copy elided). \nMore algorithmic question: The algorithm as implemented is constrained by max_perimeter and due to recursive DFS flow and the matrix transforms the triples come out in a (subjectively) \"weird order\". Several other constraints and orderings are conceivably possible. One idea is to implement several alternative .find_XX() methods to do that. \n\nEDIT: There is updated code in a separate answer below, integrating the feedback. \n#include \n#include \n\nnamespace pythag {\n\nclass triple {\n public:\n const long _a;\n const long _b;\n const long _c;\n\n template \n constexpr void find(long max_perim, F&& proc) {\n if (perimeter() > max_perim) return;\n proc(*this);\n for (auto& T : U) transform(T).find(max_perim, proc);\n }\n\n [[nodiscard]] constexpr long perimeter() const noexcept { return _a + _b + _c; }\n\n friend std::ostream& operator<<(std::ostream& stream, const triple t) noexcept {\n return stream << t._a << \", \" << t._b << \", \" << t._c;\n }\n\nprivate:\n struct vec3 { // a strong type to distinguish from triple\n const int _x;\n const int _y;\n const int _z;\n };\n\n using trans = std::array;\n\n [[nodiscard]] constexpr long dot(vec3 V) const noexcept {\n return V._x * _a + V._y * _b + V._z * _c;\n }\n\n [[nodiscard]] constexpr triple transform(const trans& T) const noexcept {\n return triple{dot(T[0]), dot(T[1]), dot(T[2])};\n }\n\n static constexpr auto U = std::array{{\n // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships\n // clang-format off\n {{{ 1, -2, 2}, // vec3 U[0][0]\n { 2, -1, 2}, // vec3 U[0][1]\n { 2, -2, 3}}}, // vec3 U[0][1]\n\n {{{ 1, 2, 2}, // vec3 U[1][0]\n { 2, 1, 2}, // vec3 U[1][1]\n { 2, 2, 3}}}, // vec3 U[1][2]\n\n {{{ -1, 2, 2}, // vec3 U[2][0]\n { -2, 1, 2}, // vec3 U[2][1]\n { -2, 2, 3}}}, // vec3 U[2][2]\n // clang-format on\n }};\n};\n\n} // namespace pythag\n\nint main() {\n // basic usage demo\n long sum_peri = 0;\n long count = 0;\n\n pythag::triple{3, 4, 5}.find(\n 100'000'000, // produces 7'023'027 \"primitive\" triples in <100ms on i7 2600\n // [](const auto& t) { std::cout << t << \"\\n\"; }); // print option. slow obviously\n [&sum_peri, &count](const auto& t) { sum_peri += t.perimeter(); ++count; });\n\n std::cout << count << \"\\n\"; // these 2 lines are just a way to prevent\n return (sum_peri ^ count) & 0xff; // entire programme being optimised away\n}\n\nA:\n\nHere are some comments on your revised code, many of which apply to your original code as well.\nfor (auto& T: U) transform(T).find(max_perim, proc);\n\nYou're using the names T and U to refer to things that are not template type parameters. In fact, U is a reference to a static data member of the enclosing class, whose only declaration appears many lines below this use. This is extremely surprising code. I might instead write\nfor (auto&& formula : this->child_formulas) {\n this->transform(formula).find(max_perim, proc);\n}\n\nNotice the use of braces around the loop body; the use of auto&&, Which Always Works; the use of this-> to clarify for the human reader what scope we're expecting to find these names in; and especially the descriptive name child_formulas for U. (child_formulas says what U is; this-> says whose it is. Both of those things were in question, in the old code.)\n\nclass triple : public std::array {\n\nDon't inherit from standard types. It's legal C++, but it's bad practice.\n\nIf you (or your project, or your company) didn\u2019t write class Foo, then class Foo should not be granted control over the API of your own class. And that\u2019s what you\u2019re doing when you inherit from a base class: you\u2019re granting that class control over your API.\n\nI like your original x, y, z data members much better.\n\ntemplate \nvoid find(long max_perim, F&& proc) {\n\nYou're passing proc by perfect-forwarding, but then when you use it, you're using it as a plain old lvalue. This is fine (in the wild-west anything-goes world of templates), but it doesn't express the meaning of proc quite as well as I'd like. proc is supposed to be a callback that gets called for each triple, right? Calling a callback doesn't modify the callback. So, we can and should require that proc be const-callable, and then we just write\ntemplate\nvoid find(int max_perim, const F& proc) {\n\n(Drive-by irrelevant style adjustments to save typing. long varies in size and is the same size as int on many platforms, so let's just use int until we're ready to step all the way up to a well-defined int64_t or __int128_t.)\nIf you really want to support non-const and/or rvalue-callable Fs, you can perfect-forward proc all over the place, but trust me, it's not worth it. (The std::forward(proc)s will clutter your code, and all you're doing is enabling your users to write confusing and unintuitive client code.)\nVice versa, re your question about concepts: You can constrain this template to SFINAE away in C++17 (or C++11) like this:\ntemplate>>\nvoid find(int max_perim, const F& proc) {\n\nThis is not much more boilerplate than the C++2a concepts version:\ntemplate requires std::is_invocable\nvoid find(int max_perim, const F& proc) {\n\nNotice that in C++2a you will also be able to write \"simply\"\nvoid find(int max_perim, const std::invocable auto& proc) {\n\nbut (A) this doesn't express exactly the same SFINAE-constraint as the other two, and (B) IMHO it looks more confusing and scary.\nBut should you constrain this function to SFINAE away when it's given a \"bad\" lambda type? IMHO, no, you shouldn't. There's no reason to SFINAE here. SFINAE is for when you need this version of find to drop out of the overload set so that some other more general version can pick up the call. That's not the situation that you have, here.\nCompare the error messages you get from (A) (or the C++2a Concepts version (A2))\ntemplate>>\nvoid find(int max_perim, const F& proc) {\n proc(*this);\n}\n\nthis->find(42, 7);\n\nversus (B)\ntemplate\nvoid find(int max_perim, const F& proc) {\n static_assert(std::is_invocable_v);\n proc(*this);\n}\n\nthis->find(42, 7);\n\nversus (C)\ntemplate\nvoid find(int max_perim, const F& proc) {\n proc(*this);\n}\n\nthis->find(42, 7);\n\nand see which version feels most \"user-friendly\" for the client programmer. (Remember that someone using find correctly will never see any of these error messages, so you should optimize to help the guy who doesn't know how to use it.)\n\n cnt_next_depth += U.size(); // always 3\n if (--cnt_this_depth == 0) {\n if (++depth > max_depth) return;\n cnt_this_depth = cnt_next_depth;\n cnt_next_depth = 0;\n }\n for (auto& T: U) q.push(t.transform(T));\n\nCode comments are usually a red flag, at least on CodeReview. ;) It seems that this += corresponds to the three calls to q.push below; i.e., your algorithm requires that cnt_next_depth exactly track q.size(). But you can't use q.size() because you are reusing q to store both the elements at the current level and the elements at the next level.\nIt would make more sense to use two different queues:\nstd::vector this_level = ...;\nstd::vector next_level;\nfor (int i=0; i < max_depth; ++i) {\n for (auto&& t : this_level) {\n proc(t);\n for (auto&& formula : child_formulas) {\n next_level.push_back(t.transform(formula));\n }\n }\n this_level = std::move(next_level);\n next_level.clear();\n}\n\nAs a bonus, it turns out that we don't even need them to be queues anymore; they can be plain old vectors, and we save a bunch of heap traffic.\n\nfriend std::ostream& operator<<(std::ostream& stream, const triple& t) noexcept {\n // Frustrating boiler plate. Any terse alternatives, that do it quickly and correctly?\n char comma[] = {'\\0', ' ', '\\0'}; // NOLINT\n for (auto d: t) {\n stream << comma << d;\n comma[0] = ',';\n }\n return stream;\n}\n\nNo good answer. The idiomatic way would be\nfriend std::ostream& operator<<(std::ostream& stream, const triple& t) {\n bool first = true;\n for (auto&& d : t) {\n if (!first) stream << \", \";\n stream << d;\n first = false;\n }\n return stream;\n}\n\nNotice that this function is not noexcept, because any of these stream operations might throw. (For example, if you're writing to a stringstream and it throws bad_alloc.)\nAlso, in real life I'd write for (int d : t) to indicate exactly what type of \"elements\" I expect to be getting out of a triple. I'm using auto&& here only because I saw your comment that you want to stick with \"Almost Always Auto\" style.\n\n triple transform(const trans& T) const noexcept {\n auto res = triple{};\n std::transform(T.begin(), T.end(), res.begin(), [this](vec3 V) {\n return std::inner_product(V.begin(), V.end(), this->begin(), 0L);\n });\n return res;\n }\n\nThis is interesting use of STL algorithms, but algorithms are really meant for operating on big anonymous ranges of data elements, not for constant-size situations like we have here. In order to use STL algorithms, you've been forced to anonymize your formulas into faceless data ranges:\n static constexpr auto U = std::array{{\n // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships\n {{{{{1, -2, 2}}, // vec3 U[0][0]\n {{2, -1, 2}}, // vec3 U[0][1]\n {{2, -2, 3}}}}}, // vec3 U[0][1]\n\n {{{{{1, 2, 2}}, // vec3 U[1][0]\n {{2, 1, 2}}, // vec3 U[1][1]\n {{2, 2, 3}}}}}, // vec3 U[1][2]\n\n {{{{{-1, 2, 2}}, // vec3 U[2][0]\n {{-2, 1, 2}}, // vec3 U[2][1]\n {{-2, 2, 3}}}}}, // vec3 U[2][2]\n }};\n\nCompare that code to a more \"code-driven\" version:\ntriple transform(const Formula& f) const noexcept {\n return f(x, y, z);\n}\n\nauto formulas[] = {\n +[](int x, int y, int z){ return triple{ x - 2*y + 2*z, 2*x - y + 2*z, 2*x - 2*y + 3*z}; },\n +[](int x, int y, int z){ return triple{ x + 2*y + 2*z, 2*x + y + 2*z, 2*x + 2*y + 3*z}; },\n +[](int x, int y, int z){ return triple{ -x + 2*y + 2*z, -2*x + y + 2*z, -2*x + 2*y + 3*z}; },\n};\n\nIn this version, trans is gone already, and t.transform(f) is hardly pulling its weight.\n\nif (perimeter() > max_perim) return;\n\nConsider what you'd do if you wanted to find all triples up to some maximum side length, or up to some maximum hypotenuse length. Does this approach generalize to\ntriple.find(callback_on_each_triple, stopping_condition);\n\n?\n\nA:\n\nUse of the lambda to process each triple\n\nSure, why not. Nothing wrong with using a lambda in main() here instead of writing a normal function.\n\nWay of constraining the template to prevent unsuitable lambda's being passed. (C++20 concepts needed to do it cleanly?)\n\nIf you could live with pythag::triple::find() not being constexpr, then you don't need C++20 for this at all. Just use std::function<> for the type of proc:\n#include \n...\nvoid find(long max_perim, std::function proc) {\n ...\n}\n\nUse of initialisers for static data. Also is there a way to get away from the {{ .. {{ .. {},{},{} .. }} .. }} craziness? 4 extra opening and closing braces.\n\nYes, by not using std::array<>, but just declaring a multidimensional, \"C-style\" array:\n static constexpr vec3 U[3][3] {\n {{ 1, -2, 2}, // vec3 U[0][0]\n { 2, -1, 2}, // vec3 U[0][1]\n { 2, -2, 3}}, // vec3 U[0][1]\n\n {{ 1, 2, 2}, // vec3 U[1][0]\n { 2, 1, 2}, // vec3 U[1][1]\n { 2, 2, 3}}, // vec3 U[1][2]\n\n {{ -1, 2, 2}, // vec3 U[2][0]\n { -2, 1, 2}, // vec3 U[2][1]\n { -2, 2, 3}}, // vec3 U[2][2]\n };\n\nYou need to change transform() as well:\n [[nodiscard]] constexpr triple transform(const vec3 T[3]) const noexcept {\n return triple{dot(T[0]), dot(T[1]), dot(T[2])};\n }\n\nUse of specific type for vec3 and a using alias for trans\n\nI think you could've made vec3 an array as well, either std::array<> (at the cost of even more braces) or just int[3]. Since you use trans in multiple places, it's good to have made an alias for it. But what's weird is that you write:\nstatic constexpr auto U = std::array{...};\n\nThe auto is totally unnecessary here, you could've written it simply as:\nstatic constexpr std::array U{...};\n\nBody of the transform() function. Is there a map() ... splat way?\n\nThere's std::inner_product which could replace dot(), and std::transform() could have replaced the body of transform(), if your triples and vectors were arrays. It would have looked like:\ntriple transform(const trans& T) const {\n triple result;\n return std::transform(T.begin(), T.end(), result.values.begin(),\n [this](vec3 V){\n return std::inner_product(V.begin(), V.end(), this->values.begin(), 0);}\n }\n );\n}\n\nInstead of const long _a, _b, _c you'd have to have something like std::array values to make it work.\n\nGeneral function signatures / use of const, constexpr, attributes etc\n\nDoes it really need to be constexpr? It is restricting you (you can't use std::function<> for find() for example), and I don't see any reason why you would ever need to know the number of Pythogorean triples up to some value at compile-time.\nOf course, marking things const, constexpr, [[nodiscard]] and so on where possible is a good thing. Keep doing that.\nI would however change the type of the components of vec3 to long, to match that of the triple itself. You could even think of making an alias for the value type, or make the whole class templated, so you can decide which value type to use.\n\nUse of \"by value\" vs \"by ref\" semantics for triples / tranforms etc. There are some \"arguably redundant\" const T&s in there which were just as fast as \"by value\" (probably copy elided).\n\nWith optimization enabled, any decent compiler will probably generate the same assembly code here, regardless of whether you pass by value or by const reference.\nYou even missed the possibility to make operator<<() take a const reference.\n\nMore algorithmic question: The algorithm as implemented is constrained by max_perimeter and due to recursive DFS flow and the matrix transforms the triples come out in a (subjectively) \"weird order\". Several other constraints and orderings are conceivably possible. One idea is to implement several alternative .find_XX() methods to do that.\n\nWhat algorithm is best depends on the application. Your recursive DFS algorithm is probably the most elegant one to implement, but apart from the weird output order, the main issue is that you can run out of stack space if the recursion goes too deep. So try to implement another algorithm that doesn't require recursive function calls.\n\n"} +{"text": "Q:\n\nEfficiently accumulate Sliding Window Percentage Changes of large dataset\n\nI have a few million datapoints, each with a time and a value. I'm interested in knowing all of the sliding windows, (ie, chunks of 4000 datapoints) where the range from high to low of the window exceeds a constant threshold.\nFor example:, assume a window of length 3, and a threshold where high - low > 3. Then the series: [10 12 14 13 10 11 16 14 17] would result in [0, 2, 4, 5] because those are the indexes where the 3 period window's high - low range exceeded the threshold.\nI have a window size of 4000 and a dataset size of millions.\nThe naive approach is to just calculate every possible window range, ie 1-4000, 2-4001, 3-4002, etc, and accumulate those sets that breached the threshold. This takes forever as you might imagine for large datasets.\nSo, the algorithm I think would be better is the following:\nCalculate the range of the first window (1-4000), and store the index of the high/low of the window range. Then, iterate to (2-4001, 3-4002) etc. Only update the high/low index if the NEW value on the far right of the window is higher/lower than the old cached value. \nNow, let's say the high/low indexes of the 1-4000 window is 333 and 666 respectively. I iterate and continue updating new highs/lows as I see them on the right, but as soon as the window is at 334-4333 (as soon as the cached high/low is outside of the current window) I recalculate the high/low for the current window (334-4333), cache, and continue iterating.\nMy question is:\n1.) Is there a mathematical formula for this that eliminates the need for an algorithm at all? I know there are formulas for weighted and exponential moving averages over a window period that don't require recalculation of the window.\n2.) Is my algorithm sensible? Accurate? Is there a way it could be greatly simplified or improved?\nThanks a lot.\n\nA:\n\nIf the data length is n and window size m, then here's an O(n log m) solution using sorted-maps.\n(defn freqs \n \"Like frequencies but uses a sorted map\"\n [coll]\n (reduce (fn [counts x] \n (assoc counts x (inc (get counts x 0)))) \n (sorted-map) coll))\n\n(defn rng\n \"Return max - min value of a sorted-map (log time)\"\n [smap]\n (- (ffirst (rseq smap)) (ffirst smap)))\n\n(defn slide-threshold [v w t] \n (loop [q (freqs (subvec v 0 w)), i 0, j (+ i w), a []] \n (if (= (count v) j) \n a \n (let [q* (merge-with + q {(v i) -1} {(v j) 1}) \n q* (if (zero? (q* (v i))) (dissoc q* (v i)) q*) \n a* (if (> (rng q) t) (conj a i) a)] \n (recur q* (inc i) (inc j) a*)))))\n\n(slide-threshold [10 12 14 13 10 11 16 14 17] 3 3)\n;=> [0 2 4 5]\n\n"} +{"text": "Q:\n\n\u041a\u0430\u043a \u0443\u0441\u043a\u043e\u0440\u0438\u0442\u044c \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435 \u043f\u043e ssh\n\n\u041f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435 \u0443\u0436\u0435 \u043f\u043e\u0441\u043b\u0435 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0438 \u043f\u0430\u0440\u043e\u043b\u0438 \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u0438\u0442 \u043e\u0447\u0435\u043d\u044c \u043c\u0435\u0434\u043b\u0435\u043d\u043d\u043e, \u043e\u043a\u043e\u043b\u043e 5-20 \u0441\u0435\u043a\u0443\u043d\u0434, \u0440\u0430\u043d\u0435\u0435 \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0430\u043b\u0441\u044f \u043a \u0445\u043e\u0441\u0442\u0443 \u0437\u0430 1-2 \u0441\u0435\u043a\u0443\u043d\u0434\u044b, \u0447\u0442\u043e \u044d\u0442\u043e \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c, \u043a\u0443\u0434\u0430 \u043a\u043e\u043f\u0430\u0442\u044c?\n\nA:\n\nUsePAM no, UseDNS no\u0415\u0441\u043b\u0438 \u0434\u0438\u0440\u0435\u043a\u0442\u0438\u0432\u0430 UsePAM \u0432\u043a\u043b\u044e\u0447\u0435\u043d\u0430, \u0442\u043e \u0437\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c sshd \u043c\u043e\u0436\u043d\u043e \u0431\u0443\u0434\u0435\u0442 \u0442\u043e\u043b\u044c\u043a\u043e \u043e\u0442 \u0438\u043c\u0435\u043d\u0438 root.UseDNS - \u043f\u044b\u0442\u0430\u0435\u0442\u0441\u044f \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u0442\u044c ip-\u0430\u0434\u0440\u0435\u0441 \u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0430\u044e\u0449\u0435\u0433\u043e \u043a\u043b\u0438\u0435\u043d\u0442\u0430 \u0432 \u043e\u0431\u0440\u0430\u0442\u043d\u043e\u0435 \u0438\u043c\u044f.195.208.238.155 - 155.238.208.195.IN-ADDR.ARPA\u0427\u0430\u0449\u0435 \u0432\u0441\u0435\u0433\u043e, \u0438\u043c\u0435\u043d\u043d\u043e \u044d\u0442\u043e\u0442 \u043f\u0440\u043e\u0446\u0435\u0441\u0441 \u0434\u0435\u043b\u0430\u0435\u0442 \u043f\u0430\u0443\u0437\u0443.\u0414\u043e\u0431\u0430\u0432\u0438\u043b \u0447\u0435\u0440\u0435\u0437 4 \u0447\u0430\u0441\u0430.GSSAPIAuthentication no\u0412\u043e\u0437\u043d\u0438\u043a\u043b\u0430 \u0441\u0438\u0442\u0443\u0430\u0446\u0438\u044f, \u043a\u0430\u043a \u0443 \u0442\u0435\u0431\u044f \u0441\u0435\u0433\u043e\u0434\u043d\u044f.\u041f\u043e\u043c\u043e\u0433\u043b\u043e \u0442\u043e\u043b\u044c\u043a\u043e \u043e\u0442\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435 \u044d\u0442\u043e\u0439 \u043e\u043f\u0446\u0438\u0438.http://alexm.here.ru/cvs-ru/html_node/cvs-ru_32.html - \u043d\u0430 \u0440\u0443\u0441\u0441\u043a\u043e\u043c \u043e \u043d\u0435\u0439. \u041c\u0430\u043b\u043e, \u043d\u0435\u043f\u043e\u043d\u044f\u0442\u043d\u043e.http://www.slac.stanford.edu/comp/unix/sshGSSAPI.html - \u0437\u0434\u0435\u0441\u044c \u0431\u043e\u043b\u044c\u0448\u0435. \u0410\u043d\u0433\u043b \u043d\u0435 \u0448\u0430\u0440\u044e.\n\n"} +{"text": "Q:\n\nCase Looping in PHP\n\nI want to use a loop to iterate through my array, calling my function to print out all of these messages. I have to somehow keep track - I'm using PHP code.\nThis my code :\n\n\nmy output should be:\n10000\n9000\n7500\n7000\n5000\n1000\n\nA:\n\nIs this what you want?\n\" ;\n}\n?>\n\n"} +{"text": "Q:\n\nHaskell: Beginner syntax question\n\na very simple question from a Haskell learner. I am working through Yet Another Haskell Tutorial and I am stuck on a simple syntax practice. The code given below: When I copy and paste it (from pdf) and then adjust the indentation it works fine, but when I type it out into an editor (in my case Notepad++) then it throws the following error:\nGuess.hs:8:9: parse error on input \u00b4hSetBuffering\u00b4\n\nI made sure that I did not mix tabs and whitespaces (4 whitespaces) and I did not find a typo in the book. I am sure it is a very simple mistake so thanks for any input.\nNebelhom\nHere is the code:\nmodule Main\n where\n\nimport IO\nimport Random\n\nmain = do\n hSetBuffering stdin LineBuffering\n num <- randomRIO (1::Int, 100)\n putStrLn \"I'm thinking of a number between 1 and 100\"\n doGuessing num\n\ndoGuessing num = do\n putStrLn \"Enter your guess:\"\n guess <- getLine\n let guessNum = read guess\n if guessNum < num\n then do putStrLn \"Too low!\"\n doGuessing num\n else if read guess > num\n then do putStrLn \"Too high!\"\n doGuessing num\n else do putStrLn \"You Win!\"\n\nA:\n\nThere's no syntax error that I can see, or reproduce:\n$ ghci A.hs\nGHCi, version 7.0.3: http://www.haskell.org/ghc/ :? for help\nLoading package ghc-prim ... linking ... done.\nLoading package integer-gmp ... linking ... done.\nLoading package base ... linking ... done.\nLoading package ffi-1.0 ... linking ... done.\n[1 of 1] Compiling Main ( A.hs, interpreted )\nOk, modules loaded: Main.\n\nwhich means it is probably tabs. Did you insert a tab somewhere? And then use 4 spaces for indenting? Tabs are in general a bad idea in Haskell, as they lead to unintentional, and unintelligible, syntax errors.\n\n"} +{"text": "Q:\n\nAbout the system in vc\n\nI run below code in vc.\n system(\"@echo off\");\n system(\"set a=3\");\n system(\"echo %a%\");\n system(\"pause\");\n\nbut it display as '%a%', but I require display as '3'.\nHow Can I make it? \nThanks very much for your help.\n\nA:\n\nCreate the \"tmp.bat\" file:\n@echo off\nset a=3\necho %a%\npause\n\nand then call the\nsystem(\"cmd /c tmp.bat\")\n\nThe thing is that system() call creates a \"clean\" environment where the \"a\" variable has not been set (in the \"echo %a%\" call).\nTo convert the sequence of commands into something \"executable\" one might use some special tool, not the \"VC\".\nLook for http://www.autoitscript.com/site/autoit/ and similar tools.\n\n"} +{"text": "Q:\n\nHow to rename Ubuntu One folders? Locked by syncdaemon?\n\ntl;dr: Does Ubuntu One detect renamed synced folders?\nI'm trying to rename a large synced folder ('Sync locally' checked) outside of Ubuntu One, but still inside the home folder on Windows. Attempting to do so results in an error message:\nCannot rename foldernamehere: It is being used by another person or program.\nClose any programs that might be using the file and try again.\n\nQuitting ubuntuone-syncdaemon and renaming results in Ubuntu One not finding the synced folder (folder in ubuntuone-control-panel-qt becomes grayed out). Ticking 'Sync locally' again causes Ubuntu One to begin downloading the synced folder with it's old name and ignoring the renamed folder.\nIs there any way to locally rename a synced folder short of reuploading the entire folder under a new name?\nThanks for the help!\n\nA:\n\nYou would have to:\n1) Stop syncing the folder to your computer\n2) Rename it\nWindows: quit ubuntuone-syncdaemon first by running the following command in Program Files\\ubuntuone\\dist: u1sdtool -q\nUbuntu: open system monitor, click the \"Processes\" tap, then perform killing the ubuntuone-syncdaemon.\nOn Ubuntu one app: un-tick the sync locally from the folder you want to rename.\n3) From the ubuntu one site, remove the folder\n4) Start syncing the new folder\nKeep in mind that any other devices where this folder was synced will not rename it, and will stop syncing it as well.\nThe reupload renaming file check should be quick (15-20 min for 740MB), because the server already has a copy of your files.\n\n"} +{"text": "Q:\n\nHow to calculate $ \\frac{1}{\\sum_{n=0}^{\\infty} \\frac{3^n}{n!}}$\n\nI am solving for the stationary distribution whose state space is $S = ${$0, 1, 2,....$}. I need to calculate $ \\frac{1}{\\sum_{n=0}^{\\infty} \\frac{3^n}{n!}}$ for $ \u03c0(0)$.\nThen answer is $e^{-3}$, but I don't know how to get it. \n\nA:\n\nNote that\n$$\ne^x=\\sum_{n=0}^\\infty\\frac{x^n}{n!}.\n$$\n\n"} +{"text": "Q:\n\nFacebook pending authorization exception while updating status from android\n\nHi I have to publish my status from an activity that is hosting a fragment and on using application for first time and after logging into application I get an exception when I try to update the status . I get this exception.\n\"Session: an attempt was made to request new permissions for a session that has a pending request.\"\nHere is my code for Fragment\n import java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\n\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport android.app.Activity;\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.provider.Settings.Secure;\nimport android.support.v4.app.Fragment;\nimport android.util.Log;\nimport android.view.Gravity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.Toast;\n\nimport com.carfrenzy.activities.FeedsActivity;\nimport com.carfrenzy.activities.SelectCarActivity;\nimport com.carfrenzy.activities.TourActivity;\nimport com.carfrenzy.activities.UserProfileActivity;\nimport com.carfrenzy.app.R;\nimport com.carfrenzy.beans.CFConstants;\nimport com.carfrenzy.beans.UserProfileInfo;\nimport com.carfrenzy.ui.ProgressBarDialog;\nimport com.carfrenzy.webservices.WebHttpServicesManager;\nimport com.facebook.FacebookRequestError;\nimport com.facebook.HttpMethod;\nimport com.facebook.Request;\nimport com.facebook.RequestAsyncTask;\nimport com.facebook.Response;\nimport com.facebook.Session;\nimport com.facebook.SessionState;\nimport com.facebook.UiLifecycleHelper;\nimport com.facebook.widget.LoginButton;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParser;\nimport com.turbomanage.httpclient.AsyncCallback;\nimport com.turbomanage.httpclient.HttpResponse;\n\npublic class MainFragment extends Fragment\n{\n private UiLifecycleHelper uiHelper;\n\n String accessToken = \"\";\n SharedPreferences mprefs;\n String mTutorial = \"\";\n static Context context;\n static Context mcontext;\n\n Button login;\n EditText etemail, etpass;\n\n private static final List PERMISSIONS = Arrays.asList(\"publish_actions\");\n private static final List EMAIL_PERMISSIONS = Arrays.asList(\"email\");\n private static final String PENDING_PUBLISH_KEY = \"pendingPublishReauthorization\";\n private static boolean pendingPublishReauthorization = false;\n final String pushNotificationToken = \"\";\n String android_id = \"\";\n String pushToken = \"\";\n private static final String TAG = \"MainFragment\";\n ImageView iemail;\n\n Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, Arrays.asList(\"email\"));\n\n LoginButton authButton = null;\n\n //private ProgressDialog mProgressDialog = null;\n\n Handler handler;\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)\n {\n context = getActivity().getBaseContext();\n mcontext = getActivity();\n\n View view = inflater.inflate(R.layout.startup, container, false);\n etemail = (EditText) view.findViewById(R.id.etUser);\n etpass = (EditText) view.findViewById(R.id.etPass);\n login = (Button) view.findViewById(R.id.bLoginNew);\n login.setEnabled(true);\n authButton = (LoginButton) view.findViewById(R.id.authButton);\n authButton.setBackgroundResource(R.drawable.logo_facebook);\n authButton.setFragment(this);\n authButton.setReadPermissions(Arrays.asList(\"email\"));\n\n View viewp = inflater.inflate(R.layout.user_mycar_home, container, false);\n /***************/\n android_id = Secure.getString(getActivity().getContentResolver(), Secure.ANDROID_ID);\n\n login.setOnClickListener(new View.OnClickListener()\n {\n\n @Override\n public void onClick(View v)\n {\n if (etemail.getText().toString().equals(\"\") || etpass.getText().toString().equals(\"\"))\n {\n Toast.makeText(context, \"Please enter your email address and password to login\", Toast.LENGTH_SHORT).show();\n }\n else if (etpass.getText().toString().length() < 6)\n {\n Toast.makeText(context, \"Password is invalid. It should be atleast 6 characters\", Toast.LENGTH_SHORT).show();\n }\n else if (etpass.getText().toString().length() > 5)\n {\n //pushToken=getRegistrationId(context);\n //Log.i(\"Audit\", pushToken);\n\n //mProgressDialog = ProgressDialog.show(getActivity(),\n // \"Cruising...\",\"\", true);\n //mProgressDialog.setCancelable(true);\n\n final ProgressBarDialog dialogBar = new ProgressBarDialog(getActivity(), \"Cruising...\");\n //\n dialogBar.show();\n\n pushToken= mprefs.getString(\"PROPERTY_REG_ID\", \"\");\n Log.i(\"Audit\", pushToken);\n new WebHttpServicesManager(context).signInWithEmail(etemail.getText().toString(), etpass.getText().toString(), android_id.toString(), pushToken.toString(), new AsyncCallback()\n {\n @Override\n public void onComplete(HttpResponse httpResponse)\n {\n dialogBar.dismiss();\n if (httpResponse != null && httpResponse.getStatus() == 200)\n {\n\n //mProgressDialog.dismiss();\n String responseString = WebHttpServicesManager.decompress(httpResponse.getBody());\n\n JSONObject jsonResponse=null;\n JSONObject status;\n\n JsonParser parser = new JsonParser();\n JsonObject o = (JsonObject)parser.parse(responseString);\n try\n {\n if( o!=null && o.get(\"status\").getAsString().equals(\"1\"))\n {\n jsonResponse = new JSONObject(responseString);\n JSONObject response = jsonResponse.getJSONObject(\"response\");\n String active1 = response.getString(\"activeSalt\");\n mprefs.edit().putString(\"activeSalt\", active1).commit();\n Boolean tour = mprefs.getBoolean(TourActivity.SharedPrefKey, false);\n\n if (tour)\n {\n // Intent intent = new\n // Intent(context,TourActivity.class);\n // startActivity(intent);\n // tourDon();\n }\n }\n else\n {\n jsonResponse = new JSONObject(responseString);\n JSONObject response = jsonResponse.getJSONObject(\"response\");\n Toast.makeText(context, \"Error:\"+ response.toString(), Toast.LENGTH_SHORT).show();\n }\n\n }\n catch (JSONException e)\n {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n String isTutorial = mprefs.getString(\"isTutorial\", \"\");\n\n // if(isTutorial.equalsIgnoreCase(\"1\"))\n // {\n // Intent in = new Intent(context, SelectCarActivity.class);\n // in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n // login.setEnabled(false);\n // startActivity(in);\n // getActivity().finish();\n // }\n // else\n // {\n Intent in = new Intent(context, UserProfileActivity.class);\n in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n login.setEnabled(false);\n startActivity(in);\n // Log.i(\"SignIn\", \"Success\");\n getActivity().finish();\n return;\n //}\n }\n else if (httpResponse !=null && httpResponse.getStatus()==401)\n {\n // AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(\"Oops\").setMessage(\"Cannot connect to server please Try again with valid email and password!\").setNeutralButton(\"OK\", null);\n // AlertDialog alert1 = alert.create();\n // alert1.show();\n String responseString = WebHttpServicesManager.decompress(httpResponse.getBody());\n //JSONObject jsonResponse=null;\n\n JsonParser parser = new JsonParser();\n JsonObject o = (JsonObject)parser.parse(responseString);\n String message = o.get(\"response\").getAsString();\n AlertDialog.Builder alert = new AlertDialog.Builder(mcontext).setTitle(\"Error\").setMessage(\" \" +message ).setNeutralButton(\"OK\", null);\n alert.show();\n }\n else\n {\n AlertDialog.Builder alert = new AlertDialog.Builder(mcontext).setTitle(\"Oops\").setMessage(\"Cannot connect to server. Please Try again!\" ).setNeutralButton(\"OK\", null);\n alert.show();\n }\n }\n\n @Override\n public void onError(Exception e, int errorCode)\n {\n super.onError(e, errorCode);\n //mProgressDialog.dismiss();\n dialogBar.dismiss();\n if (errorCode == CFConstants.INTERNET_NOT_AVAILABLE)\n {\n // AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(\"No Internet Connectivity\").setMessage(\"Please Check Your Internet Connection and Try again!\").setNeutralButton(\"OK\", null);\n // AlertDialog alert1 = alert.create();\n // alert1.show();\n Toast toast = Toast.makeText(mcontext, \"Please Check Your Internet Connection and Try again!\", Toast.LENGTH_SHORT);\n toast.setGravity(Gravity.CENTER, 0, 0);\n toast.show();\n }\n Log.i(\"SignIn\", \"Error\");\n }\n\n @Override\n public void onComplete(org.apache.http.HttpResponse httpResponse)\n {\n // TODO Auto-generated method stub\n //mProgressDialog.dismiss();\n dialogBar.dismiss();\n }\n });\n }\n }\n });\n\n if (savedInstanceState != null) {\n pendingPublishReauthorization =\n savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);\n }\n\n return view;\n }\n\n private void onSessionStateChange(Session session, SessionState state, Exception exception)\n {\n if (pendingPublishReauthorization &&\n state.equals(SessionState.OPENED_TOKEN_UPDATED)) {\n pendingPublishReauthorization = false;\n publishStory();\n }\n\n if (state.isOpened())\n {\n if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED))\n {\n pendingPublishReauthorization = false;\n publishStory();\n }\n\n else if (!pendingPublishReauthorization)\n {\n try\n {\n Log.i(\"Audit\", \"Logged in...\");\n Log.i(\"fb2\", accessToken);\n\n // Check for email permissions\n List permissions = session.getPermissions();\n if (!isSubsetOf(EMAIL_PERMISSIONS, permissions))\n {\n session.requestNewReadPermissions(newPermissionsRequest);\n\n return;\n }\n\n accessToken = session.getAccessToken();\n UserProfileInfo.setAccessToken(accessToken);\n pushToken= mprefs.getString(\"PROPERTY_REG_ID\", \"\");\n facebookLogin(accessToken, pushToken);\n }\n\n catch(Exception e )\n {\n e.printStackTrace();\n }\n }\n }\n else if (state.isClosed())\n {\n Toast.makeText(context, \"Error: Can't Login through Facebook! Please try again later!\", Toast.LENGTH_SHORT).show();\n }\n\n }\n\n private Session.StatusCallback callback = new Session.StatusCallback()\n {\n @Override\n public void call(Session session, SessionState state, Exception exception)\n {\n onSessionStateChange(session, state, exception);\n}\n};\n\n@Override\npublic void onCreate(Bundle savedInstanceState)\n{\nsuper.onCreate(savedInstanceState);\nuiHelper = new UiLifecycleHelper(getActivity(), callback);\nuiHelper.onCreate(savedInstanceState);\nmprefs = getActivity().getSharedPreferences(\"com.carfrenzy.app\", getActivity().MODE_PRIVATE);\nandroid_id = Secure.getString(getActivity().getContentResolver(), Secure.ANDROID_ID);\npushToken= mprefs.getString(\"PROPERTY_REG_ID\", \"\");\nBoolean firstTour = mprefs.getBoolean(TourActivity.firstTimTour, false);\n}\n\n@Override\npublic void onResume()\n{\nsuper.onResume();\n// For scenarios where the main activity is launched and user\n// session is not null, the session state change notification\n// may not be triggered. Trigger it if it's open/closed.\nSession session = Session.getActiveSession();\nif (session != null && (session.isOpened() || session.isClosed()))\n{\nonSessionStateChange(session, session.getState(), null);\n}\n\nuiHelper.onResume();\n}\n\n@Override\npublic void onActivityResult(int requestCode, int resultCode, Intent data)\n{\nsuper.onActivityResult(requestCode, resultCode, data);\nLog.v(\"in activity result of :::\", \"Main fragment\");\nuiHelper.onActivityResult(requestCode, resultCode, data);\n//Session.getActiveSession().onActivityResult((Activity) context, requestCode, resultCode, data);\n\nLog.i(\"Audit\", \"I am here in Result of fragment\");\n}\n\n@Override\npublic void onPause()\n{\nsuper.onPause();\nuiHelper.onPause();\n}\n\n@Override\npublic void onDestroy()\n{\nsuper.onDestroy();\nuiHelper.onDestroy();\n}\n\n@Override\npublic void onSaveInstanceState(Bundle outState) {\nsuper.onSaveInstanceState(outState);\noutState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);\nuiHelper.onSaveInstanceState(outState);\n}\n\nprivate void facebookLogin(final String accessToken, final String pushToken)\n{\nString mAccessToken = UserProfileInfo.getAccessToken();\nLog.i(\"Audit\", mAccessToken);\n// final ProgressBarDialog dialogBar = new ProgressBarDialog(context, \"Cruising...\");\n// dialogBar.show();\nToast toast = Toast.makeText(mcontext, \"Fetching data from Facebook Servers! This may take few seconds!\", Toast.LENGTH_SHORT);\ntoast.setGravity(Gravity.CENTER, 0, 0);\ntoast.show();\n//Toast.makeText(context, \"Fetching data from Facebook Servers! This may take few seconds!\", Toast.LENGTH_SHORT).show();\nnew WebHttpServicesManager(getActivity()).signInFacebook(\"1\", accessToken.toString(), android_id.toString(), pushToken.toString(), new AsyncCallback()\n{\npublic void onComplete(HttpResponse httpResponse)\n{\n// dialogBar.dismiss();\n\nif (httpResponse != null && httpResponse.getStatus() == 200)\n{\nString responseString = WebHttpServicesManager.decompress(httpResponse.getBody());\nLog.e(\"SignUp\", \" Server data : \" + httpResponse.getBodyAsString());\nJSONObject jsonResponse = null;\nJSONObject status;\n\nJsonParser parser = new JsonParser();\nJsonObject o = (JsonObject) parser.parse(responseString);\ntry\n{\nif (o != null && o.get(\"status\").getAsString().equals(\"1\"))\n{\njsonResponse = new JSONObject(responseString);\nJSONObject response = jsonResponse.getJSONObject(\"response\");\nString active1 = response.getString(\"activeSalt\");\nmprefs.edit().putString(\"activeSalt\", active1).commit();\nmTutorial = response.getString(\"userTutorial\");\nmprefs.edit().putString(\"userTutorial\", mTutorial);\nString suggestedTour = response.getString(\"isSuggestedTour\");\nmprefs.edit().putString(\"suggestedTour\", suggestedTour);\n\n}\nelse\n{\njsonResponse = new JSONObject(responseString);\nJSONObject response = jsonResponse.getJSONObject(\"response\");\nToast.makeText(context, \"Error:\" + response.toString(), Toast.LENGTH_SHORT).show();\n\n}\n}\ncatch (JSONException e)\n{\ne.printStackTrace();\n}\n\nif (mTutorial.toString().equals(\"1\"))\n{\nIntent intent = new Intent(getActivity(), SelectCarActivity.class);\nintent.putExtra(\"fbAccessToken\", accessToken);\ngetActivity().startActivity(intent);\nLog.i(\"SignInFacebook\", \"Success\");\n}\nelse if (mTutorial.toString().equals(\"0\"))\n{\nIntent intent = new Intent(getActivity(), FeedsActivity.class);\nintent.putExtra(\"fbAccessToken\", accessToken);\ngetActivity().startActivity(intent);\n}\n}\nelse if (httpResponse != null && httpResponse.getStatus() == 401)\n{\n//new AlertDialog.Builder(context).setTitle(\"Cannot connect to server\").setMessage(\"We cannot connect to server! Please try again Later!\").setNeutralButton(\"OK\", null).show();\n// dialogBar.dismiss();\nToast.makeText(context, \"We cannot connect to server! Please try again Later!\", Toast.LENGTH_SHORT).show();\n}\n}\n\n@Override\npublic void onError(Exception e, int errorCode)\n{\nsuper.onError(e, errorCode);\n// dialogBar.dismiss();\nif (errorCode == CFConstants.INTERNET_NOT_AVAILABLE)\n{\n//new AlertDialog.Builder(context).setTitle(\"No Internet Connectivity\").setMessage(\"Please Check Your Internet Connection and Try again!\").setNeutralButton(\"OK\", null).show();\n// dialogBar.dismiss();\nToast.makeText(context, \"Please Check Your Internet Connection and Try again!\", Toast.LENGTH_LONG).show();\n}\nLog.i(\"SignUp\", \"error\");\n}\n\n@Override\npublic void onComplete(org.apache.http.HttpResponse httpResponse)\n{\n// dialogBar.dismiss();\n}\n});\n}\n\npublic static void publishStory()\n{\nSession session = Session.getActiveSession();\n\nif (session != null)\n{\n// Check for publish permissions\nList permissions = session.getPermissions();\nif (!isSubsetOf(PERMISSIONS, permissions))\n{\npendingPublishReauthorization = true;\nSession.NewPermissionsRequest newPermissionsRequest = new Session\n.NewPermissionsRequest((Activity) mcontext, PERMISSIONS);\nsession.requestNewPublishPermissions(newPermissionsRequest);\nreturn;\n}\nfinal ProgressBarDialog dialogBar = new ProgressBarDialog(mcontext, \"Cruising...\");\n//\ndialogBar.show();\nBundle postParams = new Bundle();\npostParams.putString(\"name\", \"Motoqlik\");\npostParams.putString(\"caption\", \"You can now Look out for road users via motoqlik\");\npostParams.putString(\"description\", \"A smart new way to look out for road users! Look out for one another on roads and car park!\");\npostParams.putString(\"link\", \"http://www.motoqlik.com/\");\npostParams.putString(\"picture\", \"https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc3/c57.33.414.414/s160x160/972186_590988330944636_1055194609_n.png\");\n\nRequest.Callback callback = new Request.Callback()\n{\npublic void onCompleted(Response response)\n{\ndialogBar.dismiss();\nif (response != null)\n{\nJSONObject graphResponse = response.getGraphObject().getInnerJSONObject();\nString postId = null;\ntry\n{\npostId = graphResponse.getString(\"id\");\nLog.i(TAG, \"postId \" + postId);\nToast.makeText(context, \"Shared on your profile\"+ postId, Toast.LENGTH_LONG).show();\n// AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(\"Success\").setMessage(\"Shared on your wall\" + postId).setNeutralButton(\"OK\", null);\n//alert.show();\n}\ncatch (JSONException e)\n{\nLog.i(TAG, \"JSON error \" + e.getMessage());\n}\nFacebookRequestError error = response.getError();\nif (error != null)\n{\nToast.makeText((Activity) context, error.getErrorMessage(), Toast.LENGTH_SHORT).show();\n//AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(\"Sharing Error\").setMessage(\"Cannot connect to facebook Servers!\" + error.getErrorMessage()).setNeutralButton(\"OK\", null);\n//alert.show();\n}\nelse\n{\n}\n}\nelse\n{\nToast.makeText(context, \"Could not Connect to Facebook!\", Toast.LENGTH_LONG).show();\n// AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(\"Sharing Error\").setMessage(\"Cannot connect to facebook Servers!\").setNeutralButton(\"OK\", null);\n//alert.show();\n}\n}\n};\n\nRequest request = new Request(session, \"me/feed\", postParams, HttpMethod.POST, callback);\n\nRequestAsyncTask task = new RequestAsyncTask(request);\ntask.execute();\n}\n\n}\n\nprivate static boolean isSubsetOf(Collection subset, Collection superset)\n{\nfor (String string : subset)\n{\nif (!superset.contains(string))\n{\nreturn false;\n}\n}\nreturn true;\n}\n\n}\n\nThe publishStory() method is the actual method for post on my wall. This method is being called from host activity. And The UILifeCycleHelper handling is done in onActivityResult of fragment, but the fragment's onActivityResult is not being called after publish story. This only happens when user uses the application for first time and tries to publish to facebook. \nIf he logout and login again , then he can post successfully and exception is not raised. \nAny kind of help would be appreciated , \nThanks and Regards,\nMunazza\n\nA:\n\nHey use this library instead to do facebook authorization. \nhttps://github.com/sromku/android-simple-facebook\n\n"} +{"text": "Q:\n\nHow to return longest sequence of chars in a string in java?\n\nFollowing is what I end up doing but i did not find right answer.\nExample - If I have the sequence \"hellloo\" the output will be \"lll\". Please tell me what is wrong?\npublic class LongestSequenceOfChar {\n static String testcase1=\"hellloo\";\n\n public static void main(String[] args) {\n LongestSequenceOfChar test = new LongestSequenceOfChar();\n String result = test.longestSequenceOfChar(testcase1);\n System.out.println(result);\n }\n public String longestSequenceOfChar(String str){\n String result=\"\";\n for(int i=0;i.. Integer-->count\n2. Start from the beginning of your String.. For each character, check if it is already present in the hashmap\n a. If Yes, just increment the count\n b. if No, then add the character as key to the Map and set its count value to 1. \n\nA:\n\nIf there are three 'l' you only add two and in the next step are two 'l' and you add one of them. Then the same with the two 'o' where you are adding one. You only have to clear the result string when you step to the next letter and before save the result in another variable, but only if its is longer!\npublic String longestSequenceOfChar(String str){\n String interimresult=\"\";\n String result=\"\"; //final result\n for(int i=0;iresult.length())//store the result if it is longer \n result = interimresult;\n interimresult = \"\"; //clear to continue with the next letter\n }\n return result;\n}\n\n"} +{"text": "Q:\n\nError in perlipc documentation?\n\nI'm trying to puzzle through something I see in the perlipc documentation.\n\nIf you're writing to a pipe, you should also trap SIGPIPE. Otherwise,\n think of what happens when you start up a pipe to a command that\n doesn't exist: the open() will in all likelihood succeed (it only\n reflects the fork()'s success), but then your output will\n fail--spectacularly. Perl can't know whether the command worked\n because your command is actually running in a separate process whose\n exec() might have failed. Therefore, while readers of bogus commands\n return just a quick end of file, writers to bogus command will trigger\n a signal they'd better be prepared to handle. Consider:\n\n open(FH, \"|bogus\") or die \"can't fork: $!\";\n print FH \"bang\\n\" or die \"can't write: $!\";\n close FH or die \"can't close: $!\";\n\nThat won't blow up until the close, and it will blow up with a\n SIGPIPE. To catch it, you could use this:\n\n $SIG{PIPE} = 'IGNORE';\n open(FH, \"|bogus\") or die \"can't fork: $!\";\n print FH \"bang\\n\" or die \"can't write: $!\";\n close FH or die \"can't close: status=$?\";\n\nIf I'm reading that correctly, it says that the first version will probably not die until the final close. \nHowever, that's not happening on my OS X box (Perl versions 5.8.9 through 5.15.9). It blows up on the open with a \"can't fork: No such file or directory\" regardless of whether or not I have the $SIG{PIPE} line in there.\nWhat am I misunderstanding?\n\nA:\n\nThis was a change implemented back during development of 5.6 so that system() could detect when it failed to fork/exec the child\nhttps://github.com/mirrors/perl/commit/d5a9bfb0fc8643b1208bad4f15e3c88ef46b4160\nIt is also documented in http://search.cpan.org/dist/perl/pod/perlopentut.pod#Pipe_Opens\nwhich itself points to perlipc, but perlipc does seem to be missing this\n\n"} +{"text": "Q:\n\nSetting a jQuery dialog button callback\n\nHey coders, i would like to initialize a dialog box with a callback function for say a 'save' button but i want the callback to reside as a standalone function rather than defined inline using function(){....} the code snippet below highlights what I want to do. \n$( \"#dialog-form\" ).dialog({\n autoOpen: false,\n height: 300,\n width: 350,\n modal: true,\n buttons: {\n \"Save\": saveAction() \n...\nfunction saveAction() \n{ \n} \n\nwhat is the proper syntax for the \"Save\": saveAction() line cause it is doesn't seem to work?\nthanks\n\nA:\n\nThe parens after saveAction makes the function execute. Use this instead:\n \"Save\": saveAction\n\n"} +{"text": "Q:\n\nAre my forms a danger towards code injection?\n\nI'm writing a PHP tutorial and I would like to display some forms where the users could enter values that are displayed in the same webpage, just as a demonstration. \nThe forms do nothing special, they only use print instructions to display the input. \nI would like to know if these apparently innofensive forms could be a real danger for my server because of script injection.\nThe code that processes the form is:\n\n\nA:\n\nThe Short answer is yes you are vulnerable to injection. XSS to be precise which you can read more about here https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet\nExplaination:\nAll user input should be sanatized for example:\nif you input into your form you will notice an alert message will appear on your page\nhowever if you sanatize the code i.e.\nprint \"Hello, \" . htmlentities($_POST['user']);\n\nyou will no longer see the alert message\nusing htmlentities() will help protect you from the script injection.\nYou would also be better validating the data that will be expected from the user\nOther points which you can see here https://stackoverflow.com/questions/11554432/php-post-dynamic-variable-names-security-concerns which are based more on dynamically creating variables\n\nA:\n\nIt's not a security risk for your server, but it may be for your users. \nBeside the fact that if the input contains < the output might not be what you expected, the real dangers you face are XSS and CSRF. \nFor example, a malicious attacker could make the user click on a link which opens your example form, and executes some malicious javascript. The big problem is not executing (on the client) attacker-controlled code, but the fact that the browser sees it as coming from your website, so it has access to cookies, etc...\n\n"} +{"text": "Q:\n\nmethode getconnection not found in \\Doctrine\\Common\\Persistence\n\nI am following a tutoral on Symfony 4 where we want to create a raw query. Here is the code that is provided in the tutorial :\npublic function index(Request $request)\n{\n $entityManager = $this->getDoctrine()->getManager();\n\n $conn = $entityManager->getConnection();\n $sql = '\n SELECT * FROM user u\n WHERE u.id > :id\n ';\n $stmt = $conn->prepare($sql);\n $stmt->execute(['id' => 3]);\n\n //more code \n }\n\nBut when I try to do the same the methode getconnection seem to not be recognized by my IDE and it gives me this message :\n\nmethode getconnection not found in \\Doctrine\\Common\\Persistence\\ObjectManager\n\nAny ideas about what shoould I do ? I will apreciate it.\n\nA:\n\nsince it's not really an error, but more of a static analysis result, you can try to quiet the static analysis tool used (not exactly sure, which one it is) you could do this when getting your entity manager:\n/** @var \\Doctrine\\ORM\\EntityManagerInterface $entityManager */\n$entityManager = $this->getDoctrine()->getManager();\n\nif the static analysis tool is any good, it will accept the comment/hint and recognize the entity manager for what it truly is and probably will stop complaining.\n(the question I ask myself: is there a reason you use plain SQL instead of ... you know ... the entity manager, like ... $user = $entityManager->find(User::class, 3); ... unless your User is not an entity for whatever reason)\n\n"} +{"text": "Q:\n\nCreate variables from an array of cells in Matlab\n\nI have an array of cells, for example,\ncells = {'a', 'b', 'c', d', 'e'};\nwhich is inside a for loop of 1 to 5.\nI want to create a variable from a to e depending on the loop index, as 1 to a, 2 to b...\nWhen I try (i is the for index),\neval(cells{i}) = values; it gives me the error,\nUndefined function or method 'eval' for input arguments of type 'a'\n\nA:\n\nHere the answer:\neval(sprintf([cells{i} '=values;']))\n\nAnd you can remove the ; if you want to see the display in command window.\nIn answer to your comment :\ncells = {'a', 'b', 'c', 'd', 'e'};\nvalues = 4;\ni = 1;\neval(sprintf([cells{i} '=values;']))\n\nThis works perfectly fine on my computer, and i get no warning or error messages.\n\n"} +{"text": "Q:\n\nCreate web services for Data Mining using Business Intelligence Development Studio (BIDS)\n\nI am getting started with Data Mining for design an E-trading system that able to show recommendations for customers who have online trading. Depend on Market Basket (purchasing history), BIDS show the product that suitable for my recommendation I have designed all data mining structure and model good and success to query the result in BI\nI have to develop on ASP.NET, objective-C (IOS) and android. I need to write a webservice using C# but i don't know how to query from BIDS. Does anybody know?\nSELECT\n t.[CustomerKey],\n t.[Region],\n PredictAssociation([Association].[v Assoc Seq Line Items], include_statistics, 3)\nFrom\n [Association]\nPREDICTION JOIN\n SHAPE {\n OPENQUERY([Adventure Works DW],\n 'SELECT\n [CustomerKey],\n [Region],\n [OrderNumber]\n FROM\n [dbo].[vAssocSeqOrders]\n ORDER BY\n [OrderNumber]')}\n APPEND \n ({OPENQUERY([Adventure Works DW],\n 'SELECT\n [Model],\n [OrderNumber]\n FROM\n [dbo].[vAssocSeqLineItems]\n ORDER BY\n [OrderNumber]')}\n RELATE\n [OrderNumber] TO [OrderNumber])\n AS\n [vAssocSeqLineItems] AS t\nON\n [Association].[v Assoc Seq Line Items].[Model] = t.[vAssocSeqLineItems].[Model]\nORDER BY t.[CustomerKey]\n\nHow to call this predictive query in C# and get result?\n\nA:\n\nI assume here that you know how to write a web service. \nYou should use the adomd.net to fetch your cube data.\nRefer: ADOMD.NET Client Programming\nExample: Displaying a grid using ADOMD.NET and MDX\nCode:\nAdomdConnection conn = new AdomdConnection(strConn);\nconn.Open();\nAdomdCommand cmd = new AdomdCommand(MDX_QUERY, conn);\nCellSet cst = cmd.ExecuteCellSet();\n\n"} +{"text": "Q:\n\n\u041f\u0440\u0438 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u0438 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432, \u043f\u043e\u043f\u0430\u0434\u0430\u044e\u0442 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b \u0438\u0437 \u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0435\u0433\u043e\n\n#include \n\nint main ()\n{\n\n char arr[] = {'i', 's', ' ', 'i', 't'};\n char arr2[] = {'w', 'h', 'a', 't'};\n\n printf(\"%s\\n\", arr); // \u0412\u044b\u0432\u043e\u0434\u0438\u0442 'is it'\n printf(\"%s\\n\", arr2); // \u0412\u044b\u0432\u043e\u0434\u0438\u0442 'whatis it\n\n return 0;\n\n}\n\nA:\n\n\u041f\u043e\u0442\u043e\u043c\u0443 \u0447\u0442\u043e \u043f\u0440\u0438 \u0432\u044b\u0432\u043e\u0434\u0435 \u0447\u0435\u0440\u0435\u0437 %s \u0441\u0438\u043c\u0432\u043e\u043b\u044b \u0432\u044b\u0432\u043e\u0434\u044f\u0442\u0441\u044f \u043f\u043e\u043e\u0447\u0435\u0440\u0435\u0434\u043d\u043e, \u043f\u043e\u043a\u0430 \u043d\u0435 \u0432\u0441\u0442\u0440\u0435\u0442\u0438\u0442\u0441\u044f \u043d\u0443\u043b\u0435\u0432\u043e\u0439 \u0441\u0438\u043c\u0432\u043e\u043b - \u043f\u0440\u0438\u0437\u043d\u0430\u043a \u043a\u043e\u043d\u0446\u0430 \u0441\u0442\u0440\u043e\u043a\u0438.\n\u0423 \u0432\u0430\u0441 \u0436\u0435 \u0442\u0430\u043a\u043e\u0433\u043e \u0441\u0438\u043c\u0432\u043e\u043b\u0430 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\u0445 \u043d\u0435 \u043f\u0440\u0435\u0434\u0443\u0441\u043c\u043e\u0442\u0440\u0435\u043d\u043e. \u0427\u0442\u043e\u0431\u044b \u044d\u0442\u043e \u0431\u044b\u043b\u0438 \u0438\u043c\u0435\u043d\u043d\u043e \u0434\u0432\u0435 \u0441\u0442\u0440\u043e\u043a\u0438, \u043c\u043e\u0436\u043d\u043e \u0441\u0434\u0435\u043b\u0430\u0442\u044c \u0442\u0430\u043a:\nchar arr[] = {'i', 's', ' ', 'i', 't', '\\0'};\nchar arr2[] = {'w', 'h', 'a', 't', '\\0'};\n\n\u0438\u043b\u0438 \u0442\u0430\u043a:\nchar arr[] = \"is it\";\nchar arr2[] = \"what\";\n\n(\u041e\u0431\u0440\u0430\u0442\u0438\u0442\u0435 \u0432\u043d\u0438\u043c\u0430\u043d\u0438\u0435 \u043d\u0430 \u0434\u0432\u043e\u0439\u043d\u044b\u0435 \u043a\u0430\u0432\u044b\u0447\u043a\u0438 - \u0432 \u044d\u0442\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435 \u043d\u0443\u043b\u0435\u0432\u043e\u0439 \u0441\u0438\u043c\u0432\u043e\u043b \u0431\u0443\u0434\u0435\u0442 \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0438.)\n\u041d\u0443, \u0430 \u0432\u044b\u0432\u043e\u0434\u0438\u0442 \u043e\u0431\u0430 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 - \u043f\u0440\u043e\u0441\u0442\u043e \u043e\u043d\u0438 \u043e\u043a\u0430\u0437\u0430\u043b\u0438\u0441\u044c \u0440\u044f\u0434\u043e\u043c \u0432 \u043f\u0430\u043c\u044f\u0442\u0438...\n\n"} +{"text": "Q:\n\nMySQL does not use effectively use the index for ORDER BY queries\n\nI have a simple Message table, with 2 indexes:\nmysql> show keys from Message;\n+---------+------------+-----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+\n| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |\n+---------+------------+-----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+\n| Message | 0 | PRIMARY | 1 | id | A | 5643295 | NULL | NULL | | BTREE | |\n| Message | 1 | timestamp | 1 | startTimestamp | A | 5643295 | NULL | NULL | | BTREE | |\n+---------+------------+-----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+\n\nWhen issuing an order by query, a very large number of rows is examined:\nmysql> explain SELECT * from Message ORDER BY startTimestamp LIMIT 0,20;\n+----+-------------+---------+-------+---------------+-----------+---------+------+---------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+---------+-------+---------------+-----------+---------+------+---------+-------+\n| 1 | SIMPLE | Message | index | NULL | timestamp | 8 | NULL | 5643592 | |\n+----+-------------+---------+-------+---------------+-----------+---------+------+---------+-------+\n\nThe total row count is:\nmysql> select count(*) from Message;\n+----------+\n| count(*) |\n+----------+\n| 5837363 |\n+----------+\n\nThis query touches 96.7% of the rows. The index is BTREE, so as far as I know it should simply yank out the top 20 rows and return them. As it stands, it's using an index to access almost all of the table's rows, which is presumably slower than a full table scan.\nAm I mistaken in my assumption that it should simply pick the top 20 rows using the index and return them?\nThe MySQL server version is 5.0.45 and the table type is InnoDB.\n\nA:\n\nin the EXPLAIN, MySQL estimates the number of rows scanned to 5643592 but it's using the right index(order by column:timestamp) and is limited to 20 rows, so don't worry it's doing the right thing and will stop as soon as 20 rows are sent. Can you give us the query execution time?\n\n"} +{"text": "Q:\n\nHow to render multiple times on the same response object with ExpressJS?\n\nI have a situation where I need multiple renders to occur with the same response object in an ExpressJS application. (Basically one HTTP request triggers multiple back-end requests, all of which can begin rendering results to the page immediately as they complete.) The problem is that I need each one to render a view (i.e. I don't think I can use res.write()), and as far as I can tell, there is no way for res.render() to not end the response or write headers each time it is called.\nWhat am I missing?\n\nA:\n\nExpress compiles the template using an engine like EJS, Jade etc.\nThe data is then rendered using response.send: https://github.com/visionmedia/express/blob/master/lib/response.js#L76-131\nAs you can see there, at the end there is this.end..., which means response.end(...).\nIf you want do achieve sending multiple views, you must compile those views yourself using the view engine and then create a function similar to response.send (which I gave you the link above), but be careful not to send the headers twice or call response.end before the last view is rendered.\n\n"} +{"text": "Q:\n\nLoad balancers and SQL backups\n\nOur production environments typically consists in 4-8 Apache web servers and 2 (My)SQL servers :\n\nEach web server is affiliated to one SQL server\nSQL servers have a circular replication setup\nAll web servers are load balanced, by Pound for example.\n\nEvery night a job backups one of the SQL servers, locking the affiliated web servers for about 10-15 minutes.\nIs there a way to configure the balancing to avoid reaching those locked servers for a short time?\nIs there another way to handle this lock, other than backuping a non-production third server?\nPS: We envisage to reload the Pound configuration, just before and after the backup, with an appropriate configuration file, but it feels a bit odd... \n\nA:\n\nHow about using poundctl to disable and reenable the backend server? It must be run locally (the command protocol uses unix sockets), but you could probably have it launched remotely through an ssh session.\nFrom the man page:\n\nOPTIONS\n[...]\n-B/-b n m r \n Enable/disable a back-end. A disabled back-end will not be passed requests to answer. Note however that existing sessions may still cause requests to be sent their way.\n\n-n n m k\n Remove a session from service m in listener n. The session key is k.\n\n"} +{"text": "Q:\n\nNumpy matrix must be 2-dimensional error\n\nI have the following code:\nimport numpy as np\ndef J(x, y):\n return np.matrix([[8-(4 * y), -4 * y], [y, -5 + x]])\n\nx_0 = np.matrix([[1], [1]])\ntest = J(x_0[0], x_0[1])\n\nWhen I go to run it I receive the following error:\nTraceback (most recent call last):\n File \"broyden.py\", line 15, in \n test = J(x_0[0][0], x_0[1][0])\n File \"broyden.py\", line 12, in J\n return np.matrix([[8-(4 * y), -4 * y], [y, -5 + x]])\n File \"/home/collin/anaconda/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py\", line 261, in __new__\n raise ValueError(\"matrix must be 2-dimensional\")\nValueError: matrix must be 2-dimensional\n\nI don't understand why I'm getting this error. Everything appears to be 2-d.\n\nA:\n\nThe type of x_0[0] is still numpy.matrixlib.defmatrix.matrix, not a scalar value.\nYou need get a scale value to treat as a matrix element. Try this code\ntest = J(x_0.item(0), x_0.item(1))\n\n"} +{"text": "Q:\n\nCan I serve both PHP and Node apps from the same server but with different internet domains?\n\nI own a Debian server with a single IP address, which I use for all my personal projects. What I want to do is serve both my Wordpress and my Node.js apps from that same server if possible, using different internet domains for each app\nFor example\n\nwww.myblog.org:80 should serve wordpress/index.php\nmy_app.com:80 should serve node instance at localhost:3000\nmy_other_node_app.com:80 should serve node instance at localhost:3001 \netc...\n\nIs this thing possible somehow? I don't mind stop using apache if this is what it takes\n\nA:\n\nOnly one piece of software can listen on a given port of a given network interface.\nIf you had, for example, two ethernet adaptors, with different IP addresses, then you could configure your Node server to listen on port 80 on one of them and your Apache server to listen to port 80 on the other one, then set up DNS to point different domains at different ip addresses.\nIf you only have one ip address, then you would have to run the servers on different ports.\nYou could run Apache on port 80 and then use it to proxy requests to node.\n\nA:\n\nYou can serve on multiple domains using a reverse proxy server, like nginx.\nCheck out this question here:\nNginx Different Domains on Same IP\nBut the basic idea is one server actually listens on port 80, and it handles sending the request to the right app server (php, node, etc) on your machine serving internally (localhost:8000).\nIt's not technically very hard to do, but getting used to configuring a new piece of software like nginx can be a little challenging. Definitely definitely doable though!\n\n"} +{"text": "Q:\n\nC read and write from named pipe\n\nI ultimately want a solution to this problem but in true one-step-forward-two-steps-back fashion which is programming, I have been reduced to figuring out why I can't even write a character to a named pipe then get that very same character back. Here is a simple MWE script I have, and the accompanying output I am, regretfully, getting:\nMWE:\n#include \n#include \n#define PIPE_PATH \"testpipe\"\n\nint main( int argc, char *argv[] ) {\n int fd;\n FILE *fp;\n char c;\n int result;\n int contingency;\n\n //Initialize it for debugging purposes\n c = 0;\n contingency = 0;\n\n if ( atoi ( argv [ 1 ] ) == 1 )\n {\n printf (\"Writer [%s]\\n\", argv[1]);\n\n mkfifo ( PIPE_PATH, 0666 );\n\n fd = open ( PIPE_PATH, O_WRONLY );\n c = getchar();\n printf ( \"[%d] [%s]\\n\", c, &c );\n\n if ( ( result = write ( fd, &c, 1 ) ) == -1)\n {\n fprintf ( stderr, \"error writing to pipe\\n\" );\n return -1;\n }\n\n close(fd);\n }\n else if ( atoi ( argv [ 1 ] ) == 2 )\n {\n printf ( \"Reader [%s]\\n\", argv[1] );\n\n fp = fopen( PIPE_PATH, \"r\" );\n while ( contingency < 3 && ( c = getc ( fp ) ) != EOF )\n { //contingency set to 3 to avoid infinite loop\n c = getc ( fp );\n putchar ( c );\n printf ( \"[%d]\\n\", c ); //don't print c as a string or the shell will go nuts\n\n printf ( \"\\n\" );\n contingency++;\n }\n fclose ( fp );\n\n unlink( PIPE_PATH );\n }\n\n return 0;\n}\n\nOutput:\nWriter [1]\nq\n[113] [q]\n....\nReader [2]\n\ufffd[255]\n\ufffd[255]\n\ufffd[255]\n\nFor some reason I am getting a question symbol stuck in hexagon, but which in vim looks like a y (gamma?) with an umlat over it. Since the ASCII code associated with this character is 255, I am assuming that the pipe is not working as expected and returning the highest value possible. Could somebody please tell me what is going on as I have literally spent the last 6 hours of my life accomplishing nothing?\n\nA:\n\nFirst error\nA big problem here...\nchar c = getc(fp);\n\nSee that? That's a big problem. Why? Let's look at the definition of getc()...\nint getc(FILE *stream);\n\nYes, it returns int not char, and that is Important with a capital I and a bold font. The getc() function (or macro) signals EOF with the EOF, which is usually -1, and therefore becomes 0xff when stored in a char.\nAlways use int with getc().\nint c = getc(fp);\nif (c == EOF) {\n ...\n}\n\nSecond error\nWell, why are we getting EOF? Because getc() is called twice instead of once...\nwhile ((c = getc(fp)) != EOF) {\n c = getc(fp); // <-- should not be there\n ...\n}\n\nThird error\nThis code is also wrong:\nchar c = ...;\nprintf(\"[%d] [%s]\\n\", c, &c);\n\nYes, &c has type char * but that does not mean you can print it out with %s. The %s specifier is strictly for NUL-terminated strings. Either use %c, or continue using %s and NUL-terminate the string you pass it.\nchar c = ...;\nprintf(\"[%d] [%c]\\n\", c, c);\n\nOr...\nchar c = ...;\nprintf(\"[%d] [%s]\\n\", c, (char[]){c, '\\0'});\n\n"} +{"text": "Q:\n\nSelect Everything After Greater Than in Python\n\nI have a string\n\"Tyson Invitational 02/08/2013','#FFFFCC')\"\"; ONMOUSEOUT=\"\"kill()\"\" >6.54\"\n\nHow would I use regex to select everything after the right-pointing bracket? Aka how would I get the 6.54?\nI've tried \n\\>(.*)\n\nbut I'm not sure it's working properly. I use \nm = re.search( '\\>(.*)', row_out[5])\n\nand get\n<_sre.SRE_Match object at 0x10b6105d0>\n\nNot sure what the issue is.\nThanks!\n\nA:\n\n>>> import re\n>>> str=\"\"\"Tyson Invitational 02/08/2013','#FFFFCC')\"\"; ONMOUSEOUT=\"\"kill()\"\" >6.54\"\"\"\n>>> re.search('\\>(.*)',str)\n<_sre.SRE_Match object at 0x7f0de9575558>\n\nsame as you got before. However assign the search result to a variable and\n>>> f=re.search('\\>(.*)',str)\n>>> f.groups()\n('6.54',)\n\n"} +{"text": "Q:\n\nhow to convert png image to vectorized image?\n\nI use this online converter and more than this \nhttps://image.online-convert.com/convert-to-svg to convert image to vector but i only can get image as svg icon and its tag is svg but i need to make its tag vector like this format \n\n\n\nso how can i get image with this format and make it vector image .I also try with illustrator but also I get svg only .I need image for android app.\n\nA:\n\nRight click in the image folder (like drawable or mipmap) > New > Vector Asset\n\nselect the .svg file and set a name:\n\nand the you will have created the vector drawable file:\n\n\n \n\n\n"} +{"text": "Q:\n\nWhich verb collocates with the word 'heresy'?\n\nWhen talking about the first people who were known to believe or do something considered heretical, which verb do we use with the word heresy? I want the verb for the 'invention' of the heresy - not a person who just follows it.\nFor example: 'They (past verb) this heresy in the second century.'\n\nA:\n\n\"espouse\" might be the verb you're looking for. - A person espouses a heresy.\n\n\"espouse\" - to make one's own; adopt or embrace, as a cause.\n\n\"Those who espouse the \u201cheresy of Luther,\u201d are legitimate only if they are graced by God\"\n\".....they espouse the heresy that it is the president who knows best\"\n\"The founder or leader of a heretical movement is called a heresiarch, while individuals who espouse heresy or commit heresy, are known as heretics.\" Societies, Network and Transitions\n\nEDIT\nYou could say that \"According to the Holy See, Martin Luther conceived, established and disseminated that heresy (the protestant reformation) in the sixteenth century.\n\nA:\n\nThey promulgated this heresy in the second century.\nFrom Merriam-Webster:\n\nSynonym Discussion of Promulgate\nDeclare, announce, proclaim, promulgate mean to make known publicly.\n Declare implies explicitness and usually formality in making known\n . Announce implies the\n declaration of something for the first time . Proclaim implies declaring clearly,\n forcefully, and authoritatively . Promulgate implies the proclaiming of a dogma,\n doctrine, or law .\n\n"} +{"text": "Q:\n\nCould not parse Master URL: 'spark.bluemix.net'\n\nI'm trying to connect to IBM's Spark as a Service running on Bluemix from RStudio running on my desktop machine.\nI have copied the config.yml from the automatically configured RStudio environment running on IBM's Data Science Experience:\ndefault:\n method: \"shell\"\n\nCS-DSX:\n method: \"bluemix\"\n spark.master: \"spark.bluemix.net\"\n spark.instance.id: \"myinstanceid\"\n tenant.id: \"mytenantid\"\n tenant.secret: \"mytenantsecret\"\n hsui.url: \"https://cdsx.ng.bluemix.net\"\n\nI am attempting to connect like so:\ninstall.packages(\"sparklyr\")\n\nlibrary(sparklyr)\nspark_install(version = \"1.6.2\") # installed spark to '~/Library/Caches/spark/spark-1.6.2-bin-hadoop2.6'\n\nspark_home = '~/Library/Caches/spark/spark-1.6.2-bin-hadoop2.6'\n\nconfig = spark_config(file = \"./config.yml\", use_default = FALSE, config = \"CSX-DSX\")\n\nsc <- spark_connect(spark_home = spark_home, config = config)\n\nThe error:\n17/03/07 09:36:19 ERROR SparkContext: Error initializing SparkContext.\norg.apache.spark.SparkException: Could not parse Master URL: 'spark.bluemix.net'\n at org.apache.spark.SparkContext$.org$apache$spark$SparkContext$$createTaskScheduler(SparkContext.scala:2735)\n at org.apache.spark.SparkContext.(SparkContext.scala:522)\n at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2281)\n at org.apache.spark.SparkContext.getOrCreate(SparkContext.scala)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n ...\n\nThere are a few other questions on stackoverflow with similar error messages, but they are not trying to connect to the Spark service running on Bluemix.\n\nUpdate 1\nI've changed my config.yml to look like this:\ndefault:\n method: \"bluemix\"\n spark.master: \"spark://spark.bluemix.net:7070\"\n spark.instance.id: \"7a4089bf-3594-4fdf-8dd1-7e9fd7607be5\"\n tenant.id: \"sdd1-7e9fd7607be53e-39ca506ba762\"\n tenant.secret: \"6146a713-949f-4d4e-84c3-9913d2165b9e\"\n hsui.url: \"https://cdsx.ng.bluemix.net\"\n\n... and my connection code to look like this:\ninstall.packages(\"sparklyr\")\nlibrary(sparklyr)\nspark_install(version = \"1.6.2\")\nspark_home = '~/Library/Caches/spark/spark-1.6.2-bin-hadoop2.6'\nconfig = spark_config(file = \"./config.yml\", use_default = FALSE)\nsc <- spark_connect(spark_home = spark_home, config = config)\n\nHowever, the error is now:\nError in force(code) : \n Failed during initialize_connection: java.lang.NullPointerException\n at org.apache.spark.SparkContext.(SparkContext.scala:583)\n at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2281)\n at org.apache.spark.SparkContext.getOrCreate(SparkContext.scala)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at sparklyr.Invoke$.invoke(invoke.scala:94)\n ...\n\nA:\n\nI received the following response from the engineering team:\n\nRStudio desktop version doesn't support at this time to use sparklyr package to connect Bluemix SparkaaS service\n\n"} +{"text": "Q:\n\nWhen the url contains \"e\" it no longer matchs the requested route\n\nMore than a long talk to explain that bug, here's a screenshot that explains everything :\nAs soon as we enter an \"e\" inside the url which correspond to rss_category, it no longer match the route. See : \n!\nWe resolved this by forcing a requirements for {slugCat} to accept anything .^ (they were no requirements before)\nIf that can help someone somday, and if anyone has a valid explanation, i'll be glad to hear (runing under Symfony 2.1.1).\n\nA:\n\nWow, difficult one. This happens because when compiling the route, symfony tries to use the character preceeding the variable name as a separator. This code is from RouteCompiler.php:\n // Use the character preceding the variable as a separator\n $separators = array($match[0][0][0]);\n\n if ($pos !== $len) {\n // Use the character following the variable as the separator when available\n $separators[] = $pattern[$pos];\n }\n $regexp = sprintf('[^%s]+', preg_quote(implode('', array_unique($separators)), self::REGEX_DELIMITER));\n\nSymfony does this because usually you will have some kind of separator before the variable name, a route like /upload/rssArticle/{slugCat}, where '/' would be the separator and it is trying to be helpful by letting you use this separator to separate variables in routes which contain several variables. In your case, the character before the variable is an 'e' and that character becomes a separator and that is why your route does not match. If your route had beed /upload/rssArticles{slugCat}, then the 's' would be the separator and that would be the character you would not be able to use.\nMaybe you could create an issue on the symfony router component. I think that the preceeding character should not be used as a separator if it is a letter or a number.\n\n"} +{"text": "Q:\n\nRestSharp \u043f\u0440\u043e\u0431\u043b\u0435\u043c\u0430 \u0441 \u043a\u0443\u043a\u0430\u043c\u0438\n\n\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435. \u041d\u0443\u0436\u043d\u043e \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u043a\u0443\u043a\u0438 \u043f\u043e\u0441\u043b\u0435 \u0440\u0435\u0434\u0438\u0440\u0435\u043a\u0442\u0430. \u0427\u0435\u0440\u0435\u0437 \u0441\u043d\u0438\u0444\u0435\u0440 \u0432\u0438\u0434\u043d\u043e \u0447\u0442\u043e \u0440\u0435\u0434\u0438\u0440\u0435\u043a\u0442 \u0441\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0435\u0442 \u0438 \u0437\u0430\u043f\u0440\u043e\u0441 \u043f\u0435\u0440\u0435\u0441\u043a\u0430\u043a\u0438\u0432\u0430\u0435\u0442 \u043d\u0430 \u0434\u0440\u0443\u0433\u0443\u044e \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0443 \u0438 \u043f\u043e\u043b\u0443\u0447\u0430\u044e\u0442\u0441\u044f \u043a\u0443\u043a\u0438, \u043d\u043e \u0432 respons'\u0435 \u0438\u0445 \u043d\u0435\u0442. \u0412 \u0447\u0435\u043c \u043f\u0440\u043e\u0431\u043b\u0435\u043c\u0430?\n\u041c\u043e\u0439 \u043a\u043e\u0434:\npublic static async Task GetAsyncHttp(string url, List cookies)\n {\n var client = new RestClient(url)\n {\n UserAgent = @\"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0\",\n FollowRedirects = true\n };\n var request = new RestRequest(\"\", Method.GET);\n foreach (var cookie in cookies)\n {\n request.AddCookie(cookie.Name, cookie.Value);\n }\n var response = await client.ExecuteTaskAsync(request);\n return response;\n }\n\nA:\n\n\u0412\u0441\u0435 \u0440\u0435\u0448\u0438\u043b\u043e\u0441\u044c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435\u043c Cookie \u043d\u0435 \u0432 request'\u0435, \u0430 \u0432 \u0441\u0430\u043c\u043e\u043c RestClient, \u0432\u043e\u0442 \u0442\u0430\u043a:\nclient.CookieContainer = new CookieContainer();\n\n\u0412\u043c\u0435\u0441\u0442\u043e \nrequest.AddCookie(\"name\", \"value\");\n\n"} +{"text": "Q:\n\nUsing SCOPE_IDENTITY result in another query\n\nI'm having difficulties with this code\nEXECUTE Environment.dbo.psu_some_psu\n\n@instanceId = 1\n,@serverId = 2\n,@ip = '111.111.111.111'\n,@clientName = 'dev-contact'\n,@applicationId = 9\n,@accountId = 35\n,@userID = 22\n\nDECLARE @restoreId INT\nSET @restoreId = SCOPE_IDENTITY()\n\nUPDATE Environment.dbo.restore_requests\nSET Status = 1\nWHERE Id = @restoreId\n\nThe stored procedure insert a row with indentity and with a status by default.\nAfter the execution of the stored procedure i use scope_identity to get the ID of the inserted row.\nBut i cant get the update to work, i think there is a problem with the WHERE condition.\nThanks\n\nA:\n\nIt's called SCOPE_IDENTITY() because it returns the last identity value inserted in the current scope - and since each procedure has it's own scope - you do not get the expected results. \n\nReturns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.\n\nUse an output parameter to return the scope_identity() from inside the procedure that actually executes the insert statement. \nAlso, please note that if you are inserting multiple records, the scope_identity() will return only the last value - in such cases you use the output clause on the insert statement to get a table containing all the newly inserted identity values.\nDECLARE @MyTableVar table( NewScrapReasonID smallint, \n Name varchar(50), \n ModifiedDate datetime); \nINSERT Production.ScrapReason \n OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate \n INTO @MyTableVar \nVALUES (N'Operator error', GETDATE()); \n\n"} +{"text": "Q:\n\nJava Battleship game\n\nI have been given a problem statement to create a Battleship game in java. \nMy working code (Spring Boot+Web) is placed here along with the problem statement.\nhttps://github.com/ankidaemon/BattleShip\nThis question is majorly focused on design, please help me figure out, how can I make it decoupled and apply suitable design patterns.\nStartGame.java - getting called from controller\n@Component\npublic class StartGame {\n\n private static final Logger logger = LoggerFactory.getLogger(StartGame.class);\n\n public String init(File inputFile) throws FileNotFoundException, InputException {\n // TODO Auto-generated method stub\n ArrayList p1s = new ArrayList();\n ArrayList p2s = new ArrayList();\n int areaWidth = 0;\n int areahight = 0;\n ArrayList player1missiles = null;\n ArrayList player2missiles = null;\n try{\n Scanner sc = new Scanner(inputFile);\n\n areaWidth = sc.nextInt();\n if(areaWidth>9 || areaWidth<1){\n raiseException(\"Supplied area width is invalid.\",sc);\n }\n areahight = sc.next().toUpperCase().charAt(0) - 64;\n if(areahight>25 || areahight<0){\n raiseException(\"Supplied area height is invalid.\",sc);\n }\n sc.nextLine();\n int noOfships = sc.nextInt();\n if(noOfships>areahight*areaWidth || noOfships<1){\n raiseException(\"Supplied no of ships is invalid.\",sc);\n }\n sc.nextLine();\n for (int j = 0; j < noOfships; j++) {\n char typeOfShip = sc.next().toUpperCase().charAt(0);\n if(typeOfShip!='P' && typeOfShip!='Q'){\n raiseException(\"Supplied type of ship is invalid.\",sc);\n }\n int shipWidth = sc.nextInt();\n if(shipWidth>areaWidth || shipWidth<0){\n raiseException(\"Supplied ship width is invalid.\",sc);\n }\n int shiphight = sc.nextInt();\n if(shiphight>areahight || shiphight<0){\n raiseException(\"Supplied ship height is invalid.\",sc);\n }\n BattleShips ship;\n for (int i = 0; i <= 1; i++) {\n char[] locCharArr = sc.next().toUpperCase().toCharArray();\n int[] loc = new int[2];\n loc[0] = locCharArr[0] - 65;\n loc[1] = locCharArr[1] - 49;\n if(loc[0]>areahight || loc[0]<0 || loc[1]>areaWidth || loc[1]<0){\n raiseException(\"Supplied ship location is invalid.\",sc);\n }\n ship = new BattleShips(shipWidth, shiphight, typeOfShip, loc);\n if (i % 2 == 0)\n p1s.add(ship);\n else\n p2s.add(ship);\n }\n sc.nextLine();\n }\n\n player1missiles = returnMissileCoordinates(sc.nextLine());\n player2missiles = returnMissileCoordinates(sc.nextLine());\n sc.close();\n }catch(InputMismatchException e){\n throw new InputException(\"Invalid Input supplied.\",ErrorCode.INVALIDINPUT);\n }\n BattleArea player1 = new BattleArea(\"player1\", areaWidth, areahight, p1s);\n BattleArea player2 = new BattleArea(\"player2\", areaWidth, areahight, p2s);\n\n player1.placeShips();\n player2.placeShips();\n\n while (!player1.isLost() && !player2.isLost()) {\n for (int i = 0; i < player1missiles.size();) {\n Coordinate c = player1missiles.get(i);\n while (player1.fireMissile(c, player2)) {\n player1missiles.remove(i);\n if (i < player1missiles.size()) {\n c = player1missiles.get(i);\n } else\n break;\n }\n if (player1missiles.size() > 0) {\n player1missiles.remove(i);\n }\n break;\n }\n for (int j = 0; j < player2missiles.size();) {\n Coordinate c = player2missiles.get(j);\n while (player2.fireMissile(c, player1)) {\n player2missiles.remove(j);\n if (j < player2missiles.size()) {\n c = player2missiles.get(j);\n } else\n break;\n }\n if (player2missiles.size() > 0) {\n player2missiles.remove(j);\n }\n break;\n }\n }\n\n if (player1.isLost()) {\n logger.info(\"-------------------------\");\n logger.info(\"Player 2 has Won the Game\");\n logger.info(\"-------------------------\");\n return \"Player 2 has Won the Game\";\n } else {\n logger.info(\"-------------------------\");\n logger.info(\"Player 1 has Won the Game\");\n logger.info(\"-------------------------\");\n return \"Player 1 has Won the Game\";\n }\n }\n\n private static ArrayList returnMissileCoordinates(String nextLine) {\n // TODO Auto-generated method stub\n ArrayList tmp = new ArrayList();\n String[] arr = nextLine.split(\"\\\\ \");\n Coordinate tmpC;\n for (String s : arr) {\n char[] charArr = s.toCharArray();\n tmpC = new Coordinate(charArr[1] - 49, charArr[0] - 65);\n tmp.add(tmpC);\n }\n return tmp;\n }\n\n private void raiseException(String message, Scanner sc) throws InputException {\n sc.close();\n throw new InputException(message, ErrorCode.INVALIDINPUT);\n }\n}\n\nBattleArea.java\npublic class BattleArea {\n\nprivate static final Logger logger = LoggerFactory.getLogger(BattleArea.class);\n\nprivate String belongsTo;\nprivate int width,height;\nprivate ArrayList battleShips;\nprivate Set occupied=new TreeSet();\nprivate int[][] board=null;\nprivate boolean lost=false;\n\npublic BattleArea(String belongsTo, int width, int height, ArrayList battleShips) {\n super();\n this.belongsTo = belongsTo;\n this.width = width;\n this.height = height;\n this.battleShips = battleShips;\n this.board=new int[this.width][this.height];\n}\n\npublic void placeShips(){\n for(BattleShips ship:this.battleShips){\n int x=ship.getLocation()[1];\n int y=ship.getLocation()[0];\n if(ship.getWidth()+x>this.width || ship.getHeight()+y>this.height){\n logger.error(\"Coordinate x-\"+x+\" y-\"+y+\" for \"+this.belongsTo+\" is not avilable.\");\n throw new ProhibitedException(\"Ship cannot be placed in this location.\",ErrorCode.OUTOFBATTLEAREA);\n }else{\n Coordinate c=new Coordinate(x, y);\n if(occupied.contains(c)){\n logger.error(\"Coordinate x-\"+c.getX()+\" y-\"+c.getY()+\" for \"+this.belongsTo+\" is already occupied.\");\n throw new ProhibitedException(\"Ship cann't be placed in this location.\",ErrorCode.ALREADYOCCUPIED);\n }else{\n Coordinate tempC;\n for(int i=x;i {\n\nprivate int x,y;\n\npublic Coordinate(int x, int y) {\n super();\n this.x = x;\n this.y = y;\n}\n\n@Override\npublic String toString() {\n return \"Coordinate [x=\" + x + \", y=\" + y + \"]\";\n}\n\n@Override\npublic int compareTo(Coordinate o) {\n // TODO Auto-generated method stub\n if(this.x==o.x && this.y==o.y)\n return 0;\n else if(this.x p1bs = setup.getFirstBattleShips(); \n ArrayList p2bs = setup.getSecondBattleShips(); \n playerOne.setBattleShips(p1bs);\n playerTwo.setBattleShips(p2bs);\n\n playerOne.setMissiles(setup.getFirstMissileCoordinates());\n playerTwo.setMissiles(setup.getSecondMissileCoordinates());\n\n playerOne.setBoard(new BattleShipBoard(setup.getDimension());\n playerTwo.setBoard(new BattleShipBoard(setup.getDimension());\n\n playerOne.placeShips();\n playerTwo.placeShips();\n\n return true; \n}\n\nNOTE: the init method could be shortenend far more, but i think i point out in a good way what init should really do...\nas mentioned above you have moved the game logic out of your init method and put it in the playGame() method.\npublic Result playGame(){\n Result result = new Result();\n Scores score = new Score();\n while (!player1.isLost() && !player2.isLost()) {\n for (int i = 0; i < player1missiles.size();) {\n ... \n } \n }\n result.setWinner(playerOne);\n result.setScore(scores);\n return result;\n}\n\nthe BattleShipGame would start now this manner:\npublic void start(){\n init();\n Result result = playGame(); \n ... //do whatever you want with your result - for example print it into the console\n}\n\nfor your BattleShip there are some more issuses wich can be talked about. I think it was a very good idea to use a class Coordinate which looks good at first glance. But you don't use it consequencically. think about how it would be if you used Coordinate for you ship instead of int[] that would make your code as well easier to read and the math would be much easier. And don't use a char for your shiptype, use a enum instead. But let's be honest, you don't have a 'position and width and height' what you really have is an rectangle - so use an rectangle!\npublic class BattleShips {\n\n private ShipType shipType;\n private Rectangle bounds;\n private int lifePoints;\n\n public BattleShips(ShipType typeOfShip, Coordinate pos) {\n super();\n shipType = typeOfShip;\n bounds = new Rectangle(shipType.getDimension, pos);\n lifePoints = shipType.getLifePoints();\n }\n\n public Rectangle getBounds() {\n return bounds();\n }\n\n ...\n}\n\nthe dimension of the Rectangle (width/height) and the amount of lifepoints can be determind by the ShipType\npublic Enum Shiptype {\n DESTROYER(2,4,2), SUBMARINE(1,3,1), ...; //don't use shiptype P or shiptype Q\n\n private final Dimension dimension;\n final int lifePoints;\n\n public ShipType(int w, int h, int life){\n dimension = new Dimension(w,h);\n lifePoints = life;\n }\n\n public Dimension getDimension(){\n return dimension;\n }\n\n public int getLifePoints(){\n return lifePoints();\n }\n}\n\nThe BattleArea is now far more easy to use, think about how simple you can placeShips now:\npublic class BattleArea {\n\n private Player owner;\n private Rectangle boardBounds;\n private List battleShips;\n private List board;\n\n public BattleArea(Player owner, Rectangle bounds, List battleShips) {\n super();\n this.owner = owner;\n this.dimension = dimension;\n this.battleShips = battleShips;\n board = createBoard();\n }\n\n public void placeShips(){\n List placedShips = new ArrayList<>();\n for(BattleShips ship:this.battleShips){\n Bound shipBounds = ship.getBounds();\n if(!boardBounds.contains(shipBounds)){\n throw new ProhibitedException(\n \"Ship cannot be placed in this location.\",ErrorCode.OUTOFBATTLEAREA);\n }\n\n for (BattleShip placedShip: placedShips){\n if (bounds.intersects(placedShip.getBounds()){\n throw new ProhibitedException(\n \"Ship cann't be placed in this location.\",ErrorCode.ALREADYOCCUPIED); \n }\n }\n placedShips.add(battleShip);\n } \n }\n\n public boolean fireMissile(Coordinate c, BattleArea enemyBattleArea){\n BattleShip shipAt = enemyBattleArea.getShipAt(c);\n if(shipAt == null){\n return false;\n }else{\n handleDamge(shipAt, enemyBattleArea);\n return true;\n }\n }\n\n private void handleDamage(BattleShip opponent, BattleArea area){\n int lifePointsLeft = opponent.getLifePoints() - 1; //hardcoded damage (that's bad)\n if(lifPoints > 0){\n //Log damage done\n }else{ \n //log destroyed\n area.removeBattleShip(opponent);\n } \n }\n}\n\nall code above has not been compiled so there may be some spelling errors and a lot of methods are not even implemented yet (like Rectangle.contains() or others).\nsummary\nbut let's look at what we have now:\n\nyou can change the ship type quite easily without modifing any code !!! (you simply have to add another shiptype in ShipType )\nyou have reduced the complexity of your code very far, you don't have dangerous calculations.\nyou have seperated concerns, the objects now do what they are supposed to do\nyou could easily change your code for another player (three-player game)\nyou could test your code now\n\n"} +{"text": "Q:\n\nHow to allow Binary File download using GRAPE API\n\nI want to allow downloading a binary file (.p12 file) using ruby's Grape API. This is what I am trying.\nget '/download_file' do\n pkcs12 = generate_pkcsfile \n content_type('application/octet-stream')\n body(pkcs12.der)\nend\n\nThe equivalent code using ActionController is\nbegin\n pkcs12 = generate_pkcsfile\n send_data(pkcs12.der,\n :filename => 'filename.p12')\nend\n\nThe problem is the file downloaded using the API seems to be a text file with a '\\ufffd' prefix embedded for every character, whereas the file downloaded using the browser seems to be binary file. How do I use the GRAPE API framework to allow downloading the same file that is downloaded via ActionController's send_data\n\nA:\n\nThere are issues #412 and #418 have been reported to grape github page.\nWhich are related to return a binary file and override content type.\nTo return binary format like so:\nget '/download_file' do\n content_type \"application/octet-stream\"\n header['Content-Disposition'] = \"attachment; filename=yourfilename\"\n env['api.format'] = :binary\n File.open(your_file_path).read\nend\n\n"} +{"text": "Q:\n\nAre multiple calls to java SaxParser.parse(String, Handler) Legal?\n\nI have a java SAX parser which I would like to call multiple times on the same Handler with different XML files. I am using this in conjunction with iText to create a multi-page PDF document where some pages have one XML tag map and other pages have another. For example,\nparser.parse(\"xmlFile1\", handler);\nparser.parse(\"xmlFile2\", handler);\n\nWhen I try to do this, I get a java.lang.RuntimeException thrown with the following stacktrace:\nDocumentException: java.lang.RuntimeException: The document is not open.\nat com.lowagie.text.pdf.PdfWriter.getDirectContent(PdfWriter.java:695)\nat com.lowagie.text.pdf.PdfDocument.newPage(Unknown Source)\nat com.lowagie.text.pdf.PdfDocument.carriageReturn(Unknown Source)\nat com.lowagie.text.pdf.PdfDocument.add(Unknown Source)\nat com.lowagie.text.Document.add(Unknown Source)\nat myClass.myCode(Unknown Source)\norg.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)\nat org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)\nat org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)\nat org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)\nat org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)\nat org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)\nat org.apache.xerces.parsers.XMLParser.parse(Unknown Source)\nat org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)\nat javax.xml.parsers.SAXParser.parse(SAXParser.java:345)\nat javax.xml.parsers.SAXParser.parse(SAXParser.java:223)\nat myClass.myCode(Unknown Source)\nat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\nat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\nat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\nat java.lang.reflect.Method.invoke(Method.java:324)\n\nDoes the SaxParser.parse method implicitly call document.close()? Or is there some other problem in my code which I need to isolate and correct?\n\nA:\n\nReusing the same parser is legal (as long as it is not used concurrently)\nThe parser triggers an \"endDocument\". This seems to close the iText document here.. But this is not done by the parser - this is code from your handler.\n\n"} +{"text": "Q:\n\nVisualize git branch topology only, with no commit history\n\nI would like to see the branch topology of my git repository in a nutshell, without visualizing the whole commit history at the same time, which makes the branch visualization hard to read. \nFor example, here is what I get by following the command given here\n$ git log --graph --full-history --all --pretty=format:\"%h%x09%d%x20%s\"\n* 822458d (HEAD -> branch2) revision 5\n* 1057127 revision 4\n| * ae46e7e (branch1a) revision 3\n| * 39cd7e2 (branch1) revision 2\n| * 6802061 revision 1 \n|/ \n* f8c8522 (master) start\n\nWhile what I want is just the topology of the branches, without the commit historym i.e. something like this\nbranch2\n| branch1a\n| /\n| branch 1\n|/ \n(master)\n\nDo you guys know how to achieve this in git?\nThank you. \n\nA:\n\ngit log --all --decorate --oneline --graph --simplify-by-decoration\n\nThe --simplify-by-decoration option allows you to view only the big picture of the topology of the history, by omitting commits that are not referenced by tags. Commits are marked as !TREESAME (in other words, kept after history simplification rules described above) if (1) they are referenced by tags, or (2) they change the contents of the paths given on the command line. All other commits are marked as TREESAME (subject to be simplified away).\n\n"} +{"text": "Q:\n\nHOW TO Return value array on function php mysql\n\nHy I have code below,\nI wanna return value array with function :\n \";\n\n//script2\nfunction cart(){\n $array1= array();\n\n $fetch2 = mysqli_query($conn,\"SELECT * FROM orders_temp\");\n\n while ($r=mysqli_fetch_assoc($fetch2)) {\n $array1[] = $r[id_orders_temp];\n }\n return $array1;\n}\n\n$cart1 = cart();\necho \"script2 : \";\nprint_r($cart1);\n\n?>\n\nand the result :\nscript1: Array ( [0] => 150 [1] => 151 )\nscript2 : Array ( ) \n\nthere's no problem if I print_r array without function, but\nwhen I used function as above, I got blank array( ). \nHow can I get array value with function ?\n\nA:\n\nThe variable $conn is not defined within the function, so you need to either pass it to the function or reference the globally available $conn.\nPass in $conn\ninclude \"config/koneksi.php\";\n\nfunction cart($conn) {\n $identifiers = array();\n\n $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');\n\n while ($row = mysqli_fetch_assoc($result)) {\n $identifiers[] = $row['id_orders_temp'];\n }\n\n return $identifiers;\n}\n\n$cart = cart($conn);\n\nvar_dump($cart);\n\nReference global $conn\nIdeally, you should limit global state (and accessing it), so I would not recommend this.\ninclude \"config/koneksi.php\";\n\nfunction cart() {\n global $conn;\n\n $identifiers = array();\n\n $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');\n\n while ($row = mysqli_fetch_assoc($result)) {\n $identifiers[] = $row['id_orders_temp'];\n }\n\n return $identifiers;\n}\n\n$cart = cart();\n\nvar_dump($cart);\n\nNote I have renamed variables within cart() and optimized the SQL query to select only those columns actually required. \n\n"} +{"text": "Q:\n\nDatabase Connection Pooling (w/ Java)\n\nI would like to know your thoughts on whether this type of methodology could be practically implemented. I am very knew to database pooling, so forgive me for any misunderstandings. I have multiple classes calling a dbData class (which connects to a database and has helper functions, like frequently uses gets and updates and etc). I need to keep all the get and update functions in dbData class, but keep a pool of active connections I can re-use. Which means I will instantiate the dbData class multiple times, each time checking whether an appropriate connection exists, if not, create a new one and put it into the pool.\nMy question is this how and where you would store this pool. I could perhaps accomplish this if dbData would not be instantiated more than once and keeps one persistent pool object. But in my case, I have multiple dbData instances which should all connect to a single pool. I thought about serializing the pool object, but this seems ridiculous. Is this possible (what is shown in the pic)? It seems I am having trouble with the object-oriented part of this design.\nThe applications uses multithreading with Class1 and Class2.\nI would not like to use any external libraries if possible.\n\nA:\n\nIf it is a standalone app, then I would create a seperate service with a static collection that keeps the connection and does all the handling of those. Then the dbData class can call the static method to get a connection. The service then itself takes care of creating new connections if required. If your dbData instances are running in parallel you have to think about synchronized access (if required).\n\n"} +{"text": "Q:\n\nDynamically select catalog for Tomcat mysql connection pool in a Spring application\n\nI need to create a connection pool from a spring application running in a tomcat server.\nThis application has many catalogs, the main catalog (its is static) called 'db' has just one table with all existing catalog names and a boolean flag for the \"active\" one.\nWhen the application starts I need to choose from the main catalogs the active one, then I have to select it as default catalog.\nHow can I accomplish this?\nUntil now I used a custom class DataSourceSelector extends DriverManagerDataSource but now I need to improve the db connection using a pool, then I thought about a tomcat dbcp pool.\n\nA:\n\n@Configuration\npublic class DataAccessConfiguration {\n\n @Bean(destroyMethod = \"close\")\n public javax.sql.DataSource dataSource() {\n org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();\n ds.setDriverClassName(\"com.mysql.jdbc.Driver\");\n ds.setUrl(\"jdbc:mysql://localhost/db\");\n ds.setUsername(\"javauser\");\n ds.setPassword(\"\");\n ds.setInitialSize(5);\n ds.setMaxActive(10);\n ds.setMaxIdle(5);\n ds.setMinIdle(2);\n ds.get\n return ds;\n }\n\n}\n\n"} +{"text": "Q:\n\nReading very large fixed(ish) width format txt files from SQL Server Export into R data.tables or likewise\n\nI'm trying to read in (and eventually merge/link/manipulate) a series of large (~300M) and very large (~4G) fixed width files for eventual regressions, visualizations, etc., and am hitting some snags.\nFirst, the format of the files themselves is odd - I'm guessing something SQL-y. The file format is referenced here: \nhttps://msdn.microsoft.com/en-us/library/ms191479.aspx\n. It's fixed width, but the last column seems to (sometimes?) cut off with an \\r\\n before the full fixed width is experienced for that column. For reading it in I've tried laf_open_fwf and data.table::fread, but they both seem to get confused. A sample file and the associated non-XML format descriptor is here. I can't even get the thing to read in properly with that goofy last column. Here's a sample of the file:\n1 1 7 7 ER\n2 2 9 8 OI\n3 54016 1988006 1953409 OI \n4 54017 1988014 1953415 ER \n5 54017 1988014 1953415 OB \n\n(but note that the CR/LF are invisible here, and it's their odd placement that is the issue. See the above link to the .txt file or png file (which I can't link, low rep) of a notepad++ view of the data to demonstrate the problem with the field.)\nSecond, file size is an issue. I know I have a lot of table manipulation to do, so I'm tempted to look at data.table... but I also believe data.table stores the entire object in RAM, and that's going to be problematic. LaF or ffdf or sqlite seem like options, though I'm new to them, and would need to cope with this file format issue first.\nSome questions get at this general idea, suggesting LaF, ffbase or data.table are below...\nReading big data with fixed width\nQuickly reading very large tables as dataframes in R\nSpeed up import of fixed width format table in R\n... but none seems to (1) deal with this odd fixed-width-ish format or (2) move data eventually into data.tables, which seems like I'd like to try first. I thought about trying to open and rewrite them as well-formatted CSVs so data.table could handle them (my goofy hack through data.frames and back to csv feels ridiculous and unscalable, below). And the CSV export demonstates how confused the file gets, since the laf reader is strictly going by field length instead of adjusting based on where the /r/n is...\nCurrently I'm trying something like the below for starters. Help, if possible?\nrequire(\"data.table\", \"LaF\", \"ffbase\")\nsearchbasis.laf = laf_open_fwf(\"SEARCHBASIS.txt\",\n column_widths = c(12, 12, 12, 12, 10), \n column_names = c(\"SearchBasisID\", \"SearchID\", \"PersonID\", \"StopID\", \"Basis\"),\n column_types = rep(\"string\",5),\n trim = T)\n# ^ The laf_open_fwf quietly \"fails\" because the last column doesn't always \n# have 10 chars, but sometimes ends short with /r/n after the element.\nsearchbasis.dt = as.data.table(as.data.frame(laf_to_ffdf(searchbasis.laf)))\nwrite.csv(searchbasis.dt, file=\"SEARCHBASIS.csv\")\n# ^ To take a look at the file. Confirms that the read from laf, transfer \n# to data.table is failing because of the last column issue.\n\nA:\n\nFor this particular file:\nform <- read.table(\"SEARCHBASIS_format.txt\", as.is = TRUE, skip = 2)\nx <- read.table(\"SEARCHBASIS.txt\", col.names = form$V7, as.is = TRUE)\n\nIf you sometimes have strings including spaces you'll almost certainly need to process the file externally first.\nIf you're planning to read really large files I'd suggest (presuming you have awk on your path):\nx <- setNames(data.table::fread(\"awk '{$1=$1}1' SEARCHBASIS.txt\"), form$V7)\n\nIf you want to use fixed widths you could use:\nx <- setNames(fread(\"gawk 'BEGIN {OFS = \\\"\\t\\\"; FIELDWIDTHS = \\\"12 12 12 12 12\\\"} {for (i = 1; i<= NF; i++) {gsub(/ +$/, \\\"\\\", $i);}}1' SEARCHBASIS.txt\"), form$V7)\n\nYou can also pull the widths from the format file:\nx <- setNames(fread(paste0(\"gawk 'BEGIN {OFS = \\\"\\t\\\"; FIELDWIDTHS = \\\"\", paste(form$V4, collapse = \" \"), \"\\\"} {for (i = 1; i<= NF; i++) {gsub(/ +$/, \\\"\\\", $i);}}1' SEARCHBASIS.txt\")), form$V7)\n\nNote $1=$1 forces awk to reevaluate the fields and the 1 at the end is effectively shorthand for print. I've also assumed you want to strip trailing spaces from each field.\nOn Windows you'll need to use single quotes in R and replace the single quotes within the command with \" and the nested double quotes with \"\". So the last one above becomes:\nx <- setNames(fread(paste0('gawk \\\"BEGIN {OFS = \"\"\\t\"\"; FIELDWIDTHS = \"\"', paste(form$V4, collapse = \" \"), '\"\"} {for (i = 1; i<= NF; i++) {gsub(/ +$/, \"\"\"\", $i);}}1\" SEARCHBASIS.txt')), form$V7)\n\nFor a cross-platform solution, you'll need to put your awk script in an external file:\nstripSpace.awk\nBEGIN {OFS=\"\\t\"} {for (i = 1; i<= NF; i++) {gsub(/ +$/, \"\", $i);}}1\n\nR code\nx <- setNames(fread(paste0('gawk -v FIELDWIDTHS=\"', paste(form$V4, collapse = \" \"), '\" -f stripSpace.awk SEARCHBASIS.txt')), form$V7)\n\nTested on Scientific Linux 6 and Windows 8.1\n\n"} +{"text": "Q:\n\nDeclare matrix at file scope, dimensions from user input? C\n\nI have a program based on a matrix and need various functions to be able to access this matrix and it's dimensions, which I get from the user. I've managed to do it by passing them as arguments to each separate function, but that doesn't seem efficient.\nWhen I try to declare this:\nint lin, col;\nchar matrix[lin][col]; \n\nI get an error: variable length array declaration not allowed at file scope. I'm guessing it's because at that point, I haven't asked the user for 'lin' and 'col'? My question is: is there a way to make my matrix of variable dimensions have global scope? Or a way to access this matrix and dimensions without passing them as arguments to various functions?\n\nA:\n\nDo\nchar **matrix;\n\nRead rows r and columns c as input from the user.\nThen do :\n*matrix[c]=malloc(sizeof(matrix[r][c]); //You get contiguous memory here\n\nThen you access the matrix like matrix[x][y] , the same way you access a 2D array.\nAt the end of the day, clear the memory allocated :\nclear(matrix);\n\nOr a way to access this matrix and dimensions without passing them as\n arguments to various functions?\n\nWell, yes . You usually you pass the arguments like below :\nvoid print_matrix(char** matrix_copy,int rows,int cols)\n{\n//Access the matrix using matrix_copy[x][y] format\n}\n\nYou can just pass the matrix from main() like below :\nprint_matrix(matrix,r,c); // As simple as that.\n\nSince you don't need arguments you need a workaround which is simple.\nDeclare \nchar **matrix;\nint r,c; // rows & columns\n\noutside all the functions, so that they are accessible across the program.\nIn other words declare them in file scope. But in this case make sure that you access the matrix only after it is allocated some space using malloc.\n\n"} +{"text": "Q:\n\nWittgenstein criticizes Coffey's work 'The Science of Logic' in its assumption that every proposition requires a subject and a predicate. Why?\n\nWhy does Wittgenstein believe there can be propositions that lack a subject or predicate? What examples does Wittgenstein give in support of this belief? \n\nA:\n\nIn his review of Peter Coffey's book : The Science of Logic (1st ed 1912), published in The Cambridge Review, Vol.34, 1913, Wittgenstein criticizes it as a representative of \"old\" logic, precedent to the new mathematical logic of Frege, Peano and Russell [the first volume of Principia Mathematica by Alfred North Whitehead and Bertrand Russell was first published in 1910].\nSee Gottlob Frege, Begriffsschrift (1879), \u00a73:\n\nA distinction between subject and predicate does not occur in my way of representing a judgment. [...] We can imagine a language in which the proposition \"Archimedes perished at the capture of Syracuse\" would be expressed thus: \"The violent death of Archimedes at the capture of Syracuse is a fact\". To be sure, one can distinguish between subject and predicate here, too, if one wishes to do so, but the subject contains the whole content, and the predicate serves only to turn the content into a judgment. Such a language would have only a single predicate for all judgments, namely, \"is a fact\". We see that there cannot be any question here of subject and predicate in the ordinary \n sense. \n\nFor a reprint, see :\n\nLudwig Wittgenstein, Philosophical Occasions, 1912-1951 (1993), page 1.\n\n"} +{"text": "Q:\n\nHow can I change a showAnnotation zoom using mapbox for iOS?\n\nI have a method (seen below) which zooms into an annotation which was tapped. \nfunc mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {\n print(\"Tapped\")\n mapView.showAnnotations(pointAnnotations, animated: true)// this does the zooming\n mapView.deselectAnnotation(annotation, animated: false)\n}\n\nThis works, however, I dont like the way it zooms. (currently it, as soon as you tap, starts zooming then somewhat lagging behind it begins to center the object until it gets to the correct position. At which point it abruptly stops)\nHow Can I change this to emulate Snapmaps zoom? \nI believe what happens in their zoom is that the zoom begins a little after the centering begins and this all happens much faster. Additionally, the stopping is not as sudden. I believe Its like ease in thing. \n\nA:\n\nWhat I did is I used the following to make the zoom look much better. Check out here for more info and other versions of this zoom. \n let cam2 = mapView.cameraThatFitsShape(object.polyline!, direction: 0.0, edgePadding: .init(top: 20, left: 30, bottom: 100, right: 30))\n\n mapView.fly(to: cam2, withDuration: 0.25, completionHandler: nil)\n\n"} +{"text": "Q:\n\nWhy doesn't Postfix announce AUTH during EHLO?\n\nI have setup postfix and dovecot, I can even receive e-mails and pick them up remotely using Thunderbird client connecting via IMAP \nHowever, I can not send out using the Smtp server, when I telnet locally to my server using telnet mail.mydomain.com 25 and then perform ehlo mail.mydomain.com there is no 250-auth line - is this the problem and how do I fix it ?\nI have smtpd_sasl_auth_enable = yes in main.cf\n\nA:\n\nsmtpd_tls_auth_only = yes\n\nNeeded to change this to \nsmtpd_tls_auth_only = no\n\n"} +{"text": "Q:\n\nSplitting a grammar rule in Bison\n\nI have a Bison rule\nblock: LBRACE { some code } decls stmts RBRACE {more code } \n ;\n\nThe issue is in the \"more code\" section, I have \n$$ = $3 ;\n\nBasically, I want the return value of block to be stmts. When I do this, Bison says \"$3 of block has no type.\" If I remove the code block containing some code and stick it into the latter block, bison does not complain. I have stmts and all of its derivatives declared as types. So is this not allowed by Bison? I can make changes to the grammar to accommodate this, but it will be tedious and much easier to just use the above.\n\nA:\n\nUse $4 to refer to stmts. Since you have a mid-rule action, all proceeding symbol numbers are offset as the action itself can have a value.\nThe corresponding component numbers are:\n$1 LBRACE\n$2 { some code }\n$3 decls\n$4 stmts\n$5 RBRACE\n$6 { more code }\n\n"} +{"text": "Q:\n\ncall a function after directive is loaded\n\nI am working on custom directive of angular 1.6\nI want to call a function after my directive is loaded. Is there a way to achieve this?\nI tried link function, but it seems the link function is executed before the directive is loading.\nAny help will be appreciated.\nThis is my directive code\n\n\napp.directive(\"pagination\", [pagination]);\n\nfunction pagination() {\n return {\n restrict: 'EA',\n templateUrl: 'template/directives/pagination.html',\n scope: {\n totalData: '=',\n },\n link: dirPaginationControlsLinkFn\n };\n}\n\nA:\n\nSince you are using AngularJS V1.6, consider making the directive a component:\napp.component(\"pagination\", {\n templateUrl: 'template/directives/pagination.html',\n bindings: {\n totalData: '<',\n },\n controller: \"paginationCtrl\"\n})\n\nAnd use the $onChanges and $onInit life-cycle hooks:\napp.controller(\"paginationCtrl\", function() {\n this.$onChanges = function(changesObj) {\n if (changesObj.totalData) {\n console.log(changesObj.totalData.currentValue); \n console.log(changesObj.totalData.previousValue); \n console.log(changesObj.totalData.isFirstChange());\n };\n };\n this.$onInit = function() {\n //Code to execute after component loaded\n //...\n });\n});\n\nComponents are directives structured in a way that they can be automatically upgraded to Angular 2+ components. They make the migration to Angular 2+ easier.\nFor more information, see\n\nAngularJS Developer Guide - Components\nAngularJS 1.5+ Components do not support Watchers, what is the work around?\n\n"} +{"text": "Q:\n\nI have a sql table with only two columns, CODE and BALANCE, CODE is a name and Balance is a $ amount\n\nHow come when i try to print_r inside of this echo and div class it returns patient owes 1? \n $balance_out = sql::results(\"SELECT CODE,BALANCE FROM event.acs.ptbalance() WHERE CODE='$patient_id' and BALANCE > 0\");\n echo \"
Patient owes \".print_r($balance_out).\"
\";\n\nBut if i just print_r like this it gives me the array correctly.\necho \"
\"; print_r ($balance_out); echo \"
\"; \n\nlike so:\nArray\n(\n [0] => Array\n (\n [CODE] => ACSSCHAR00\n [BALANCE] => 24.33\n )\n\n)\n\nAny help would be greatly appreciated. Do i have to identify which array key value i want?\n\nA:\n\nYou can't concatenate print_r into a string like you are attempting, unless you pass a second param of true\nFor example \nprint_r($balance_out, true);\n\nOtherwise it returns true, which is interpreted by the string as 1\nYou may need to do something like this however, if you want to insert the patient balance into your HTML output\n \"
Patient owes \".$balance_out[0]['BALANCE'].\"
\";\n\n"} +{"text": "Q:\n\nConnecting to MongoDB from mongo shell and Robo 3T\n\nAll,\nI'm new to MongoDB and I was pulled into it when the vendor who setup our website left which means I'm learning everything from basic with a strong SQLServer DBA background.\nOn our Dev MongoDB V3.4.2 Windows installation, the vendor gave me a user named Monguser defined in admin with root as role and after they left I noticed Robo 3T as part of the installation.\nWhen I try to connect via the mongo shell as below, I get an error with the message \"Authentication failed\". C:>mongo --username monguser --password mongold!234. I tried connecting to it via the Robo 3T and I'm able to connect via the same login/password.\n\nAlso, I was asked to create a backup of a database and I tried the following but it failed with the error Server returned error on SASL authentication step: Authentication failed for database MiningDB\nC:\\mongodump --username monguser --password mongold!234 --dbMiningDB\nBut if I run C:\\mongodump --username monguser --password mongold!234 then it backs up all the databases in the installation without returning any error.\nIn both the cases, why am I getting the error? Any help will be deeply appreciated.\nThanks,\nrgn\n\nA:\n\nOK. From the below link I figured out that I need to include \"--authenticationDatabase admin\"\nReferred Link\n\n"} +{"text": "Q:\n\nHow does the naive Bayes classifier handle missing data in testing?\n\nAssume that a classier has been trained already (no missing training data), but a prediction has been requested based on an observation that does not include every feature. How can we handle this missing feature? \n\nA:\n\nIn evaluation (test) phase, when data point $x_n$ has $d$ missing features at indices $M=\\{m_1,...,m_d\\}$, corresponding terms $P(x_i|C_k),i \\in M$ are simply removed from the classifier. That is, classifier\n$$C(x_n) = \\underset{k \\in \\{1,..,K\\}}{\\mbox{argmax }}P(C_k)\\prod_{i}P(x_i=x_{n,i}|C_k)$$\nis replaced with\n$$C(x_n) = \\underset{k \\in \\{1,..,K\\}}{\\mbox{argmax }}P(C_k)\\prod_{\\color{blue}{i:i \\notin M}}P(x_i=x_{n,i}|C_k)$$\nwhere $i$ iterates over features, $x_{n,i}$ denotes the $i$-th feature of data point $n$, and there is $K$ classes in total.\n\n"} +{"text": "Q:\n\nRenaming a Word document and saving its filename with its first 10 letters\n\nI have recovered some Word documents from a corrupted hard drive using a piece of software called photorec. The problem is that the documents' names can't be recovered; they are all renamed by a sequence of numbers. There are over 2000 documents to sort through and I was wondering if I could rename them using some automated process.\nIs there a script I could use to find the first 10 letters in the document and rename it with that? It would have to be able to cope with multiple documents having the same first 10 letters and so not write over documents with the same name. Also, it would have to avoid renaming the document with illegal characters (such as '?', '*', '/', etc.)\nI only have a little bit of experience with Python, C, and even less with bash programming in Linux, so bear with me if I don't know exactly what I'm doing if I have to write a new script.\n\nA:\n\nHow about VBScript? Here is a sketch:\nFolderName = \"C:\\Docs\\\"\nSet fs = CreateObject(\"Scripting.FileSystemObject\")\n\nSet fldr = fs.GetFolder(Foldername)\n\nSet ws = CreateObject(\"Word.Application\")\n\nFor Each f In fldr.Files\n If Left(f.name,2)<>\"~$\" Then\n If InStr(f.Type, \"Microsoft Word\") Then\n\n MsgBox f.Name\n\n Set doc = ws.Documents.Open(Foldername & f.Name)\n s = vbNullString\n i = 1\n Do While Trim(s) = vbNullString And i <= doc.Paragraphs.Count\n s = doc.Paragraphs(i)\n s = CleanString(Left(s, 10))\n i = i + 1\n Loop\n\n doc.Close False\n\n If s = \"\" Then s = \"NoParas\"\n s1 = s\n i = 1\n Do While fs.FileExists(s1)\n s1 = s & i\n i = i + 1\n Loop\n\n MsgBox \"Name \" & Foldername & f.Name & \" As \" & Foldername & s1 _\n & Right(f.Name, InStrRev(f.Name, \".\"))\n '' This uses copy, because it seems safer\n\n f.Copy Foldername & s1 & Right(f.Name, InStrRev(f.Name, \".\")), False\n\n '' MoveFile will copy the file:\n '' fs.MoveFile Foldername & f.Name, Foldername & s1 _\n '' & Right(f.Name, InStrRev(f.Name, \".\"))\n\n End If\n End If\nNext\n\nmsgbox \"Done\"\nws.Quit\nSet ws = Nothing\nSet fs = Nothing\n\nFunction CleanString(StringToClean)\n''http://msdn.microsoft.com/en-us/library/ms974570.aspx\nDim objRegEx \nSet objRegEx = CreateObject(\"VBScript.RegExp\")\nobjRegEx.IgnoreCase = True\nobjRegEx.Global = True\n\n''Find anything not a-z, 0-9\nobjRegEx.Pattern = \"[^a-z0-9]\"\n\nCleanString = objRegEx.Replace(StringToClean, \"\")\nEnd Function\n\n"} +{"text": "Q:\n\nDebugging into external libraries in QtCreator\n\nI have been using Qt Creator to develop some Qt apps recently with no problems. This week I started to use Qt Creator to work on an Open Scene Graph application. I have all of the source (.cpp and .h) files for Open Scene Graph and used those to build the libraries. \nI then created a new project and linked those libraries into my project through the .pro file. My application works and runs, I can debug but not step into the code from the Open Scene Graph libraries. \nHow can I set up Qt Creator to step through these source files or even break at breakpoints within the source code of these libraries?\nIn Tools -> Options -> Debugger, there is Source Paths Mapping which may be what I'm after but I'm not sure.\nThanks.\n\nA:\n\nI assume since you can link a debug version of your app with OSG and you can't trace into OSG source code that you're using gcc (because with Visual C++ I don't think it's possible to link debug apps with non-debug libs) If that's the case, you simply need to re-build OSG for debugging. There may be an option when you run OSG's 'configure' or you may have to edit the Makefiles. Or if it's CMake-based, you run cmake with -DCMAKE_BUILD_TYPE=Debug.\n\n"} +{"text": "Q:\n\nWhy code contracts can be added and removed for postconditions and object invariants, but not for preconditions in C#?\n\nWhy code contracts can be added and removed for postconditions and object invariants, but not for preconditions in C#?\nIn the CLR via C# book I met the following excerpt:\n\nAnd since a contract cannot be made stricter with new versions (without breaking compatibility), you\n should carefully consider preconditions when introducing a new virtual, abstract, or interface member.\n For postconditions and object invariants, contracts can be added and removed at will as the conditions\n expressed in the virtual/abstract/interface member and the conditions expressed in the overriding\n member are just logically AND-ed together.\n\nThat is very confusing for me that postconditions and object invariants, contracts can be added and removed at will. I would expect a suggestion that the postconditions and object invariants can become only stricter as well as the preconditions. Why am I expecting this? Because I can come up with an example where the suggestion proves wrong. E.g.\nAt first we had a postcondition and everything worked just fine:\nusing System.Diagnostics.Contracts;\n\npublic sealed class Program\n{\n public static void FooBaseContract(int i) \n {\n Contract.Ensures(i > 0);\n }\n}\n\npublic class FooBase \n{\n public virtual int i \n {\n get {return 2;} \n }\n}\npublic class FooDerived : FooBase\n{\n public override int i \n {\n get {return 4;} \n }\n}\n\nNow we decide to make the postcondition stricter:\nusing System.Diagnostics.Contracts;\n\npublic sealed class Program\n{\n public static void FooBaseContract(int i) \n {\n Contract.Ensures(i > 4);\n }\n}\n\npublic class FooBase \n{\n public virtual int i \n {\n get {return 2;} \n }\n}\npublic class FooDerived : FooBase\n{\n public override int i \n {\n get {return 4;} \n }\n}\n\nThat definitely makes the code which worked with the previous postcondition incompatible with the new postcondition. That means that we lose the backward compatibility by making the postconditions stricter.\nAlso, I am not getting why the author refers only the virtual, abstract, or interface member. Because in the contrived example I gave above the incompatibility with the new code contract version will happen even if I change code to the following (remove all virtual, abstract, or interface member):\nusing System.Diagnostics.Contracts;\n\npublic sealed class Program\n{\n public static void FooBaseContract(int i) \n {\n Contract.Ensures(i > 4);\n }\n}\n\npublic class FooBase \n{\n public int i \n {\n get {return 2;} \n }\n}\n\nSo, could someone explain in a foolproof manner what am I missing here, please?\nUPDATE\nAs was mentioned in the comments section - the code contracts is a deprecated concept. That is ok for me, I just would like to understand the idea - in this case it is why can we make the postconditions and object invariants stricter? It contradicts with my common sense, meaning that something was allowed to be returned previously (or take place for object invariants) and now we state that that something is not allowed any more and the author of the book tells that such a case is not breaking a backward compatibility.\n\nA:\n\nThe text says that the conditions are \"anded\" together. This means that you simply do not have the ability to remove postconditions and invariants. You can only add them regardless of how you write the code.\nPostconditions and invariants are things that must be ensured on exit. It makes sense to be able to add obligations. If you are adding a contradiction then CC should flag that as a postcondition violation.\nFrom a compatibility and extensibility standpoint, users of the base class will receive the guarantees they expect. They might receive additional guarantees that they don't know or care about.\n\n"} +{"text": "Q:\n\nWhy C# compiler generates single class to capture variables of several lambdas?\n\nAssume we have such code:\npublic class Observer\n{\n public event EventHandler X = delegate { };\n}\n\npublic class Receiver\n{\n public void Method(object o) {}\n}\n\npublic class Program\n{\n public static void DoSomething(object a, object b, Observer observer, Receiver r)\n {\n var rCopy = r;\n EventHandler action1 = (s, e) => rCopy.Method(a);\n EventHandler action2 = (s, e) => r.Method(b);\n observer.X += action1;\n observer.X += action2;\n }\n\n public static void Main(string[] args)\n {\n var observer = new Observer();\n var receiver = new Receiver();\n DoSomething(new object(), new object(), observer, receiver);\n }\n}\n\nHere action1 and action2 have completely separated set of captured variables - rCopy was created especially for this. Still, compiler generates just one class to capture everything (checked generated IL). I suppose it is done for optimization reasons, but it allows very hard-to-spot memory leak bugs: if a and b captured in single class, GC is unable to collect both at least so long as any of lambdas are referenced.\nIs there a way to convince compiler to produce two different capture classes? Or any reason why it cannot be done?\nP.S. Somewhat more detailed, in my blog: here and here.\n\nA:\n\nYou have rediscovered a known shortcoming in the implementation of anonymous functions in C#. I described the problem in my blog in 2007.\n\nIs there a way to convince compiler to produce two different capture classes? \n\nNo. \n\nOr any reason why it cannot be done?\n\nThere is no theoretical reason why an improved algorithm for partitioning closed-over variables so that they are hoisted into different closure classes could not be devised. We have not done so for practical reasons: the algorithm is complicated, expensive to get right and expensive to test, and we have always had higher priorities. Hopefully that will change in Roslyn, but we are making no guarantees.\n\nA:\n\nI'm fairly sure you are seeing practical limitations in the compiler's code rewriting logic, it is not simple to do. The workaround is easy enough, create the lambda in a separate method so you get two separate instances of the hidden class:\npublic static void DoSomething(object a, object b, Observer observer, Receiver r) {\n var rCopy = r;\n observer.X += register(r, a);\n observer.X += register(rCopy, b);\n}\nprivate static EventHandler register(Receiver r, object obj) {\n return new EventHandler((s, e) => r.Method(obj));\n}\n\n"} +{"text": "Q:\n\nLength Contraction And Simultaneity\n\nI wanted to derive length contraction from the Lorentz transformation, but I keep getting stuck on problems with simultaneity in my derivation. At some point, I came across Wikipedia's article on Length Contraction where, in the section labeled \"Derivation\", it states\n\nIn an inertial reference frame $S^\\prime$, $x_1^{\\prime}$ and\n $x_2^{\\prime}$ shall denote the endpoints for an object of length\n $L_0^\\prime$ at rest in this system. The coordinates in $S^\\prime$ are\n connected to those in $S$ by the Lorentz transformations as follows:\n$ x_1^{\\prime} = \\frac{x_1-vt_1}{\\sqrt{1-\\frac{v^2}{c^2}}} $ and $\n x_2^{\\prime} = \\frac{x_2-vt_2}{\\sqrt{1-\\frac{v^2}{c^2}}} $\nAs this object is moving in $S$, its length $L$ has to be measured\n according to the above convention by determining the simultaneous\n positions of its endpoints, so we have to put $t_1=t_2$. Because\n $L=x_2-x_1$ and $L_0^\\prime=x_2^\\prime-x_1^\\prime$, we obtain\n$ L_0^{\\prime} = \\frac{L}{\\sqrt{1-\\frac{v^2}{c^2}}}. $\n\nI understand everything except for the line which reads $L_0^\\prime=x_2^\\prime-x_1^\\prime.$ After setting $t_1=t_2$, it is possible to write $L=x_2-x_1,$ since events $1$ and $2$ are simultaneous. However, in the primed inertial reference frame, which is moving with a nonzero velocity with respect to the laboratory frame, the events are not simultaneous. Therefore, how can it be that $ L_0^\\prime=x_2^\\prime-x_1^\\prime, $ since $ t_1^\\prime \\neq t_2^\\prime? $\n\nA:\n\nYou just confused the frames. In the derivation, $S'$ is the rest frame of the object of length $L'_0=x'_2-x'_1$. In that rest frame, the endpoints are simply at coordinates $x'_1$ and $x'_2$, regardless of $t'$. The length $L'_0$ in that rest frame is measured as the distance between two simultaneous events in that frame, i.e. events with $t'_1=t'_2$, and the result is, once again, $L'_0=x'_2-x'_1$. The world lines of both end points are vertical in that frame. Simple.\nWe want to know how this object looks like in another frame, $S$, which is moving relatively to $S'$. To measure the length $L_0$ in $S$, we have to see both endpoints simultaneously in $S$ i.e. impose $t_1=t_2$. That's exactly what they did and derived that in the frame $S$ where the object is moving, the length is measured to be $L_0 = L'_0 \\cdot \\sqrt{1-v^2/c^2}$. It is Lorentz-contracted.\nTheir derivation may have unnaturally exchanged various things, $S$ with $S'$, and they wrote the final relationship in the inverted way so that it looks like a \"length dilatation\", but the actual content of the derivation is right given their conventions.\n\n"} +{"text": "Q:\n\nIf $\\Sigma$ is finitely satisfiable, can both $\\Sigma \\cup \\{ \\phi\\}$ and $\\Sigma \\cup \\{ \\neg \\phi\\}$ be finitely satisfiable?\n\nIn propositional logic, if $\\Sigma$ is finitely satisfiable, can both $\\Sigma \\cup \\{ \\phi\\}$ and $\\Sigma \\cup \\{ \\neg \\phi\\}$ be finitely satisfiable?\nI proved that at least one of $\\Sigma \\cup \\{ \\phi\\}$ and $\\Sigma \\cup \\{ \\neg \\phi\\}$ must be finitely satisfiable, but could both be?\n\nA:\n\nOf course both are satisfiable:\nRecall that a set of sentences $S$ is complete if, for every sentence $\\varphi$, either $S \\vdash \\varphi$ or $S \\vdash \\neg \\varphi$.\nAll we need to show is that not every finite satisfiable set is complete. That is, as observed in the comments, it suffices give a counterexample of an incomplete finite satisfiable set. And for any signature you have, there are certainly many of them:\n\n$\\emptyset$ is (vacuously) finite satisfiable, but incomplete.\n$\\{\\alpha\\}$ is finite satisfiable, but incomplete.\n$\\{\\alpha, \\alpha\\rightarrow \\alpha\\}$ is finite satisfiable, but incomplete and so on\n\nFor any arbitrary sentences $\\alpha, \\beta$ of your language.\n\n"} +{"text": "Q:\n\nDebian GNU/Linux 9 (stretch) 64-bit doesn`t detect wireless\n\nI can`t use my wi-fi on my dual boot laptop. In Windows it works perfectly, but in Debian it not.\n> ip a:\n1: lo: mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1\nlink/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00\ninet 127.0.0.1/8 scope host lo\n valid_lft forever preferred_lft forever\ninet6 ::1/128 scope host \n valid_lft forever preferred_lft forever\n2: enp4s0: mtu 1500 qdisc pfifo_fast state UP group default qlen 1000\nlink/ether 18:31:bf:74:90:24 brd ff:ff:ff:ff:ff:ff\ninet 192.168.31.220/24 brd 192.168.31.255 scope global dynamic enp4s0\n valid_lft 42027sec preferred_lft 42027sec\ninet6 fe80::1a31:bfff:fe74:9024/64 scope link \n valid_lft forever preferred_lft forever\n\n> lsusb:\nBus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub\nBus 001 Device 005: ID 8087:0a2b Intel Corp. \nBus 001 Device 004: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card \nReader Controller\nBus 001 Device 003: ID 04f2:b57a Chicony Electronics Co., Ltd \nBus 001 Device 002: ID 046d:c077 Logitech, Inc. M105 Optical Mouse\nBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub\n\n> lspci:\n00:00.0 Host bridge: Intel Corporation Device 5910 (rev 05)\n00:01.0 PCI bridge: Intel Corporation Skylake PCIe Controller (x16) (rev 05)\n00:02.0 VGA compatible controller: Intel Corporation Device 591b (rev 04)\n00:04.0 Signal processing controller: Intel Corporation Skylake Processor Thermal Subsystem (rev 05)\n00:14.0 USB controller: Intel Corporation Sunrise Point-H USB 3.0 xHCI Controller (rev 31)\n00:14.2 Signal processing controller: Intel Corporation Sunrise Point-H Thermal subsystem (rev 31)\n00:15.0 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO I2C Controller #0 (rev 31)\n00:15.1 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO I2C Controller #1 (rev 31)\n00:16.0 Communication controller: Intel Corporation Sunrise Point-H CSME HECI #1 (rev 31)\n00:17.0 RAID bus controller: Intel Corporation 82801 Mobile SATA Controller [RAID mode] (rev 31)\n00:1c.0 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #1 (rev f1)\n00:1c.2 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #3 (rev f1)\n00:1c.3 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #4 (rev f1)\n00:1e.0 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO UART #0 (rev 31)\n00:1e.2 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO SPI #0 (rev 31)\n00:1f.0 ISA bridge: Intel Corporation Sunrise Point-H LPC Controller (rev 31)\n00:1f.2 Memory controller: Intel Corporation Sunrise Point-H PMC (rev 31)\n00:1f.3 Audio device: Intel Corporation Device a171 (rev 31)\n00:1f.4 SMBus: Intel Corporation Sunrise Point-H SMBus (rev 31)\n01:00.0 3D controller: NVIDIA Corporation Device 1c8d (rev ff)\n03:00.0 Network controller: Intel Corporation Device 24fd (rev 78)\n04:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 15)\n\n> lspci -knn | grep Net -A2:\n03:00.0 Network controller [0280]: Intel Corporation Device [8086:24fd] (rev 78)\nSubsystem: Intel Corporation Device [8086:0010]\nKernel modules: iwlwifi\n\nA:\n\nAs sudo, do the following:\ncat \"deb http://httpredir.debian.org/debian/ stretch main contrib non-free\" >> /etc/apt/sources.list\napt-get update\napt-get install firmware-iwlwifi\nmodprobe -r iwlwifi\nmodprobe iwlwifi\n\nIt should work now. \n\n"} +{"text": "Q:\n\nSSDT/SSRS - Report Previewer Won't Run\n\nI'm having a very peculiar issue with SQL Server Data Tools 2012. Whenever I attempt to launch the report previewer, I get the following exception:\n\nThere was no endpoint listening at net.pipe://localhost/PreviewProcessingServce7324/ReportProcessing that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more deatils.\n\nAs far as I can tell, nothing I did triggered the issue. It just started happening one day when I fired up SSDT. I tried the suggestion on \nReport Designer Preview in SSDT throws up a 'end point' not found error. \nHowever, my service is up and running just fine (restarting it didn't help), and using Setspn didn't do anything for it, either. \nAnyone have any ideas?\n\nA:\n\nThat is a current bug in SSDT-BI. The current workaround for now is to right click on the report you want to preview in your Solution Explorer and click RUN. \nYou will also notice that if you try to preview the report for the first time a command prompt window opens up that runs the preview process, If you don't close this window and just minimize it then you can preview the report but I think the RUN method is much easier for now. Please mark as answer if this helped.\n\nA:\n\nThis can happen when you have some SQL Services installed and running on your machine that interfere with the Report Preview. You can check your current services by going opening Sql Server Configuration Manager:\n\nTo fix this you can do the following:\n\nType WinKey + R, input services.msc in the Run box, and press Enter.\nFind the \"Net.Pipe Listener Adapter\" and either Restart or Disable it.\n\nThe workaround, as SQLnbe mentioned, is to:\n\nRight Click the RDLC file from solution explorer\nClick \"Run\" from there which will open up a new window.\n\n"} +{"text": "Q:\n\nTablesorter and date mm/yyyyy\n\nI've been using tablesorter a lot in my website like this\n$(\".tablesorter\").tablesorter({\n widgets: ['zebra'], \n dateFormat: 'uk', \n});\n\nBut i've a problem with date in the format : MM/YYYY (it's when I don't have the day I prefer showing 12/2005 than 00/12/2005).\nThis format does not work with tablesorter dateFormat uk. How to make it working ?\nAnd the difficulty is that I can have in the same table differents formats like this : \nDate - Title\n11/2005 - Movie 1\n12/11/2005 - Movie 2\n2006 - Movie 3\n\nThank you.\n\nA:\n\nYou could add a custom parser:\n$.tablesorter.addParser({ \n id: 'rough-date', \n is: function() { \n // return false so this parser is not auto detected \n return false; \n }, \n format: function(s) { \n // format to look like an ISO 8601 date (2005-11-12).\n // Month-only dates will be formatted 2005-11.\n return s.split('/').reverse().join('-');\n }, \n type: 'text' // sort as strings\n});\n\nAnd then use it like this (where 0 is the column number that contains the date):\n$(\".tablesorter\").tablesorter({ \n headers: { \n 0: {\n sorter:'rough-date' \n } \n } \n});\n\nHere's a JSFiddle.\n\n"} +{"text": "Q:\n\nfor example \"party:\u30d1\u30fc\u30c6\u30a3\u30fc\",how to type \"\u30fc\"\n\n\"party:\u30d1\u30fc\u30c6\u30a3\u30fc\",how to type \"\u30fc\" in the computer\n\nA:\n\nFor all IMEs I'm aware of, typing a \"-\" results in a \"\u30fc\".\nIf you're using the Windows IME, there are various tips on this site which you might be interested in.\n\n"} +{"text": "Q:\n\nImage value was null when posted to controller\n\nin controller image comes null i tried this code but it did not work\nfunction bindForm(dialog) {\n\n$(\"form\", dialog).submit(function () {\n var formdata = new FormData($('form').get(0));\n $.ajax({\n url: \"/Books/Create\",\n type: \"POST\",\n dataType: \"JSON\",\n data: formData,\n contentType: false,\n processData: false,\n success: function (result) {\n if (result.success) {\n $(\"#myModal\").modal(\"hide\");\n location.reload();\n } else {\n $(\"#myModalContent\").html(result);\n bindForm();\n }\n }\n });\n return false;\n});\n}\n\nA:\n\n$(function () {\n\n $.ajaxSetup({ cache: false });\n\n $(\"a[data-modal]\").on(\"click\", function (e) {\n $(\"#myModalContent\").load(this.href, function () {\n \n\n $(\"#myModal\").modal({\n keyboard: true\n }, \"show\");\n\n bindForm(this);\n });\n\n return false;\n });\n});\n\nfunction bindForm(dialog) {\n \n $(\"#crtForm\", dialog).submit(function () {\n var myform = document.getElementById(\"crtForm\");\n var fdata = new FormData(myform);\n $.ajax({\n url: this.action,\n data: fdata,\n cache: false,\n processData: false,\n contentType: false,\n type: \"POST\",\n success: function (result) {\n if (result.success) {\n $(\"#myModal\").modal(\"hide\");\n location.reload();\n } else {\n $(\"#myModalContent\").html(result);\n bindForm();\n }\n }\n });\n return false;\n });\n}\n\n"} +{"text": "Q:\n\nRewrite file with 0's. What am I doing wrong?\n\nI want rewrite file with 0's. It only write a few bytes. \nMy code:\nint fileSize = boost::filesystem::file_size(filePath);\n\nint zeros[fileSize] = { 0 };\n\nboost::filesystem::path rewriteFilePath{filePath};\nboost::filesystem::ofstream rewriteFile{rewriteFilePath, std::ios::trunc};\nrewriteFile << zeros;\n\nAlso... Is this enough to shred the file? What should I do next to make the file unrecoverable? \nEDIT: Ok. I rewrited my code to this. Is this code ok to do this?\nint fileSize = boost::filesystem::file_size(filePath);\n\nboost::filesystem::path rewriteFilePath{filePath};\nboost::filesystem::ofstream rewriteFile{rewriteFilePath, std::ios::trunc};\n\nfor(int i = 0; i < fileSize; i++) {\n rewriteFile << 0;\n}\n\nA:\n\nThere are several problems with your code.\n\nint zeros[fileSize] = { 0 };\nYou are creating an array that is sizeof(int) * fileSize bytes in size. For what you are attempting, you need an array that is fileSize bytes in size instead. So you need to use a 1-byte data type, like (unsigned) char or uint8_t.\nBut, more importantly, since the value of fileSize is not known until runtime, this type of array is known as a \"Variable Length Array\" (VLA), which is a non-standard feature in C++. Use std::vector instead if you need a dynamically allocated array.\nboost::filesystem::ofstream rewriteFile{rewriteFilePath, std::ios::trunc};\nThe trunc flag truncates the size of an existing file to 0. What that entails is to update the file's metadata to reset its tracked byte size, and to mark all of the file's used disk sectors as available for reuse. The actual file bytes stored in those sectors are not wiped out until overwritten as sectors get reused over time. But any bytes you subsequently write to the truncated file are not guaranteed to (and likely will not) overwrite the old bytes on disk. So, do not truncate the file at all.\nrewriteFile << zeros;\nofstream does not have an operator<< that takes an int[], or even an int*, as input. But it does have an operator<< that takes a void* as input (to output the value of the memory address being pointed at). An array decays into a pointer to the first element, and void* accepts any pointer. This is why only a few bytes are being written. You need to use ofstream::write() instead to write the array to file, and be sure to open the file with the binary flag.\n\nTry this instead:\nint fileSize = boost::filesystem::file_size(filePath);\n\nstd::vector zeros(fileSize, 0);\n\nboost::filesystem::path rewriteFilePath(filePath);\nboost::filesystem::ofstream rewriteFile(rewriteFilePath, std::ios::binary);\nrewriteFile.write(zeros.data()/*&zeros[0]*/, fileSize);\n\nThat being said, you don't need a dynamically allocated array at all, let alone one that is allocated to the full size of the file. That is just a waste of heap memory, especially for large files. You can do this instead:\nint fileSize = boost::filesystem::file_size(filePath);\n\nconst char zeros[1024] = {0}; // adjust size as desired...\n\nboost::filesystem::path rewriteFilePath(filePath);\nboost::filesystem::ofstream rewriteFile(rewriteFilePath, std::ios::binary);\n\nint loops = fileSize / sizeof(zeros);\nfor(int i = 0; i < loops; ++i) {\n rewriteFile.write(zeros, sizeof(zeros));\n}\nrewriteFile.write(zeros, fileSize % sizeof(zeros));\n\nAlternatively, if you open a memory-mapped view of the file (MapViewOfFile() on Windows, mmap() on Linux, etc) then you can simply use std::copy() or std::memset() to zero out the bytes of the entire file directly on disk without using an array at all.\n\nAlso... Is this enough to shred the file?\n\nNot really, no. At the physical hardware layer, overwriting the file just one time with zeros can still leave behind remnant signals in the disk sectors, which can be recovered with sufficient tools. You should overwrite the file multiple times, with varying types of random data, not just zeros. That will more thoroughly scramble the signals in the sectors.\n\n"} +{"text": "Q:\n\nCAKEPHP - MSSQL Error When Filtering Records by Distant Association\n\nSo I'm a bit stuck on the above and I keep getting an sql server error. Yes I'm using mssql server :| - not my database.\nA little background, my relationships concerned look like this:\nAssetMaintenanceRecord->(belongs to)->Asset->(belongs to)->Project->(has one)->ProjectManager\n(note ProjectManager is like an alias model for a personnel table. The project table has an id for ProjectManager which is just the personnel id.\nSo I'm trying to do a simple filter whereby I select all the AssetMaintenanceRecords by a search on ProjectManager.\nThe related index function in AssetMaintenanceRecordsController.php looks like:\npublic function index() {\n $conditions = NULL;\n if (isset($this->params['url']['report']) && $this->params['url']['report'] == 'open') {\n $conditions[] = array('CompletedDate' => NULL);\n }\n\n if (isset($this->params['url']['report']) && $this->params['url']['report'] == 'notified') {\n $conditions[] = array('NotifiedDate BETWEEN ? AND ?' => array(date('M d Y g:iA', strtotime($this->params['url']['datefrom'])), date('M d Y g:iA', strtotime($this->params['url']['dateto']))));\n }\n\n if (isset($this->params['url']['report']) && $this->params['url']['report'] == 'completed') {\n $conditions[] = array('CompletedDate BETWEEN ? AND ?' => array(date('M d Y g:iA', strtotime($this->params['url']['datefrom'])), date('M d Y g:iA', strtotime($this->params['url']['dateto']))));\n }\n\n if (isset($this->params['url']['project'])) {\n $conditions[] = array('Asset.aCurrProject' => $this->params['url']['project']);\n }\n\n if (isset($this->params['url']['ptCode']) && $this->params['url']['ptCode'] != NULL) {\n $conditions[] = array('Asset.ptCode' => $this->params['url']['ptCode']);\n }\n\n if (isset($this->params['url']['asset']) && $this->params['url']['asset'] != NULL) {\n $conditions[] = array('Asset.aFullCode' => $this->params['url']['asset']);\n }\n\n if (isset($this->params['url']['pm']) && $this->params['url']['pm'] != NULL) {\n $pm_search_terms = explode(' ', $this->params['url']['pm']);\n foreach($pm_search_terms as $pm_search_term) {\n $conditions[] = array(\n 'OR' => array(\n 'ProjectManager.PerGivenName LIKE' =>'%'.$pm_search_term.'%',\n 'ProjectManager.PerSurname LIKE' =>'%'.$pm_search_term.'%',\n )\n );\n }\n }\n\n $this->paginate['AssetMaintenanceRecord'] = array(\n 'contain' => array(\n 'Asset' => array(\n 'Project' => array(\n 'ProjectManager'\n ))\n ),\n 'order' => 'CompletedDate ASC',\n 'limit' => 10\n );\n\n $planttype = $this->AssetMaintenanceRecord->Asset->PlantType->find('list');\n $this->set(compact('planttype'));\n $this->AssetMaintenanceRecord->recursive = -1;\n $this->set('records', $this->paginate('AssetMaintenanceRecord', $conditions));\n }\n\nWithout the ProjectManager filter it works fine and I can echo out the ProjectManager array etc. but when I enter in a search term I get this error:\n\nThe multi-part identifier \"ProjectManager.PerSurname\" could not be bound.\n\nThe executed sql looks like:\n'SELECT TOP 10 [AssetMaintenanceRecord].[MtceRegID] AS [AssetMaintenanceRecord_0], [AssetMaintenanceRecord].[AssetID] AS [AssetMaintenanceRecord_1], CAST(CAST([AssetMaintenanceRecord].[MtceRegNote] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_2], [AssetMaintenanceRecord].[POno] AS [AssetMaintenanceRecord_3], CAST(CAST([AssetMaintenanceRecord].[NotifiedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_4], CAST(CAST([AssetMaintenanceRecord].[CompletedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_5], [AssetMaintenanceRecord].[MtceRegTitle] AS [AssetMaintenanceRecord_6], CAST(CAST([AssetMaintenanceRecord].[CreatedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_7], [AssetMaintenanceRecord].[CreatedUserID] AS [AssetMaintenanceRecord_8], CAST(CAST([AssetMaintenanceRecord].[ModifiedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_9], [AssetMaintenanceRecord].[ModifiedUserID] AS [AssetMaintenanceRecord_10], [Asset].[aID] AS [Asset_11], [Asset].[ptCode] AS [Asset_12], [Asset].[aNo] AS [Asset_13], [Asset].[aFullCode] AS [Asset_14], [Asset].[aDesc] AS [Asset_15], [Asset].[aMake] AS [Asset_16], [Asset].[aModel] AS [Asset_17], [Asset].[aSerialNo] AS [Asset_18], [Asset].[aRegNo] AS [Asset_19], CAST(CAST([Asset].[aRegExpDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_20], [Asset].[aActive] AS [Asset_21], [Asset].[aIncAssetRpt] AS [Asset_22], [Asset].[aIncFinanceRpt] AS [Asset_23], [Asset].[aIsTrailer] AS [Asset_24], [Asset].[aIsSurveyEquip] AS [Asset_25], [Asset].[aCostedItem] AS [Asset_26], [Asset].[aCostedPeriod] AS [Asset_27], [Asset].[aWarrantyPeriod] AS [Asset_28], [Asset].[aPONo] AS [Asset_29], CAST(CAST([Asset].[aPODate] AS VARCHAR(8000)) AS TEXT) AS [Asset_30], CAST(CAST([Asset].[aPOCostExGst] AS VARCHAR(8000)) AS TEXT) AS [Asset_31], [Asset].[aQtyStock] AS [Asset_32], [Asset].[aQtyInUse] AS [Asset_33], [Asset].[aCurrProject] AS [Asset_34], [Asset].[aCurrOperator] AS [Asset_35], [Asset].[aStolen] AS [Asset_36], CAST(CAST([Asset].[aStolenDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_37], [Asset].[aWO] AS [Asset_38], CAST(CAST([Asset].[aWODate] AS VARCHAR(8000)) AS TEXT) AS [Asset_39], [Asset].[aSold] AS [Asset_40], CAST(CAST([Asset].[aSoldDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_41], CAST(CAST([Asset].[aSoldPrice] AS VARCHAR(8000)) AS TEXT) AS [Asset_42], CAST(CAST([Asset].[aNotes] AS VARCHAR(8000)) AS TEXT) AS [Asset_43], CAST(CAST([Asset].[LastModDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_44], CAST(CAST([Asset].[CreatedDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_45], [Asset].[aCat] AS [Asset_46], [Asset].[aPoliceRptNo] AS [Asset_47], [Asset].[aRelatedAssetID] AS [Asset_48], [Asset].[aRelatedAssetFullCode] AS [Asset_49], [Asset].[aPayMethod] AS [Asset_50], [Asset].[aInvoiceNo] AS [Asset_51], CAST(CAST([Asset].[aLastFuelDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_52], [Asset].[aFuelType] AS [Asset_53] FROM [tbMtceRegister] AS [AssetMaintenanceRecord] LEFT JOIN [tbAsset] AS [Asset] ON ([AssetMaintenanceRecord].[AssetID] = [Asset].[aID]) WHERE [CompletedDate] IS NULL AND [Asset].[aCurrProject] IS NULL AND (([ProjectManager].[PerGivenName] LIKE '%test%') OR ([ProjectManager].[PerSurname] LIKE '%test%')) ORDER BY [CompletedDate] ASC'\nLooks ok to me but I'm obviously going wrong somwhere?\nAny help appreciated.\nThanks in advance.\n\nA:\n\nProjectManager is not contained in FROM or JOIN Part \nbut used in WHERE : OR ([ProjectManager].[PerSurname] LIKE\n\n"} +{"text": "Q:\n\nMocking interfaces in DUnit with Delphi-Mocks and Spring4D\n\nSo, I am getting Access Violation error when try to Mock 2-nd composite interface, below examples of code with using Delphi-Mocks and Spring4D frameworks\nunit u_DB;\ntype\n TDBObject = class\n public\n property ID: TGUID;\n end;\n\n TDBCRM = class(TDBObject)\n public\n property SOME_FIELD: TSomeType;\n end;\n\nunit i_dmServer;\ntype\n {$M+}\n IdmServer = interface\n ['{A4475441-9651-4956-8310-16FB710EAE5E}']\n function GetServiceConnection: TServiceConnection;\n function GetCurrentUser(): TUser;\n end; \n\nunit d_ServerWrapper;\ntype\n TdmServerWrapper = class(TInterfacedObject, IdmServer)\n private\n function GetServiceConnection: TServiceConnection;\n function GetCurrentUser(): TUser;\n protected\n FdmServer: TdmServer;\n end;\n\nimplementation\n\nconstructor TdmServerWrapper.Create();\nbegin\n inherited Create();\n FdmServer := TdmServer.Create(nil);\nend;\nend.\n\nunit i_BaseDAL;\ntype\n {$M+}\n IBaseDAL = interface\n ['{56D48844-BD7F-4FF8-A4AE-30DA1A82AD67}']\n procedure RefreshData(); ....\n end;\n\nunit u_BaseDAL;\ntype\n TBaseDAL = class(TInterfacedObject, IBaseDAL)\n protected\n\n FdmServer: IdmServer;\n\n public\n procedure RefreshData();\n end;\n\nimplementation\n\nprocedure TBaseDAL.Create;\nbegin\n FdmServer := GlobalContainer.Resolve;\nend;\n\nend.\n\nunit ChildFrame;\n\ninterface\n\ntype\n\n TChildFrame = class(TFrame)\n private\n fDM: IBaseDAL;\n function GetDM: IBaseDAL;\n procedure SetDM(const Value: IBaseDAL);\n public\n constructor Create(AOwner: TComponent); override;\n property DM: IBaseDAL read GetDM write SetDM;\n end;\n\nimplementation\n\nconstructor TChildFrame.Create(AOwner: TComponent);\nbegin\n inherited Create(AOwner);\n DM := nil;\nend;\n\nfunction TChildFrame.GetDM: IBaseDAL;\nbegin\n if not Assigned(fDM) then\n fDM := GlobalContainer.Resolve>;\n Result := fDM;\nend;\n\nprocedure TfrmCustomChildFrame.SetDM(const Value: IBaseDAL);\nbegin\n if Assigned(fDM) then\n fDM := nil;\n fDM := Value;\nend;\nend.\n\nTCRMFrame = class(TChildFrame)\n ....\nend;\n\nprocedure TCRMFrame.Create\nbegin\n DM := GlobalContainer.Resolve('i_BaseDAL.IBaseDAL@TBaseDAL').AsInterface as IBaseDAL;\n // DM := GlobalContainer.Resolve(IBaseDAL); {Not compiled et all: \"E2250 There is no overloaded version of 'Resolve' that can be called with these arguments\"}\nend;\n\nREGISTERING TYPES\nunit RegisteringTypes.pas\n\nprocedure RegTypes;\n\nimplementation\n\nprocedure RegTypes;\nbegin\n GlobalContainer.RegisterType;\n GlobalContainer.RegisterType, IBaseDAL>;\n GlobalContainer.RegisterType, IBaseDAL>;\n\n GlobalContainer.Build;\nend;\n\ninitialization\n RegTypes\nend.\n\nDUNIT TEST\n\ntype\n TestTCRM = class(TTestCase)\n private\n FFrame: TCRMFrame;\n FBaseDALMock: TMock>;\n procedure Init;\n\n protected\n procedure SetUp; override;\n published\n end;\n\nimplementation\n\nprocedure TestTCRM.Init;\nbegin\n inherited;\n GlobalContainer.RegisterType.DelegateTo(\n function: IdmServer\n begin\n Result := TMock.Create;\n end\n );\n\n GlobalContainer.RegisterType>.DelegateTo(\n function: IBaseDAL\n begin\n Result := TMock>.Create;\n end\n );\n\n GlobalContainer.RegisterType>.DelegateTo(\n function: IBaseDAL\n begin\n Result := TMock>.Create;\n end\n );\n\n GlobalContainer.Build;\nend;\n\nprocedure TestTfrCRMAccountClasses.SetUp;\nbegin\n inherited;\n Init;\n FFrame := TCRMFrame.Create(nil); // and I got ACCESS VIOLATION HERE\nend;\n\nFull sources of test project here - https://drive.google.com/file/d/0B6KvjsGVp4ONeXBNenlMc2J0R2M. \nColleagues, please advise me where I am wrong. Thank you in advance!\n\nA:\n\nYou need to have a reference to the TMock somewhere, because the mocks are records which will get cleaned up when they go out of scope.\nThis should work :\nprocedure DelphiMocksTest;\nvar\n func: TFunc;\n dm: IdmServer;\n i: IInitializable;\n mock : TMock;\nbegin\n func := function: IdmServer\n begin\n mock := TMock.Create;\n Supports(dm, IInitializable, i); // works\n result := mock; \n end; \n dm := func();\n Supports(dm, IInitializable, i); // fails\nend;\n\n"} +{"text": "Q:\n\nHow can I reload a visual studio project thru a nuget powershell script\n\nIn Solution Explorer 'DependentUpon' project items are normally disabled as children of the other item (ex. web.config / web.Debug.config). \nThe problem I have is when items are dynamically added via nuget/powershell at package install, Solution Explorer doesn't reload the project so the items don't show as dependent. Manually closing and reopening the solution or unload/reload the project fix the issue.\nI'd like to automate the Project Reload as part of the install.ps1 powershell script but when I do this I get 'Project Unloaded' errors and nuget rolls back the install. I think this is because the only way I know how to get the Reload context menu is to unload the project first.\nI'm looking for the object that gets invoked behind this call. I think if I could execute directly, I wouldn't have to Unload the project first.\n$dte.ExecuteCommand(\"Project.ReloadProject\")\n\nAnd here is the full code to unload/reload the project in Solution Explorer\n# Reload a project thru dte/SolutionExplorer Window \n# using Unload and Reload Context Menus.\n\n$project = Get-Project\n$shortpath = $dte.Solution.Properties.Item(\"Name\").Value + \"\\\" + $project.Name\n\n#following GUID = Constants.vsWindowKindSolutionExplorer\n#magic 1 = vsUISelectionType.vsUISelectionTypeSelect\n$dte.Windows.Item(\"{3AE79031-E1BC-11D0-8F78-00A0C9110057}\").Activate()\n$dte.ActiveWindow.Object.GetItem($shortpath).Select(1)\n$dte.ExecuteCommand(\"Project.UnloadProject\")\n$dte.ExecuteCommand(\"Project.ReloadProject\")\n\nA:\n\nI've got around this issue by 'touching' the project file and therefore triggering Visual Studio to prompt the user to reload the modified project after the package manager has closed. So my Install.ps1 file looks like this:\nparam($installPath, $toolsPath, $package, $project)\n\n# if there isn't a project file, there is nothing to do\nif (!$project) { return }\n\n# Do some stuff here\n\n$project.Save()\n\n# Touch the file to force a project reload\n$(get-item $project.FullName).lastwritetime=get-date\n\nA:\n\nSimilar question answered here:\nIs there a setting in VS 2010 that will allow it to recover open files after a project file changes?\nHowever, it doesn't indicate that reload can be called without first calling unload and it doesn't provide a mechanism for calling directly w/o going thru dte.executecommand.\n\n"} +{"text": "Q:\n\nVmware Workstation in Ubuntu 9.10 Karmic Koala\n\nI am unable to get vmware workstation to work in Ubuntu 9.10. The same installer worked fine in 9.04. Installation is successful, but initialization is not. Does anybody know a fix?\n$ lsb_release -a\nNo LSB modules are available.\nDistributor ID: Ubuntu\nDescription: Ubuntu 9.10\nRelease: 9.10\nCodename: karmic\n\nVMware-Workstation-for-Linux-64bit-6.5.1-126130.x86_64\nI don't think my key will work for version 7, sadly. I have a free 365 day student evaluation license. \n\nA:\n\nI run VMWare Workstation on Ubuntu 9.10 Karmic. In order to get it to install I had to follow these directions which basically state:\n\n[...] By default\n the installer would freeze at the\n \u201cConfiguring\u2026\u201d stage, never actually\n completing.\n1) The first step consists in\n installing the program via terminal\n and suppressing the warnings otherwise\n eventually stucking the installer. [...]\nchmod u+x VMware-Workstation-6.5.3-185404.i386.bundle\nwhile true; do sudo killall -9\nvmware-modconfig-console; sleep 1;\n\ndone in a separate terminal run:\nsudo ./VMware-Workstation-6.5.3-185404.i386.bundle --ignore-errors\nwhen the installer has finished, terminate the previous\n command (while true\u2026) with a CTRL+C or\n simply close the terminal window.\nvmware-modconfig --console --install-all\n\n[...]\n The mouse automatically ungrabs outside an area of 640 x 480 (vga resolution)\n edit file /etc/vmware/bootstrap add at the bottom\nVMWARE_USE_SHIPPED_GTK=force\n\n"} +{"text": "Q:\n\nIs it possible to use this small floating notification with Phonegap?\n\nI don't know exactly the name of it, so it's hard to find. Android have that small messages that popup over all applications and fade out after few seconds. It's not alert or push notification. Here is one screenshot for example:\nhttp://postimg.org/image/w5a3w015n/\nSo, is it possible to send that kind of notifications with phonegap? How?\n\nA:\n\nmaybe toast is what youre asking about?\n\n"} +{"text": "Q:\n\nI'm not getting JUnit HTML report in Karate\n\nI have followed the steps in Karate documentation to create a project, I ran the example test cases given in the default archifect , My cases got passed but i'm not getting any report \nmy pom.xml\n\n4.0.0\n\ncom.poc.karate\ninteracKarate\n0.0.1-SNAPSHOT\njar\n\n\n UTF-8\n 1.8\n 3.6.0\n \n\n \n \n com.intuit.karate\n karate-junit4\n 0.2.7\n test\n \n\n\n\n \n \n src/test/java\n \n **/*.java\n \n \n \n \n \n org.apache.maven.plugins\n maven-surefire-plugin\n 2.10\n \n -Dfile.encoding=UTF-8\n \n \n \n org.apache.maven.plugins\n maven-compiler-plugin\n ${maven.compiler.version}\n \n UTF-8\n ${java.version}\n ${java.version}\n -Werror\n \n \n \n \n\nRunnerClass\npackage examples.users;\n\nimport com.intuit.karate.junit4.Karate;\nimport org.junit.runner.RunWith;\n\n@RunWith(Karate.class)\npublic class UsersRunner {\n\n}\n\nmy feature file is \nFeature: sample karate test script\nBackground:\n* url 'https://jsonplaceholder.typicode.com'\nScenario: get all users and then get the first user by id\nGiven path 'users'\nWhen method get\nThen status 200\n\ndef first = response[0]\n\nGiven path 'users', first.id\nWhen method get\nThen status 200\nScenario: create a user and then get it by id\n\ndef user =\n\"\"\"\n{\n\"name\": \"Test User\",\n\"username\": \"testuser\",\n\"email\": \"test@user.com\",\n\"address\": {\n \"street\": \"Has No Name\",\n \"suite\": \"Apt. 123\",\n \"city\": \"Electri\",\n \"zipcode\": \"54321-6789\"\n}\n}\n\"\"\"\n\nGiven url 'https://jsonplaceholder.typicode.com/users'\nAnd request user\nWhen method post\nThen status 201\n\ndef id = response.id\nprint 'created id is: ' + id\n\nWhat else I'm missing here?\n\nA:\n\nThis is a really old version of Karate and I'm sure you are following outdated instructions. I suggest you follow the quick-start: https://github.com/intuit/karate#quickstart\nmvn archetype:generate \\\n-DarchetypeGroupId=com.intuit.karate \\\n-DarchetypeArtifactId=karate-archetype \\\n-DarchetypeVersion=0.8.0 \\\n-DgroupId=com.mycompany \\\n-DartifactId=myproject\n\n"} +{"text": "Q:\n\njQuery pesquisa em uma tabela\n\nEstou renderizando valores em uma tabela e tenho que filtrar por um campo que chama razao, para isso utilizo um script, a consulta funciona mas ao deletar a consulta feita os valores anteriores n\u00e3o voltam, ou seja ao apagar o campo pesquisa a pesquisa ainda persiste.\nHTML pesquisa:\n\n\n\nJs:\n $(\".pesquisa\").keyup(function () {\n var texto = $(this).val();\n $(\".lista\").css(\"display\", \"grid\");\n $(\".lista\").each(function () {\n if ($(this).find(\".razao\").text().toUpperCase().indexOf(texto.toUpperCase()) < 0) {\n $(this).css(\"display\", \"none\");\n }\n })\n })\n\nHTML lista:\n @if (Model != null)\n {\n foreach (var item in Model)\n {\n \n \n @Html.DisplayFor(modelItem => item.codigo)\n \n \n @Html.DisplayFor(modelItem => item.razao)\n \n \n @Html.DisplayFor(modelItem => item.cidade)\n \n \n @Html.DisplayFor(modelItem => item.estado)\n \n \n @Html.DisplayFor(modelItem => item.telefone)\n \n \n }\n }\n\nAlgu\u00e9m pode me ajudar?\n\nA:\n\nAo apagar o valor do campo de pesquisa, voc\u00ea deve retirar o estilo display: none, assim todos os itens ir\u00e3o voltar para o seu estado original, ou seja, ir\u00e3o aparecer novamente. \nDo jeito que est\u00e1 sua fun\u00e7\u00e3o, ele apenas esconde os resultados que n\u00e3o s\u00e3o compat\u00edveis com o valor do campo de pesquisa e n\u00e3o faz o contr\u00e1rio, que \u00e9 mostrar.\n\n"} +{"text": "Q:\n\n\u0427\u0442\u043e \u0434\u0430\u0435\u0442 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430 rel \u0440\u0430\u0432\u043d\u043e\u0435 bookmark?\n\n\u0427\u0442\u043e \u0440\u0435\u0430\u043b\u044c\u043d\u043e \u0434\u0430\u0435\u0442 rel=bookmark? \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 \u0435\u0441\u043b\u0438 \u043d\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u0441\u0441\u044b\u043b\u043a\u0443 \u0441\u0441\u044b\u043b\u043a\u0430. \u041f\u043e \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u044e \u0441\u043f\u0435\u0446\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u0438 html5 \u0442\u0430\u043a \u0438 \u043d\u0435 \u043f\u043e\u043d\u044f\u043b, \u0447\u0442\u043e \u044d\u0442\u043e \u0431\u0443\u0434\u0435\u0442?\n\nA:\n\n\u0410\u0442\u0440\u0438\u0431\u0443\u0442 rel, \u043f\u0440\u043e\u0441\u0442\u043e \u043e\u043f\u0438\u0441\u044b\u0432\u0430\u0435\u0442 \u0441\u0441\u044b\u043b\u043a\u0443, \u0442\u043e \u0435\u0441\u0442\u044c \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u0447\u0442\u043e \u044d\u0442\u043e \u0437\u0430 \u0441\u0441\u044b\u043b\u043a\u0430, \u0447\u0442\u043e \u0437\u0430 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u043d\u0430 \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u043e\u043d\u0430 \u0432\u0435\u0434\u0451\u0442.\n\u0410 \u0438\u043c\u0435\u043d\u043d\u043e rel=bookmark \u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0430\u0435\u0442 \u0447\u0442\u043e \u044d\u0442\u0430 \u0441\u0441\u044b\u043b\u043a\u0430 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u044f\u043a\u043e\u0440\u0435\u043c \u0438 \u0432\u0435\u0434\u0451\u0442 \u043d\u0430 \u043a\u0430\u043a\u0443\u044e-\u0442\u043e \u0442\u043e\u0447\u043a\u0443 \u0432 \u044d\u0442\u043e\u043c \u0436\u0435 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0435. \n\u0418 \u043f\u043e \u0441\u0443\u0442\u0438 \u043e\u043d\u0430 \u043d\u0435 \u0447\u0435\u0433\u043e \u043d\u0435 \u0434\u0430\u0451\u0442, \u0440\u0430\u0437\u0432\u0435 \u0447\u0442\u043e \u043f\u043e\u0438\u0441\u043a\u043e\u0432\u044b\u043c \u0441\u0438\u0441\u0442\u0435\u043c\u0430\u043c, \u0447\u0442\u043e \u044d\u0442\u0430 \u0441\u0441\u044b\u043b\u043a\u0430 \u043f\u043e\u0441\u0442\u043e\u044f\u043d\u043d\u0430\u044f, \u0430 \u043e\u0431\u044b\u0447\u043d\u044b\u043c \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f\u043c - \u043d\u0435 \u0447\u0435\u0433\u043e.\n\n"} +{"text": "Q:\n\nHow do I loosen nuts on bottom side of faucet are connected to each other\n\nI am replacing a 4-inch spread faucet. The hot and cold water taps each have a big brass nut threaded under the sink (in addition to the basin nuts). These nuts are connected to each other by something I\u2019ve never seen (I\u2019ve only done about a half dozen sinks in houses I\u2019ve had). I don\u2019t know how to remove the piece connecting those nuts so that I can remove the nuts. \n\nA:\n\nThis was a bottom-mount faucet.\nI was able to pry out a plastic ring holding each side, and drop it down from the bottom.\nSee the hot water side in the picture.\nA small screwdriver easily fit in the notch.\n\n"} +{"text": "Q:\n\nIssue to build a fixed sticky sidebar\n\nI'm learning bootstrap and I'd like my custom horizontal navbar to stick at the top of the page once it reaches it (like this).\nI have tried to add an affix class to my CSS as well as a piece of JS code, but that does not work. What is the issue?\nSee https://jsfiddle.net/bs7bdpmh/ \nhtml\n
\n \n\nCSS\n#nav.affix {\n position: fixed;\n top: 0;\n width: 100%;\n height: 70px;\n background: #fff;\n z-index:10;\n}\n\nJS\n$('#nav').affix({\n offset: {\n top: $('header').height()\n }\n}); \n\nA:\n\nYou mean something like this ?\nSee this fiddle\nJS : \n$(window).scroll(function(){\n scrollTop = $(window).scrollTop();\n if(scrollTop > 50){\n $('#nav').addClass('affix');\n }else{\n $('#nav').removeClass('affix');\n }\n});\n\nOf course, it's not perfect, I let you adapt the CSS code and HTML structure ;) \n\n"} +{"text": "Q:\n\nCan I change a filed utility patent application to change the original filing fee?\n\nI've filed a utility patent application, with a number of claims that increased the original filing fee.\nIs it possible to change that application, to reduce the number of claims, resulting in the reduction of the original filing fee?\n\nA:\n\nIf you did not pay yet (no refund...): yes - a readable blog post which says: \n\n\"In a US national stage application filed with excess or multiple dependent claims, the USPTO will issue a Notice of Insufficiency which will provide the applicant with an opportunity to amend the claims to reduce or eliminate excess claims and multiple dependent claims\".\n\nAlso here - the MPEP, which says (see section III (V)): \n\n\"In situations in which a payment submitted for the fees due on filing in a nonprovisional application filed under 35 U.S.C. 111(a) is insufficient and the applicant has not specified the fees to which the payment is to be applied, the Office will apply the payment in the following order until the payment is expended:...(8) the excess claims fee (37 CFR 1.16(h), (i), and (j))\". Which means that some claims will not be paid for and will therefore not be searched/examined (you do not get to choose).\n\n"} +{"text": "Q:\n\nVertical alignment in table: m-column, row size - problem in last column\n\nUnfortunatly, I have a problem with m-columns (array package) in tables with adjusted row height. Somehow in the last column (only there) the text is not centered vertically.\nCheck it out:\n\n\\documentclass{article}\n\\usepackage{array}\n\n\\begin{document}\n\n\\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|}\n\\hline\na & b & c \\\\[2ex]\n\\hline\n0 & 0 & 0 \\\\\n\\hline\n\\end{tabular}\n\n\\end{document}\n\nA:\n\nIn my opinion, it is a bug and should be reported. Tweak for the impatient: add one extra column with zero width and no padding. Remember to pre-pend \\\\ with & on the problematic lines!\n\\documentclass{article}\n\\usepackage{array}\n\n\\begin{document}\n\n\\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|@{}m{0pt}@{}}\n\\hline\na & b & c &\\\\[2ex]\n\\hline\n0 & 0 & 0 \\\\\n\\hline\n\\end{tabular}\n\n\\end{document}\n\nA:\n\nThe question as well as the answer by @tohecz indicate that there is at least one fundamental misconception about what the preamble tokens \"m\", \"b\", etc. do and how this relates to \\\\ and its optional argument. \nThe \"m\" token is not centering its material vertically in the available space!\nThe tokens \"c\", \"l\" and \"r\" produce horizontal cells (one line high) and their alignment point vertically is just the baseline of each cell.\nNow \"p\", \"m\" and \"b\" generate cells of a certain width and possibly several lines. Their vertical alignment is the first line, the middle of the box and the bottom line, respectively. So if we modify the example a bit and run:\n\\begin{tabular}{|p{0.18cm}|m{0.18cm}|b{0.18cm}|l|}\n\\hline\na\\newline a & b\\newline b & c\\newline c\\newline c& d \\\\\n\\hline\n\\end{tabular}\n\nand what we get is\n\nSo this is all positioned relative to the baseline of the cell containing \"d\".\nNow the optional argument of \\\\ only extends the space from the alignment point downwards it is not extending the size of the actual cells. Furthermore it is not actually adding this space but only making sure that there is at least that amount of space to the next row. So for example, in the above case \\\\[2ex] would have no effect because the cell in the first column goes further down than this.\nSo coming back to the original question and its input: because each cell has only a single line they should all line up but the \"m\" would not have the effect of centering the content in the available space. Instead the extra space requested by \\\\[2ex] would go after it (or should ... that's the bug).\nSo let's add an \"l\" column to avoid the bug and see what happens:\n\\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|l|}\n\\hline\na & b & c & d \\\\[2ex]\n\\hline\na\\newline a & b & c & d \\\\[2ex]\n\\hline\n\\end{tabular}\n\nResult is \n\nThe first row shows that \"m\" and \"l\" sit side by side if the \"m\" has only a single line inside and that the 2ex is between the baseline and the next row.\nThe second line has an \"m\" with 2 lines inside and there you see again that the 2ex goes from the row baseline to the next row and \"m\" is not vertically centered either.\nSo the suggestion to use an extra (kind of hidden row) like\n\\begin{tabular}{|m{0.18cm}|m{0.18cm}|m{0.18cm}|@{}m{0pt}@{}}\n\\hline\na & b & c & x\\\\[4ex] % x normally being a space\n\\hline\na\\newline a & b & c & x\\\\[4ex]\n\\hline\n\\end{tabular}\n\nis actually making use of the current bug, i.e., the \"space\" in that hidden question is actually pushed upwards so that the visible rows now appear more or less centered (which I made visible by putting in an \"x\" above):\n\nSo the moment this would get fixed the above trick no longer works.\nSo what is the bug?\nThe issue is very subtle. To make a table with rules work it is not possible to vertically skip downwards on \\\\[2ex], instead what happens is that in one of the row an invisible rule/box is placed that has a depth extending the normal depth by 2ex. If you don't do this then any vertical rule gets a disruption in places where you add additional vertical space.\nThe downside of this is, that if a row has an unusual depth, any such exstra space may come out short because it is measured in relation to the \"normal\" depth.\nIn addition and that is the \"bug\" in array putting this invisual strut at the end of the material in the last row, simply goes wrong for m-columns as they are vertically centered. Thus here you see the \"c\" moving upwards as the strut ends up in some sort of $\\vcenter{... c \\strut}$ instead of $\\vcenter{... c}$\\strut.\nThe reason for this is the strange behavior of the underlying \\halign mechanism of TeX that is used to build tables: when we reach \\\\[2ex] LaTeX has processed $\\vcenter{... c but not yet seen the remaining material that forms the column, i.e., }$.\nSo \\\\[ex] calculates and adds the strut and then tells TeX that the column is finished (using \\crinternally) and that results in TeX copying the remaining part of the column template (}$...plus space and rule) into the input stream and bingo you end up with the strut inside vcenter.\nA possible fix would be to delay the strut placement to ensure that this happens only in the right part of the column template. That in turn is a bit tricky as by that time scoping will have changed values back etc. So this needs to be a global operation.\n\\documentclass{article}\n\\usepackage{array}\n\n\\makeatletter\n\\def\\@classz{\\@classx\n \\@tempcnta \\count@\n \\prepnext@tok\n \\@addtopreamble{\\ifcase \\@chnum\n \\hfil\n \\d@llarbegin\n \\insert@column\n \\d@llarend\\fmi@fix \\hfil \\or\n \\hskip1sp\\d@llarbegin \\insert@column \\d@llarend\\fmi@fix \\hfil \\or\n \\hfil\\hskip1sp\\d@llarbegin \\insert@column \\d@llarend\\fmi@fix \\or\n $\\vcenter\n \\@startpbox{\\@nextchar}\\insert@column \\@endpbox $\\fmi@fix\n \\or\n \\vtop \\@startpbox{\\@nextchar}\\insert@column \\@endpbox\\fmi@fix \\or\n \\vbox \\@startpbox{\\@nextchar}\\insert@column \\@endpbox\\fmi@fix\n \\fi}\\prepnext@tok}\n\n\\def\\@mkpream#1{\\gdef\\@preamble{}\\@lastchclass 4 \\@firstamptrue\n \\let\\@sharp\\relax \\let\\@startpbox\\relax \\let\\@endpbox\\relax\n \\let\\fmi@fix\\relax\n \\@temptokena{#1}\\@tempswatrue\n \\@whilesw\\if@tempswa\\fi{\\@tempswafalse\\the\\NC@list}%\n \\count@\\m@ne\n \\let\\the@toks\\relax\n \\prepnext@tok\n \\expandafter \\@tfor \\expandafter \\@nextchar\n \\expandafter :\\expandafter =\\the\\@temptokena \\do\n {\\@testpach\n \\ifcase \\@chclass \\@classz \\or \\@classi \\or \\@classii\n \\or \\save@decl \\or \\or \\@classv \\or \\@classvi\n \\or \\@classvii \\or \\@classviii\n \\or \\@classx\n \\or \\@classx \\fi\n \\@lastchclass\\@chclass}%\n \\ifcase\\@lastchclass\n \\@acol \\or\n \\or\n \\@acol \\or\n \\@preamerr \\thr@@ \\or\n \\@preamerr \\tw@ \\@addtopreamble\\@sharp \\or\n \\or\n \\else \\@preamerr \\@ne \\fi\n \\def\\the@toks{\\the\\toks}} \n\n\\def\\@xargarraycr#1{\\gdef\\fmi@fix\n {\\@tempdima #1\\advance\\@tempdima \\dp\\@arstrutbox\n \\vrule \\@depth\\@tempdima \\@width\\z@\\global\\let\\fmi@fix\\relax}\\cr}\n\\let\\fmi@fix\\relax\n\n\\makeatother\n\n\\begin{document}\n\n\\begin{tabular}{|m{0.18cm}|m{0.18cm}|}\n\\hline\na&c \\\\[2ex]\n\\hline\n0& 0 \\\\\n\\hline\n\\end{tabular}\n\n\\end{document}\n\nAs I said this is rather delicate so I'm not sure it is safe to make that type of change without breaking a lot of other stuff (after all array is a really old package (25+ years) which is used quite a lot and that issue is in there from the beginning.\nAnyway with the above change we now get:\n\nwhich is what we should but perhaps not what people hoped when they thought they specify an \"m\" column.\nUpdate\nAs of 2018-04 release of LaTeX (or even one release earlier) the actual bug has now been corrected as outline above. That means (unfortunately) that the trick suggested above and marked as the correct answer is not longer working, but as I explained it was based on a wrong assumption of what the specification of \"m\" is.\n\n"} +{"text": "Q:\n\nUDP TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'\n\nI'm completely newbie to python and computer networking. While working on Uni project I have faced a problem. What am I doing wrong? Any help will me much appreciated. \nHere is server side:\nimport socket\n\ndef Main():\n host = \"127.0.0.1\"\n port = 5000\n\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind((host, port))\n\n print (\"Server Started.\")\n while True:\n data, addr = s.recvfrom(1024)\n print (\"message from: \") + str(addr)\n print (\"from connected user: \") + str(data.decode('utf-8'))\n data = str(data).upper()\n print (\"sending: \") + str(data)\n s.sendto(data, addr)\n\n s.close()\n\nif __name__ == '__main__':\n Main()\n\nHere is my client side: \nimport socket\n\ndef Main():\n host = \"127.0.0.1\"\n port = 5000\n\n server = ('127.0.0.1', 5000)\n\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind((host, port))\n\n message = input('->')\n while message != 'q':\n s.sendto(message.encode('utf-8'), server)\n data, addr = s.recvfrom(1024)\n print ('Received from server: ') + str(data)\n message = input('->')\n s.close()\n\nif __name__ == '__main__' : \n Main()\n\nA:\n\nThere were a couple of issues; mostly with the printing.\nYou had a few instances of print('some text') + str(data); this won't work, because while print() outputs to the screen (STDOUT) it returns None, so what you were actually doing was trying to concatenate None + str(data)\nWhat you need is print('some text' + str(data)).\nAdditionally, there was as issue on the server-side where you echo the data received from the client back to the client- it needed to be re-encoded as a bytearray (it comes in as a bytearray, gets converted to a utf-8 string for display, it needs to go back to bytearray before replying).\nIn summary, server:\nimport socket\n\ndef Main():\n host = \"127.0.0.1\"\n port = 5000\n\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind((host, port))\n\n print(\"Server Started.\")\n while True:\n try:\n data, addr = s.recvfrom(1024)\n print(\"message from: \" + str(addr)) # moved string concatenation inside print method\n print(\"from connected user: \" + str(data.decode('utf-8'))) # moved string concatenation inside print method\n data = str(data).upper()\n print(\"sending: \" + str(data)) # moved string concatenation inside print method\n s.sendto(data.encode('utf-8'), addr) # needed to re-encode data into bytearray before sending\n except KeyboardInterrupt: # added for clean CTRL + C exiting\n print('Quitting')\n break\n\n s.close()\n\nif __name__ == '__main__':\n Main()\n\nAnd the client:\nimport socket\n\ndef Main():\n host = \"127.0.0.1\"\n port = 5001\n\n server = ('127.0.0.1', 5000)\n\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind((host, port))\n\n message = input('->')\n while message != 'q':\n try:\n s.sendto(message.encode('utf-8'), server)\n data, addr = s.recvfrom(1024)\n print('Received from server: ' + str(data)) # moved string concatenation inside print method\n message = input('->')\n except KeyboardInterrupt: # added for clean CTRL + C exiting\n print('Quitting')\n break\n\n s.close()\n\nif __name__ == '__main__':\n Main()\n\n"} +{"text": "Q:\n\nDecomposition of a signal to slow and fast components\n\nI am currently recording biological responses which are triggered by different events. The figure below shows the original signal (black) and the occurrence of input events (colored dots). There is typically few seconds of a delay in response to different events, and only some of the events generate a response. These phasic responses occur simultaneously with slowly changing fluctuations (tonic component), which are also biologically important (rather than measurement noise). So it is important to come up with a model that can decompose these signals with few constraints that are biologically plausible: signal = tonic + phasic.\nIn this system, phasic responses can be well modeled with typical linear system characterization methods based on impulse response function. Also note that, these phasic responses are always positive, that is biologically speaking there is no inhibition. For this reason, if there were no slow fluctuations in the recordings, the recorded signal would never go below zero, except for measurement noise.\nWhat is more problematic is to account for baseline shifts (the tonic component). I would like to come up with a method that can be used to model the tonic component and phasic responses simultaneously based on the following assumptions:\n1/ tonic component changes slowly.\n2/ phasic component changes fast.\n3/ phasic component is always positive, that is: signal - tonic should contain as negative values as possible.\nThe problem boils down to extracting slow and fast components of a signal. I have already 4 methods in mind, and I would like to see what you think is best suited or come up with an alternative.\nThe first thing that comes to mind is to low-pass filter the signal to obtain an estimation of the tonic component (see blue line). The main problem here is that the estimated tonic component violates the above-mentionned constraint #3. According to this assumption, no points in the recorded signal should be below the tonic component. Instead the tonic component should pass through all the data points where the phasic response is close to zero (schematically shown with the red curve in the figure below).\nAnother approach would be to make an assumption about the duration of phasic response. In doing so, one could use recorded samples that are at least as far as the duration of phasic response as keypoints and interpolate using cubic splines for the remaining data points. This is actually how I have drawn the red curve, but I feel like the interpolation of data points between the key points is problematic, because there are not many key points.\nA third approach would be to work on first or second derivative space and characterize the system in this domain, as it is supposed to be less sensitive to low-variations. \nA fourth approach consists of extracting slow components. One could use rely more on the history, when the signal is changing fast, and update the history with new data when the signal changes slowly. I am not sure though how to mathematically tackle this one.\n\nA:\n\nYour problem is pervasive in signal and image processing: being able to separate a trend (with some assumptions) from a signal (with some other assumptions) and potentially additional noise. This is an instance of (semi-)informed source separation: a sine from a drift, a texture from a cartoon image, a biological information from instrumental artifacts, etc, that requires a more involved modeling and optimization framework.\nYour choices are related to fundamental questions related to the model you can build based on physical and mathematical assumptions, aside from the algorithmic tools you can program.\n1) Low-pass filtering: \nStandard low-pass filtering is linear and time-invariant. Linearity is very consistent with \"signal = tonic + phasic\". But phasic could be (on theory) negative, as \"$2+(-1) = 1$\". As your graphic does not include x/y scales, \"above\" is clear, but i am not sure of what you can model with \"no points in the recorded signal should be below the tonic component\", since additional noise can be fluctuating too. But positivity is a property which can be taken into account, with some non-linearity caveats.\n2) Duration:\n\"that are at least as far as the duration of phasic response\" : your assumption seems to me to related to a time-delay, yet i cannot interpret it precisely so far.\n3) High-order derivatives: \n\"A third approach would be to work on first or second derivative space and characterize the system in this domain, as it is supposed to be less sensitive to low-variations\" Indeed, slow variations are expected to be with limited derivatives. This could result in a \"sparsity\" prior assumption.\n4) Causality: \"rely more on the history\" there is some causality assumption behind that. This too is a tough stuff.\nAll your four approaches seem consistent to me, and may help you ponder and state your assumptions. They are otherwise termed as \u201cmorphological component analysis (MCA)\u201d, \u201cgeometric separation\u201d or \u201cclustered sparsity\u201d, adding positivity. Such topics are addressed for instance in \"Blind source separation of positive and partially correlated data\" http://dx.doi.org/10.1016/j.sigpro.2005.03.006. \nYou may find additional history for instance in the introduction of (mong other papers \"Chromatogram baseline estimation and denoising using sparsity (BEADS)\" \nhttp://dx.doi.org/10.1016/j.chemolab.2014.09.014 \nwhich also deals with positivity, low-pass-filtering and derivative sparisty, yet the causal approach is not considered. So you can specify your model in more precise terms (you did do talk about the noise yet), you may find some tracks to solve your questions\n\n"} +{"text": "Q:\n\nPrevent Git from changing permissions on pull\n\nWhen I pull change from my repositories, Git change the file permissions (actually, he change the group write permission).\nIf I'm correct, Git should only track executable bit and this anyway can be removed using setting core.filemode to false.\nBut, although the filemode is set to false (in local, global and user), when I pull, write permission constantly change.\nI could use a git-hooks in order to reset correct chmod, but this is some overhead and I'd prefer if there's a way to just ask git to completly ignore file mode change.\nAnyone know how to achieve this ?\n\nA:\n\nOne config setting that might help here is core.sharedRepository, presented in the blog post \"Preserving Group Write on Git Objects in a Collaborative Repository\":\n\nThe solution turned out to be fairly straightforward.\n In the file .git/config, I added a line that read: \"sharedRepository = group\", like so:\n[core]\n repositoryformatversion = 0\n filemode = true\n bare = false\n logallrefupdates = true\n sharedRepository = group\n\nThereafter, new files in .git/objects were created with the proper permissions for group write.\n (However, note that new files are group-owned by the primary group of the user account via which the push was received. If the users collaborating on the project have different primary groups, and if those users do not share membership in that set of groups, you may still run into problems.)\n\nMake sure of the value of your umask:\n\nExample: 0660 will make the repo read/write-able for the owner and group, but inaccessible to others (equivalent to group unless umask is e.g. 0022).\n\nA:\n\nThe solution I use is to run the command as the user that has the permissions you want to keep:\nsudo -u user command\n\nIn this case, it could be:\nsudo -u www-data git pull\n\nwww-data being the apache default user on Ubuntu at least.\nThis keeps the permissions from changing. I use it when updating git repositories on my VPS, while keeping the file permissions set to the webserver user.\n\n"} +{"text": "Q:\n\nHow can I make SKSpriteNode positions the same for any simulator/device?\n\nIn my game, the position of my SKNodes slightly change when I run the App on a virtual simulator vs on a real device(my iPad).\nHere are pictures of what I am talking about.\nThis is the virtual simulator\nThis is my Ipad\nIt is hard to see, but the two red boxes are slightly higher on my iPad than in the simulator\nHere is how i declare the size and position of the red boxes and green net:\nThe following code is located in my GameScene.swift file\nfunc loadAppearance_Rim1() { \nRim1 = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake((frame.size.width) / 40, (frame.size.width) / 40))\nRim1.position = CGPointMake(((frame.size.width) / 2.23), ((frame.size.height) / 1.33)) \nRim1.zPosition = 1 \naddChild(Rim1) \n}\n\nfunc loadAppearance_Rim2(){ \n Rim2 = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake((frame.size.width) / 40, (frame.size.width) / 40))\n Rim2.position = CGPoint(x: ((frame.size.width) / 1.8), y: ((frame.size.height) / 1.33)) \n Rim2.zPosition = 1 \n addChild(Rim2) \n}\nfunc loadAppearance_RimNet(){ \n RimNet = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake((frame.size.width) / 7.5, (frame.size.width) / 150))\n RimNet.position = CGPointMake(frame.size.width / 1.99, frame.size.height / 1.33)\n RimNet.zPosition = 1 \n addChild(RimNet) \n}\nfunc addBackground(){\n //background\n background = SKSpriteNode(imageNamed: \"Background\")\n background.zPosition = 0\n background.size = self.frame.size\n background.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)\n self.addChild(background)\n}\n\nAdditionally my GameViewController.swift looks like this\nimport UIKit\nimport SpriteKit\n\nclass GameViewController: UIViewController {\n\nvar scene: GameScene!\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n\n //Configure the view\n let skView = view as! SKView\n //If finger is on iphone, you cant tap again\n skView.multipleTouchEnabled = false\n\n //Create and configure the scene\n //create scene within size of skview\n scene = GameScene(size: skView.bounds.size)\n scene.scaleMode = .AspectFill\n scene.size = skView.bounds.size\n //scene.anchorPoint = CGPointZero\n\n //present the scene\n skView.presentScene(scene)\n\n}\n\noverride func shouldAutorotate() -> Bool {\n return true\n}\n\noverride func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {\n if UIDevice.currentDevice().userInterfaceIdiom == .Phone {\n return .Landscape\n } else {\n return .All\n }\n}\n\noverride func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Release any cached data, images, etc that aren't in use.\n}\n\noverride func prefersStatusBarHidden() -> Bool {\n return true\n}\n}\n\nHow can I make the positions of my nodes be the same for each simulator/physical device?\n\nA:\n\nIf you are making a Universal application you need to declare the size of the scene using integer values. Here is an example:\nscene = GameScene(size:CGSize(width: 2048, height: 1536))\n\nThen when you initialize the positions and sizes of your nodes using CGPoint and CGSize, make them dependant on SKScene size. Here is an example:\nnode.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)\n\nIf you declare the size of the scene for a Universal App like this:\nscene.size = skView.bounds.size\n\nthen your SKSpriteNode positions will be all messed up. You may also need to change the scaleMode to .ResizeFill. This worked for me.\n\n"} +{"text": "Q:\n\nTD contenteditable with autocomplete bootstrap 3\n\nI spend my whole day for searching any autocomplete lib that support contenteditable. The closest that I found is jQuery UI which I tried but it conflicts with Bootstrap 3( this is only my guess i'm not really sure ).\nIs there any lib that will allow me to do this?\nNote: if it is related I'm also using dataTables\nI will really appreciate it if someone give me a working example with this fiddle ready\n\nA:\n\nOn mouse click of any td why don't you dynamically add an input tag inside td. Which can make your cell editable. \nIf you are trying to implement something similar to excel data grid, try this:\nsuppose each cell (td) of your grid has a class - \"cell\" then,\n$('.cell').click(function(){\n var text = $(this).text();\n $(this).html(\"
\"+text+\"
\");\n});\n\nI added class \"editable\" so that you can add any styling to it if required.\nTo move to next cell on tab you either need to bind 'keydown' and do the required action for tab or use tabindex property if your grid is made of divs\n\n"} +{"text": "Q:\n\nRemove Binary while Waiting for Review\n\nI have just uploaded a binary file for review.\nThe status for my app now is Waiting for Review. But i discovered a bug which i should fix it before submitting but i can't find where the remove binary is located.\nThe last submit, it was under the Version section, But now it is just disappeared!!\nI have tried lot of research and all refers to the old iTunes design, and just found 1 solution which was under the version tab which is not found in my case now.\nDoes anyone know where is it now with all these changes made by iTunes every day? or it is delayed more than 1 hour to appear ?\nThank you\n\nA:\n\nI met the same problem and could not found where to Reject the binary.\nFinally I downloaded an iTunes Connect app from App Store and rejected the binary by it.\n\n"} +{"text": "Q:\n\nMySQL won't start after reboot. Exiting with signal 11\n\nlast night I was doing a server maintenance that required DB reboot.\nNo changes in a config were made.\nCurrent setup is as follows:\nmaster (server1) - master (server2) and slave (server0)\nMySQL version: mysql-5.5.32\nserver0 and server1 started fine after a reboot but when i try to start server0 it crashes with signal 11 error:\nHere's the log output:\n140604 03:10:08 mysqld_safe Starting mysqld daemon with databases from /opt/mysql/mysql_data\n140604 3:10:08 [Note] Plugin 'FEDERATED' is disabled.\n140604 3:10:08 InnoDB: The InnoDB memory heap is disabled\n140604 3:10:08 InnoDB: Mutexes and rw_locks use GCC atomic builtins\n140604 3:10:08 InnoDB: Compressed tables use zlib 1.2.3\n140604 3:10:08 InnoDB: Using Linux native AIO\n140604 3:10:08 InnoDB: Initializing buffer pool, size = 32.0G\n140604 3:10:10 InnoDB: Completed initialization of buffer pool\n02:10:10 UTC - mysqld got signal 11 ;\nThis could be because you hit a bug. It is also possible that this binary\nor one of the libraries it was linked against is corrupt, improperly built,\nor misconfigured. This error can also be caused by malfunctioning hardware.\nWe will try our best to scrape up some info that will hopefully help\ndiagnose the problem, but since we have already crashed,\nsomething is definitely wrong and this may fail.\n\nkey_buffer_size=67108864\nread_buffer_size=8388608\nmax_used_connections=0\nmax_threads=2000\nthread_count=0\nconnection_count=0\nIt is possible that mysqld could use up to\nkey_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 49240442 K bytes of memory\nHope that's ok; if not, decrease some variables in the equation.\n\nThread pointer: 0x0\nAttempting backtrace. You can use the following information to find out\nwhere mysqld died. If you see no messages after this, something went\nterribly wrong...\nstack_bottom = 0 thread_stack 0x40000\n/usr/local/mysql/bin/mysqld(my_print_stacktrace+0x35)[0x7a2825]\n/usr/local/mysql/bin/mysqld(handle_fatal_signal+0x403)[0x670b43]\n/lib/x86_64-linux-gnu/libpthread.so.0(+0xf030)[0x7f1c2db0e030]\n/usr/local/mysql/bin/mysqld[0x93ec38]\n/usr/local/mysql/bin/mysqld[0x8328d2]\n/usr/local/mysql/bin/mysqld[0x861511]\n/usr/local/mysql/bin/mysqld[0x7f302f]\n/usr/local/mysql/bin/mysqld[0x7c40dd]\n/usr/local/mysql/bin/mysqld(_Z24ha_initialize_handlertonP13st_plugin_int+0x48)[0x673948]\n/usr/local/mysql/bin/mysqld[0x58307a]\n/usr/local/mysql/bin/mysqld(_Z11plugin_initPiPPci+0xb5d)[0x586c9d]\n/usr/local/mysql/bin/mysqld[0x507bab]\n/usr/local/mysql/bin/mysqld(_Z11mysqld_mainiPPc+0x3e2)[0x508772]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xfd)[0x7f1c2ccccead]\n/usr/local/mysql/bin/mysqld[0x4fe17a]\nThe manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains\ninformation that should help you find out what is causing the crash.\n140604 03:10:10 mysqld_safe mysqld from pid file /opt/mysql/mysql_data/odb2.pid ended\n\nAfter that I started mysql with innodb_force_recovery = 1 and server started ok.\nLooking at the documentation:\n\n*1 (SRV_FORCE_IGNORE_CORRUPT) Let the server run even if it detects a corrupt page. Try to make SELECT * FROM tbl_name jump over corrupt\n index records and pages, which helps in dumping tables.*\n\nSo my next step was to run mysqlcheck on all databases but no errors were found.\nAny ideas how to bring that server to life? I have a backup of all databases (~300GB) but restoring it would take a considerable amount of time and if possible I'd like to avoid that\n\nA:\n\nTurns out it was a bug introduced in 5.5.32 http://bugs.mysql.com/bug.php?id=69623 where MySQL fails to open a second tablespace if stored in more than 1 file.\nUpdate to 5.5.39 solved the issue\n\n"} +{"text": "Q:\n\nIterate thru ec2 describe instance boto3\n\nI am trying to get specific values for a describe instance call. So for example, if I want to get the 'Hypervisor' value or the Ebs has 'DeleteOnTermintation' value from the output. Below is the current code I am currently using to make the call and iterate thru the dictionary output.\nimport boto3\nimport pprint\nfrom datetime import datetime\nimport json\n\nclient = boto3.client('ec2')\n\nfilters = [{ \n'Name': 'tag:Name',\n'Values': ['*']\n}]\n\nclass DatetimeEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime):\n return obj.strftime('%Y-%m-%dT%H:%M:%SZ')\n elif isinstance(obj, date):\n return obj.strftime('%Y-%m-%d')\n # Let the base class default method raise the TypeError\n return json.JSONEncoder.default(self, obj) \n\noutput = json.dumps((client.describe_instances(Filters=filters)), cls=DatetimeEncoder) \n\npprint.pprint(output)\n\nfor v in output:\n print v['Hypervisor']\n\nGetting this error:\nTypeError: string indices must be integers, not str\n\nUsing the pprint to see all the values available from the output.\n\nA:\n\nHere's how you could display the information via the AWS Command-Line Interface (CLI):\naws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Hypervisor, NetworkInterfaces[0].Attachment.DeleteOnTermination]'\n\nHere's some Python:\nimport boto3\n\nclient = boto3.client('ec2')\n\nresponse = client.describe_instances()\n\nfor r in response['Reservations']:\n for i in r['Instances']:\n print i['InstanceId'], i['Hypervisor']\n for b in i['BlockDeviceMappings']:\n print b['Ebs']['DeleteOnTermination']\n\nA:\n\nHere's John's answer but updated for Python3\nimport boto3\n\nclient = boto3.client('ec2')\n\nresponse = client.describe_instances()\n\nfor r in response['Reservations']:\n for i in r['Instances']:\n print(i['InstanceId'], i['Hypervisor'])\n for b in i['BlockDeviceMappings']:\n print(b['Ebs']['DeleteOnTermination']) \n\n"} +{"text": "Q:\n\nForeach loop array with same array name\n\nWhat I am trying to do is this:\nI want to echo information based on year/month/day.\nMy code is:\n $data = array(\n \"2018\" => array(\n \"September\" => array(\n \"02\" => array(\n \"Line 1\"\n ),\n \"02\" => array(\n \"Line 11\"\n ),\n \"12\" => array(\n \"Line 2\"\n ),\n \"31\" => array(\n \"Line 3\"\n )\n ),\n \"December\" => array(\n \"02\" => array(\n \"Line 11\"\n ),\n \"12\" => array(\n \"Line 22\"\n ),\n \"31\" => array(\n \"Line 33\"\n ),\n \"32\" => array(\n \"Line 66\"\n )\n )\n ),\n \"2019\" => array(\n \"May\" => array(\n \"05\" => array(\n \"Line z\"\n ),\n \"15\" => array(\n \"Line y\"\n ),\n \"55\" => array(\n \"Line x\"\n )\n )\n )\n);\n\necho '
';\nprint_r($data);\necho '
';\n\nforeach ($data as $years => $year) {\n\n echo $years . \"
\";\n\n foreach ($year as $months => $month) {\n\n echo $months . \"
\";\n\n foreach ($month as $days => $day) {\n\n foreach ($day as $key => $value) {\n echo $days . \" - \" . $value . \"
\";\n }\n }\n }\n}\n\nAs you see for 2018 september there are two arrays for the date of 2nd.\nI was hoping to see this when print_r\n2018\nSeptember\n02 - Line 1\n02 - Line 11\n12 - Line 2\n31 - Line 3\n\nbut instead I get this\n2018\nSeptember\n02 - Line 11\n12 - Line 2\n31 - Line 3\n\nHow can I echo both values of september 2, 2018?\n\nA:\n\nYou cannot have duplicate keys. You are defining \"02\" twice.\nSolution: Define \"September\" as:\n \"September\" => array(\n \"02\" => array(\n \"Line 1\",\n \"Line 11\"\n ),\n \"12\" => array(\n \"Line 2\"\n ),\n \"31\" => array(\n \"Line 3\"\n )\n ),\n\n"} +{"text": "Q:\n\nNetBeans: how to split window and place output panel to the right?\n\nBy default NetBeans has projects on the left, open files on the top part of right panel and output/variables/... on the bottom part of the left panel. As a result file panel is wide and tall. Is it possible to reorganize panels, so that \"projects\" panel is on the left, \"open files\" panel is on the center and \"output/variables/...\" panel is on the right?\n\nA:\n\nThis can be done much the same way you split the string horizontally. Grub the page tab and move it until you see that the red rectangle indicating alignment appears vertically along the right side of screen. This works in NetBans 8.1 and above.\n\n"} +{"text": "Q:\n\nIf .NET uses mark&sweep GC, why does it cut the memory addresses space in half?\n\nAccording to MSDN, the .NET framework uses the mark&sweep garbage collection method. The same page also says that on 32bit systems, the address space is 2GB - which means that the address space is cut in half from the 4GB of 32bit systems.\nCutting the available memory in half is a trait of the stop© garbage collection method, but .NET uses mark&sweep which can operate on the whole address space - so why does .NET cut the address space in half?\n\nA:\n\nThis is Windows, not .NET. 32bit Windows reserved the top 2GB of the address space for the operating system, and restricted applications to 2GB (provided the /3GB flag wasn't used).\nNote that, in practice, it's actually worse. A 32bit .NET application will typically start raising OutOfMemoryException between 1.2 and 1.6GB of RAM usage, even on a 64bit system with plenty of phsyical memory.\n\n"} +{"text": "Q:\n\nextend a right floating div to the left\n\nI am trying to extend a right floating div to the left.\nI have an image and would like to put some text on the right of the image.\nEDIT\nthe goal is that the site stays dynamic. So I can not use a fixed width.\nOne way would be to use Javascript, I guess but I would prefer to do this in HTML CSS only if possible.\nHere is a picture of what I have\n\nAnd here is a picture of what I would like to have\n\nHow can I extend the right div to left ?\nOr should I use a div in the middle ?\nHere is the HTML\n
\n
\n \"KI-consult \n
\n
\n test
address 1
address2\n
\n
\n\nand the CSS\n#logo_container\n\n{\npadding: 0px; \noverflow: hidden; \nzoom: 1;\n\n}\n\n#logo_image\n\n{\nfloat: left;\nbackground-color: transparent;\nborder: 1px solid red;\n\n}\n\n#logo_address\n\n{\nbackground-color: #0E4194;\ncolor: #FFFFFF;\nmargin-left: auto; \npadding: 0px; \nfloat: right;\nborder: 1px solid red;\nheight: 150px;\n\n}\n\nA:\n\n#logo_address\n{\nbackground-color: #0E4194;\ncolor: #FFFFFF;\npadding: 0px; \ntextalign: right;\nfloat: left;\nborder: 1px solid red;\nheight: 150px;\nwidth: ENTER VALUE HERE;\n}\n\nThis would be a solution. If you float the #logo_address to the left, align the text to the right and enter a width value it would look as you want.\n\n"} +{"text": "Q:\n\nEither Remote or Local Sandbox, why not both ?\n\nWRT : http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e3f.html\nWhy a flash application can either use Remote or Local Sandbox . What is the problem if it's using both of them ?\nSay a flash application at one time communicating with a local file... and also communicating with some file on the server. Isn't that allowed ? \n\nA:\n\nIt is not allowed because of security reasons, if it was allowed to communicate with both you can potentially take files from the users machine and send them to a server on the web.\n\n"} +{"text": "Q:\n\nMap of mutex c++11\n\nI need to make a thread-safe map, where I mean that each value must be independently mutexed. For example, I need to be able to get map[\"abc\"] and map[\"vf\"] at the same time from 2 different threads.\nMy idea is to make two maps: one for data and one for mutex for every key:\nclass cache\n{\nprivate:\n....\n\n std::map mainCache;\n std::map > mutexCache;\n std::mutex gMutex;\n.....\npublic:\n std::string get(std::string key);\n\n};\nstd::string cache::get(std::string key){\n std::mutex *m;\n gMutex.lock();\n if (mutexCache.count(key) == 0){\n mutexCache.insert(new std::unique_ptr);\n }\n m = mutexCache[key];\n gMutex.unlock();\n}\n\nI find that I can't create map from string to mutex, because there is no copy constructor in std::mutex and I must use std::unique_ptr; but when I compile this I get:\n/home/user/test/cache.cpp:7: error: no matching function for call to 'std::map, std::unique_ptr >::insert(std::unique_ptr*)'\n mutexCache.insert(new std::unique_ptr);\n ^\n\nHow do I solve this problem?\n\nA:\n\nWhy do you need to use an std::unique_ptr in the first place?\nI had the same problem when I had to create an std::map of std::mutex objects. The issue is that std::mutex is neither copyable nor movable, so I needed to construct it \"in place\".\nI couldn't just use emplace because it doesn't work directly for default-constructed values. There is an option to use std::piecewise_construct like that:\nmap.emplace(std::piecewise_construct, std::make_tuple(key), std::make_tuple());\n\nbut it's IMO complicated and less readable.\nMy solution is much simpler - just use the operator[] - it will create the value using its default constructor and return a reference to it. Or it will just find and return a reference to the already existing item without creating a new one.\nstd::map map;\n\nstd::mutex& GetMutexForFile(const std::string& filename)\n{\n return map[filename]; // constructs it inside the map if doesn't exist\n}\n\nA:\n\nReplace mutexCache.insert(new std::unique_ptr) with:\nmutexCache.emplace(key, new std::mutex);\n\nIn C++14, you should say:\nmutexCache.emplace(key, std::make_unique());\n\nThe overall code is very noisy and inelegant, though. It should probably look like this:\nstd::string cache::get(std::string key)\n{\n std::mutex * inner_mutex;\n\n {\n std::lock_guard g_lk(gMutex);\n\n auto it = mutexCache.find(key);\n if (it == mutexCache.end())\n {\n it = mutexCache.emplace(key, std::make_unique()).first;\n }\n inner_mutex = it->second.get();\n }\n\n {\n std::lock_guard c_lk(*inner_mutex);\n return mainCache[key];\n }\n}\n\n"} +{"text": "Q:\n\nHow a group represents the passage of time?\n\nI am reading a book on algebraic geometry and I google some keywords, eventually come up with this post in terry tao blog: \nhttp://terrytao.wordpress.com/2009/10/19/grothendiecks-definition-of-a-group/\nI think I got good intuition on the different thoughts on a group, but not this one:\n\n(6) Dynamic: A group represents the passage of time (or of some other\n variable(s) of motion or action) on a (reversible) dynamical system.\n\nCan anyone explain to me how a group represents the passage of time? \nI can only think of Noether's theorem on conservation law when combining the concept of time and algebra.\n\nA:\n\nIt's hard to say what Terry meant exactly unless you ask him. Nevertheless, it seems quite probable that he is talking about flows on manifolds (or more general kind of spaces but let's stick with this).\nA reversible flow on a manifold $M$ is a family of diffeomorphisms $\\phi_t:M \\to M, t \\in {\\bf R}$ that obey the rule of composition $\\phi_t \\circ \\phi_s = \\phi_{s+t}$. In other words, flow is an action of the group $({\\bf R}, +)$ on the manifold. That this describes dynamics is immediate: for any $x \\in M$, $\\phi_t(x)$ is a curve that shows how $x$ moves under the flow.\n\n"} +{"text": "Q:\n\nOutOfMemoryError Whilst Writing a String to a ByteArrayOutputStream\n\nI have a method which I have an array of String objects which I need to write to a ByteArrayOutputStream which later on I will write into a ZipOutputStream.\nHere is my code.\n// SAVE THE STRING AS A BYTE ARRAY IN MEMORY INSTEAD OF CREATING AND SAVING TO A NEW FILE\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n DataOutputStream byteOut = new DataOutputStream(baos);\n byte[] data;\n if (i == 1) {\n if (nodeStringArray != null) {\n for (String s : nodeStringArray) {\n byteOut.write(s.getBytes(\"UTF-8\"));\n }\n }\n } else {\n data = stringArray.get(i).getBytes(\"UTF-8\");\n byteOut.write(data);\n }\n\n byteOut.close();\n byte[] input = baos.toByteArray();\n\n ZipEntry entry = new ZipEntry(fileName);\n entry.setSize(input.length);\n zos.putNextEntry(entry);\n zos.write(input);\n zos.closeEntry();\n\nThe issue is, and I have only received on crash report for it, I am getting an OutOfMemoryError on the line that reads byteOut.write(s.getBytes(\"UTF-8\"));\nAnyone know of a better way of doing this or can see if I am doing something wrong?\nIDEA\nCould I put a try catch statement around the problem and when it happens call byteOut.flush()?\nThanks in advance\n\nA:\n\nYou are making to many copies of the data, and this is causing you to run out of memory.\nYou should be directly writing into your ZipOutputStream in your first loop.\nZipEntry entry = new ZipEntry(fileName);\nzos.putNextEntry(entry);\nfor (String s : nodeStringArray) {\n zos.write(s.getBytes(\"UTF-8\"));\n}\nzos.closeEntry();\n\n"} +{"text": "Q:\n\njava program to return the sum of all integers found in the parameter String\n\ni want write a java program to return the sum of all integers found in the parameter String.\nfor example take a string like:\" 12 hi when 8 and 9\"\nnow the answer is 12+8+9=29.\nbut i really dont know even how to start can any one help in this!\n\nA:\n\nYou may start with replacing all non-numbers from the string with space, and spilt it based on the space\nString str = \"12 hi when 8 and 9\";\nstr=str.replaceAll(\"[\\\\D]+\",\" \");\nString[] numbers=str.split(\" \");\nint sum = 0;\nfor(int i=0;i is a prime, and all this for first 1000 Fibonacci numbers only.\nFor example, this code: (K=1)\nSelect[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 1] &]\n\nreturns\n\n{1, 1, 2}\n\nThis code: (K=2)\nSelect[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 2] &]\n\nreturns\n\n{1, 1, 3, 21, 6765, 32951280099, \\\n 971183874599339129547649988289594072811608739584170445, \\\n 1082459262056433063877940200966638133809015267665311237542082678938909\\\n }\n\nThis code: (K=3)\nSelect[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 3] &]\n\nreturns\n\n{2, 8, 3524578, 27777890035288, \\\n 2011595611835338993891308327102733537615455242513357158345612749706882\\\n 9146295425939723629305572732574726246290673965789878845363842331040064\\\n 16432124798818261534841714338, \\\n 2949592466076064248964701302014885591673737506156850406413751530665307\\\n 5810241060939483954895520932111023343610904846943097162533007651451709\\\n 723277579925520157875345780869307228929160}\n\nAnd this code: (K=99)\nSelect[Table[Fibonacci[n], {n, 1, 1000}], PrimeQ[#*# + 99] &]\n\nreturns\n\n{2, 8, 3524578, 6557470319842, \\\n 4286863412788815942499567477797350205106309231244244822408841055026686\\\n 7672}\n\nI need to get all results from 1 to 99, then count elements of each answer, and display these in the following (or similar) form:\n K number of primes\n 1 3\n 2 8\n 3 6\n . .\n . .\n 99 5\n\nI appreciate your help.\n\nA:\n\nfibs2 = Fibonacci@Range@1000^2;\ntab = Table[{k, Count[fibs2 + k, _?PrimeQ]}, {k, 1, 99}];\n\nTableForm[tab, TableHeadings -> {None, {\"K\", \"number of primes\"}}]\n\n(welcome back)\n\n"} +{"text": "Q:\n\nQuestion regarding algebraicity of two elements whose sum and product are algebraic.\n\nLet $\\alpha , \\beta \\in \\Bbb C$ and suppose $\\alpha + \\beta$ and $\\alpha \\beta$ are algebraic over $\\Bbb Q$. Prove $\\alpha , \\beta$ are algebraic over $\\Bbb Q$.\n\nA:\n\nObserve that $\\alpha^2-(\\alpha+\\beta)\\alpha + \\alpha \\beta = 0$. Hence, $\\alpha$ is algebraic over $\\mathbb{Q}(\\alpha+\\beta,\\alpha\\beta)$. But $\\mathbb{Q}(\\alpha+\\beta,\\alpha\\beta)$ is algebraic over $\\mathbb{Q}$. Hence, $\\alpha$ is algebraic over $\\mathbb{Q}$.\n\n"} +{"text": "Q:\n\nRedirect Working on Module Not Menu Item\n\nJoomla 3.9.19\nI have a login module and in the Login Redirection Page I have selected a menu item > single article. This redirect works fine.\nI also have a menu item type > login form. In the Menu Item Login Redirect I have selected a menu item > single article (same as above). This redirect doesn't work, I am always redirected to the user profile page.\nI have tried an absolute URL in the menu item type > login form, makes no difference.\nI don't have any other login componetns or plugins installed.\nI've seen a similar question here and a few other places.\nAny ideas why this could be or how I can redirect to an article on both the login module and the login menu item? I don't want to edit core files, and I dont think I should need an override for such a basic task?\n\nA:\n\nThe solution was the change the Login Redirect Type to an Internal URL, and ensure it was non-sef.\nThis is in the documentation https://docs.joomla.org/How_do_you_redirect_users_after_a_successful_login%3F\n\nDue to a security fix on Joomla 3.4.6, the redirect url must be an\ninternal url, it must start with index.php? and be a non-sef url.\nBefore Joomla 3.4.6, it worked but that was due to a bug in the way\nJoomla validated the urls. Now that security has been applied and the\nurls tested correctly the above examples will fail.\n\nOnce I change my URL to a non-sef version of my menu item it worked;\n\nindex.php?option=com_content&view=article&id=32&Itemid=469\n\nThanks to @Grant G for the tips.\n\n"} +{"text": "Q:\n\nCan the Dispel Magic spell be used to dispel a familiar summoned by the Find Familiar spell?\n\nSince you cast the find familiar spell to get a familiar, is the familiar a magical effect? And if that is true, would you be able to target the familiar with the dispel magic spell and get the familiar destroyed/killed/dispelled?\nWould this then be a good reason to cast find familiar at a higher level?\n\nA:\n\nNo.\nThe familiar from find familiar isn't an ongoing magical effect to be dispelled. When you cast the spell (with a duration of instantaneous), the following occurs (from the spell's text):\n\nYou gain the service of a familiar, a spirit that takes an animal form you choose... it is a celestial, fey, or fiend (your choice) instead of a beast.\n\nThe spell doesn't create the familiar, per se. Rather, the familiar is a spirit whose service you instantaneously gain when you cast the spell. So the familiar isn't a spell effect.\nIn addition, the spell's duration of instantaneous indicates that there is no ongoing effect to be dispelled (from the rules on spell duration):\n\nMany spells are instantaneous. The spell harms, heals, creates, or alters a creature or an object in a way that can't be dispelled, because its magic exists only for an instant.\n\nSo the familiar can't be dispelled using dispel magic.\nFor more details on dispelling magical effects, see this related question.\n\n"} +{"text": "Q:\n\nJS - Removing Keys from object\n\nI got a question, and would be really grateful if someone could explain to me in pseudo code how do I solve it\nSo here we go, I have an object like this\nconst obj = {\n 'key1': [],\n 'key2': [val1, val2],\n 'key3': [],\n 'key4': [val3]\n }\n\nI need to remove the keys which contain an empty array, in this case key1 and key3, and then return a new object without the keys that contained the empty array.\nIm trying to figure this out on my own, but I'm still a JS newbie.\n\nA:\n\nIt could be done by using the following actions:\n\nuse Object.entries() method to return an array of a given object's own enumerable string-keyed property\nthen use reduce() method to iterate through result of Object.entries. At each iteration, you are making a decision whether key_x contains array with length > 0\n\nSo the code looks like this:\nconst result = Object.entries(obj).reduce((a, [k,v])=> {\n if (v.length > 0) {\n a[k] = v;\n }\n return a;\n},{})\n\nAn example:\n\nconst obj = {\n 'key1': [],\n 'key2': ['val1', 'val2'],\n 'key3': [],\n 'key4': ['val3']\n };\n\n const result = Object.entries(obj).reduce((a, [k,v])=> {\n if (v.length > 0) {\n a[k] = v;\n }\n return a;\n },{})\n\n console.log(result);\n\n"} +{"text": "Q:\n\nTCP kernel implementation\n\nI have developed a new TCP congestion avoidance algorithm which I want to implement in the linux kernel and test its performance. But for this I need to understand the existing TCP kernel (2.6) implementation. How do you suggest I should proceed with this? Please suggest some articles/books etc which can give me a head start. I know I will have to eventually dive into the source code but it would be helpful if I at least know broad implementation aspects and how to navigate through the code.\n\nA:\n\nI would just dive directly into the source code of the simpler congestion avoidance algorithms already in the kernel. They're in the net/ipv4 directory, and tcp_vegas.c is pretty thoroughly commented. You may also wish to look at tcp_highspeed.c and tcp_bic.c because they're fairly simple (fewer than 250 lines of code).\n\n"} +{"text": "Q:\n\nCreate Apache mod rewrite rule to process all request to subdirectory\n\nI want to redirect all incoming requests to a subdirectory, but can't figure out how. I looked here but that did not work for me.\nSo, if someone visits www.example.com/test, I want it to redirect to: www.example.com/test/subdirectory, but the URL still needs to be www.example.com/test\nI also need the parameters to work, for example www.example.com/test/index.php?action=home must redirect to www.example.com/test/subdirectory/index.php?action=home.\nI hope someone can help me!\n\nA:\n\nSo in fact what you ask for is not a redirect.\nA redirect means the web server will send a new url containing the subdirectory, the browser will then request this new url, and show it in the url bar of the browser.\nWhat you want is to tranparently map an directory structure to a real directory structure which differs. This is what Apache can do easily with the Alias instruction. Mod-rewrite could also do that, with RewriteRules not containing the [R] tag, this would imply an internal rewrite, not a redirect HTTP response. A [QSA] tag would also tell mod-rewrite to keep the current query string parameters on the rewritten url. But Mod-rewrite is not always simple to understand, and your problem is simple enough for a basic Alias, which is almost always included in Apache (more often than mod-rewrite).\nthis should be ok:\nAlias /test /test/subdirectory\n\n"} +{"text": "Q:\n\nPython shlex.split(), ignore single quotes\n\nHow, in Python, can I use shlex.split() or similar to split strings, preserving only double quotes? For example, if the input is \"hello, world\" is what 'i say' then the output would be [\"hello, world\", \"is\", \"what\", \"'i\", \"say'\"].\n\nA:\n\nimport shlex\n\ndef newSplit(value):\n lex = shlex.shlex(value)\n lex.quotes = '\"'\n lex.whitespace_split = True\n lex.commenters = ''\n return list(lex)\n\nprint newSplit('''This string has \"some double quotes\" and 'some single quotes'.''')\n\nA:\n\nYou can use shlex.quotes to control which characters will be considered string quotes. You'll need to modify shlex.wordchars as well, to keep the ' with the i and the say.\nimport shlex\n\ninput = '\"hello, world\" is what \\'i say\\''\nlexer = shlex.shlex(input)\nlexer.quotes = '\"'\nlexer.wordchars += '\\''\n\noutput = list(lexer)\n# ['\"hello, world\"', 'is', 'what', \"'i\", \"say'\"]\n\n"} +{"text": "Q:\n\ntextFieldDidBeginEditing: is not called although delegate is connected\n\nHere is my code:\nIn .h file\n@interface VTViewController : UIViewController \n\nIn .m file\n- (void)viewDidLoad\n{\n [super viewDidLoad];\n // Do any additional setup after loading the view.\n self.postText.delegate = self;\n\n}\n\n#pragma mark - textField delegate\n\n- (void)textViewDidBeginEditing:(UITextView *)textView {\n NSLog(@\"textViewDidBeginEditing:\");\n}\n\n- (void)textViewDidEndEditing:(UITextView *)textView{\n NSLog(@\"textViewDidEndEditing:\");\n}\n\n- (BOOL)textFieldShouldReturn:(UITextField *)textField {\n [textField resignFirstResponder];\n return NO;\n}\n\nThe last one works, the first two do not since I do not see the NSLog being printed. I also tried connected the textfield in the IB.\n\nA:\n\nYou are mixing your methods up - some are text view methods and some are text field methods. Check the names from the appropriate delegate protocols and replace as required.\n\n"} +{"text": "Q:\n\nUpdating data with jQuery Mobile\n\nI have a simple form that contains the jquery UI date picker and basically when the date changes I want to refresh my data (go and get all records based on date).\nHowever i have no idea how to do refresh the data?\nSo looking for advice and simple example if you could help please.\n@model ViewModels.ScheduleMobileDisplay\n@{\n ViewBag.Title = \"Test\";\n Layout = \"~/Views/Shared/_AppHomeLayout.Iphone.cshtml\";\n\n}\n\n@using (Html.BeginForm())\n{\n{\n
\n \n \n
\n\n \n\n \n
\n\n
\n\n}\n\nA:\n\nYou'd want to make an ajax call to a webservice to get the data, then update your page in the ajax call's success callback. \n$.ajax('www.mywebsite.com/myserviceurl', {\n contentType: 'application/json; charset=utf-8',\n dataType: 'json',\n data: messageData,\n type: 'POST',\n timeout: 20000,\n success: function(data) {\n /* update page here */\n },\n error: function(jqXHR, textStatus, errorThrown) {\n console.log(errorThrown);\n }\n});\n\n"} +{"text": "Q:\n\nWhen I reopen the program is everything fades in txt file\n\nI have a code like that,\ndatabase = open(r\"C:\\Users\\PC\\Desktop\\database.txt\", \"w\")\n\nprint(\"Please type 1 if add a film\")\n\nenter = input(\"Enter: \")\n\nif enter == \"1\":\n film=input(\"Please write a film name: \")\n database.write(film)\n database.close()\n\nWhen I reopen the program is everything fades in txt file.How I do before writing what I write is saved under :)\n\nA:\n\nUse the a mode.\ndatabase = open(r\"C:\\Users\\PC\\Desktop\\database.txt\", \"a\")\n\nThe w mode will truncate the file when you open it (rewriting the file), while this will append to the end of the file.\nTo append into a new line, simply:\nif enter == \"1\":\n film=input(\"Please write a film name: \")\n database.write(film + \"\\n\") #\\n is the newline character\n database.close()\n\n"} +{"text": "Q:\n\nHtml and css Trying to put image\n\nI am trying to put image to above of my video but it won't show up, only little mark top of the left side ? I know this is maybe simple but I don't get it.Maybe add something to css and change that images code place ?\n\n\n\n \n\n\n\n\n\n\n
\n\n
\n
\n \n
\n \n
\n
\n
\n
\n
\n

\n
\n
\n
Hello and Welcome --------------
\n\n
\n\n
\n\n\n\n\n\nCSS:\n\nbody {\nmargin:0;\npadding:0;\nmin-width:525px;\nfont-family: Arial;\nfont-size: 17px;\nbackground-image:url('fifa2.jpg');\n}\n\n#header {\nfloat: left;\nwidth: 100%;\nheight: 100px;\nposition: absolute;\n}\n\n#footer {\nfloat: left;\nwidth: 100%;\nbackground-color: #000000;\nfont-size: 14pt;\nfont-weight: bold;\ntext-align: center;\nposition: absolute;\nheight: 40px;\nleft: 0px;\nbottom: 0px;\n}\n\n#wrapper {\npadding-left: 200px;\npadding-right: 125px;\noverflow: hidden;\n}\n\n#left_side {\nposition: relative;\nfloat: left;\nwidth: 200px;\nright: 200px;\nmargin-left: -100%;\npadding-bottom: 2000px;\nmargin-bottom: -2000px;\n}\n\n#right_side {\nposition: relative;\nfloat: left;\nwidth: 125px;\nbackground-color: #66CCCC;\nmargin-right: -125px;\npadding-bottom: 2000px;\nmargin-bottom: -2000px;\n}\n\n#content_area {\nposition: relative;\nfloat: left;\nwidth: 100%;\npadding-bottom: 2000px;\nmargin-bottom: -2000px;\n}\n\n#nav {\nbackground-color: #222;\n}\n#nav_wrapper {\nwidth: 335px;\nmargin: 0 auto;\ntext-align: left;\n}\n#nav ul {\nlist-style-type: none;\npadding: 0;\nmargin: 0;\nposition: relative;\nmin-width: 200px;\n}\n#nav ul li {\ndisplay: inline-block;\n}\n#nav ul li:hover {\nbackground-color: #333;\n}\n#nav ul li a, visited {\ncolor: #CCC;\ndisplay: block;\npadding: 15px;\ntext-decoration: none;\n}\n#nav ul li:hover ul {\ndisplay: block;\n}\n#nav ul ul {\ndisplay: none;\nposition: absolute;\nbackground-color: #333;\nborder: 5px solid #222;\nborder-top: 0;\nmargin-left: -5px;\n}\n#nav ul ul li {\ndisplay: block;\n}\n#nav ul ul li a:hover {\ncolor: #699;\n}\n\nvideo {\nmargin-top: 250px;\n}\n\n![My page][1]\n\nLink to image: [1]: http://i.stack.imgur.com/AARLw.jpg\n\nA:\n\nSet css position form image and video elements as:\nimg{\n position:absolute;\n}\n\nvideo{\n position:relative;\n}\n\n"} +{"text": "Q:\n\nCannot start Docker in Azure Shell\n\nWhen in Azure Shell I type the following\nPS Azure:\\> systemctl start docker.service\n\nI get the following error message\n\nError getting authority: Error initializing authority: Could not\n connect: No such file or directory (g-io-error-quark, 1) Failed to\n connect to bus: No such file or directory\n\nHow can I resolve it?\nThank you in advance\n\nA:\n\nAzure Cloud Shell offers a browser-accessible, pre-configured shell experience for managing Azure resources without the overhead of installing, versioning, and maintaining a machine yourself. You could read the supported features and tools here.\nMoreover, you could not run the docker daemon in the Azure cloud shell since Cloud Shell utilizes a container to host your shell environment, as a result running the daemon is disallowed. You could Utilize docker-machine to manage Docker containers from a remote Docker host.\n\n"} +{"text": "Q:\n\nRed Circle Around Custom Android Button Image\n\nI have created a floating action button, and made my own image (at each of dpi sizes), but there is a red circle around it (image below). Here is my xml defining the button \n\n\nHere is my source image (@192x192), and a screenshot of what i'm seeing in android studio.\n\nA:\n\nYou can try the below -\n \n\nsetting tint to transparent will override that primary color pink you have given in styles.\n\nA:\n\nEDIT 2 \nNo need to use app:backgroundTint juse USE android:scaleType=\"center\" in your FloatingActionButton it will work\n\n\nOUTPUT\n\nTry this\n\n\nandroid:src=\"@drawable/add_plant\"\n\n\n \n\n\nOUTPUT\n\nEDIT\nTo support vector drawablea add this in your build.gradle file\ndefaultConfig {\n vectorDrawables.useSupportLibrary = true\n }\n\n"} +{"text": "Q:\n\nIs it possible to import XML or JSON data from a table within a Word online document into Apps Script website as an HTML table?\n\nI am building a web app using Apps Script.\nIn this web app I have a table that needs to be populated from a table in a Word doc in OneDrive.\nThis document is updated regularly, so I would prefer to programmatically update the content of the html table in Apps Script.\nIs this possible?\nIf so, can anyone give me guidance as to how to accomplish this?\nI've started looking into importing xml from a url, but I'm not sure that I'm on the right track.\n\nA:\n\nYou need to incorporate the following steps\n\nRead your data into a Google Apps function, e.g. with OneDriveApp as recommended by Cooper\nUse google.script.run to call the Apps Script function from you html file\nIncorporate a Web Polling function that updates your html table with fresh contents in desired intervals\n\nSample:\n\ncode.gs\n\nfunction doGet(){\n return HtmlService.createHtmlOutputFromFile('index');\n}\nfunction getFreshData(){\n //read here your Word Doc data, e.g. with One DriveApp and store it e.g. in an array\n ...\n return myDataArray;\n}\n\nindex.html\n\n...\n\n...\n \n...\n\n"} +{"text": "Q:\n\nMSTest: How to assert positive if one of 3 asserts are valid?\n\nI have an IntegrationTest where I want to test the result of a linq query.\nThe linq query goes something like this \nwhere myObject.fieldA.StartsWith(aString) \n || myObject.fieldB.StartsWith(aString) \n || myObject.fieldC.StartsWith(aString)\n\nNow I want write the test like so:\nforeach(var result in results)\n{\n StringAssert.StartsWith(result.fieldA, aString);\n StringAssert.StartsWith(result.fieldB, aString);\n StringAssert.StartsWith(result.fieldC, aString); \n}\n\nbut of course that is not correct, because it should assert valid when one of the 3 above is valid.\nAny idea how to do that using MSTest ?\n\nA:\n\nYou can work around it by using \nAssert.IsTrue(\n result.fieldA.StartsWith(astring) || \n result.fieldB.StartsWith(astring) ||\n result.fieldC.StartsWith(astring)\n);\n\n"} +{"text": "Q:\n\nIs passing data between directives, controllers, and services using $emit and $broadcast bad practice?\n\nHi I'm a beginning Angular developer and I was wondering if the way I've passed data between controllers is bad practice or not. \nI'm creating a seatmap widget whereby you click on a seat and it will display data in another part of the App using a different controller. \n1) I have a directive that incorporates dynamic templating. Based on the model being passed (from an ng-repeat), it will create an event listener like so:\nif(scope.seat.isAvailable) {\n element.bind('click', function() {\n scope.$emit('clickedSeat', scope.seat);\n }\n element.append(seatAvailableTemplate);\n}\n\n2) In my controller, I have the following listening for the click:\n$scope.$on('clickedSeat', function(event, seat) {\n seatSelectionService.broadcastSeatData(seat);\n}\n\n3) I have a service where I've passed in $rootScope which allows me to broadcast the data to a different controller:\nvar seatSelectionService = {};\nseatSelectionService.broadcastSeatData = function(clickedSeat) {\n seatSelectionService.seatData = clickedSeat;\n $rootScope.$broadcast('seatSelected');\n}\nreturn seatSelectionService;\n\n4) In the other controller, I have a listener which sets the $scope attribute, which renders {{selectedSeat}} in the view:\n$scope.$on('seatSelected', function() {\n $scope.selectedSeat = seatSelectionService.seatData;\n $scope.apply();\n} \n\nOf course I have had to pass in seatSelectionService into both controllers for it to work. \nIs there a better way to do this? Or is this way of passing data valid practice?\n\nA:\n\n$broadcast and $emit themselves aren't bad practice, but it does look like you've over complicated your app.\nYou can add services directly to directives - they can have controllers built into them that depend on the services.\nSo in your directive, add a controller that uses the seatSelectionService, something like:\nseatSelectionService.setSeat( scope.seat )\n\nWhich cuts out one of the steps at least - your setSeat method would still want to do a $broadcast when it's done down to anything listening.\nDirectives can be really simple or really complex - they can simply be a quick way of outputting a repeated template, or a dynamic template with a controller and access to multiple services.\nSomething else you might want to look at is promises - I used to use $broadcast and $emit a lot more than I needed to, until I learnt how to use promises and defer properly \n\n"} +{"text": "Q:\n\nFirefox/Chrome Web Extension - Security Error When Trying To Inject IFrame Through Content Script\n\nI have the following really simple code in a content script that runs whenever a button in my \"popup.html\" file is pressed:\nSection of code inside \"inject.js\"\nbrowser.runtime.onMessage.addListener((message) => {\n console.log(\"Trying to inject iFrame\");\n var iframe = document.createElement(\"iframe\");\n iframe.src = browser.extension.getURL(\"inject.html\");\n document.body.appendChild(iframe);\n});\n\nThe content of \"inject.html\" is:\n\n\n\n\n\n\n\n

\n Hello. This is a Test.\n

\n\n\n\n\nHowever, when this code runs I get the following output in the console (Using \"example.com: as an example URL):\n\nTrying to inject iFrame\n Security Error: Content at http://example.com/ may not load or link to moz-extension://218287b3-46eb-4cf6-a27f-45b9369c0cd9/inject.html.\n\nHere is my \"manifest.json\"\n{\n\"manifest_version\": 2,\n\"name\": \"Summarizer\",\n\"version\": \"1.0\",\n\n\"description\": \"Summarizes webpages\",\n\n\"permissions\": [\n \"activeTab\",\n \"tabs\",\n \"storage\",\n \"downloads\",\n \"*://*.smmry.com/*\"\n],\n\n\"icons\":\n{\n \"48\": \"icons/border-48.png\"\n},\n\n\"browser_action\":\n{\n \"browser_style\": true,\n \"default_popup\": \"popup/choose_length_page.html\",\n \"default_icon\":\n {\n \"16\": \"icons/summarizer-icon-16.png\",\n \"32\": \"icons/summarizer-icon-32.png\"\n }\n}\n\n\"web_accessible_resources\": [\n \"inject.html\"\n]\n}\n\nAnd, lastly, here is the top level file structure of my extension:\n\nHow can I fix this security error? \nThis is not a duplicate of this: Security error in Firefox WebExtension when trying getUrl image because I provided the full path in my manifest.json\n\nA:\n\nI was missing a comma. Here is the relevant portion of the manifest.json with the comma in place:\n\"browser_action\":\n{\n \"browser_style\": true,\n \"default_popup\": \"popup/choose_length_page.html\",\n \"default_icon\":\n {\n \"16\": \"icons/summarizer-icon-16.png\",\n \"32\": \"icons/summarizer-icon-32.png\"\n }\n},\n\n\"web_accessible_resources\": [\n \"inject.html\"\n]\n\n"} +{"text": "Q:\n\nHow can I toggle the margin of an element using JavaScript?\n\nI am trying to move a div to the side, and back, with a transition, by changing the margin. I have one button that I want to toggle it's margin. The div moves to the right,but when I click again, it doesn't move back to it's original position. This is what I have:\nHTML\n\n\nCSS\n#movingdiv {\noverflow: hidden;\nleft: 0;\ntop: 0;\nright: 0;\nbottom: 0;\nbackground-color: gray;\n-webkit-transition-duration: 0.3s;\n-moz-transition-duration: 0.3s;\n-o-transition-duration: 0.3s;\ntransition-duration: 0.3s;\n}\n\nJavaScript\nfunction toggle () {\n\nvar el = document.getElementById(\"movingdiv\");\nif ( el.style.marginLeft=\"250px\" ) {\n\n el.style.marginLeft=\"250px\";\n\n}\n\nelse {\n\n el.style.marginLeft=\"0px\";\n\n}\n\n}\n\nHere it is in action:\nhttp://codepen.io/dakoder/pen/nfimJ\n\nA:\n\nYou're making an assignment, instead of checking equality. In addition, you have your else condition and if condition mixed. Change it to the following:\nif ( el.style.marginLeft===\"250px\" ) {\n el.style.marginLeft=\"0px\";\n} else {\n el.style.marginLeft=\"250px\";\n}\n\n"} +{"text": "Q:\n\nHow to hide products in Shopify search results based on a vendor name\n\nI'm in a situation where hiding a certain vendors products in the control panel isn't an options due to an outside POS. For a test in search.liquid, I used search.terms like below. This code works but not everyone will type thevendor exactly the same way and will see the products if they don't type thevendor. \n{% for item in search.results %}\n{% if search.terms == 'thevendor' %}\n{% else %}\n{% include 'search-result' %}\n{% endif %}\n{% endfor %}\n\nI tried to figure out how to write the code to hide these products in a better way. I tried product.vendor like below but when I search for those products individually they are not hidden. The code: \n{% for item in search.results %}\n{% if product.vendor == 'thevendor' %}\n{% else %}\n{% include 'search-result' %}\n{% endif %}\n{% endfor %}\n\nCan someone tell me what I'm missing here? It seems it doesn't know what product.vendor is but when I print out who the vendor is, it displays the vendor. I don't understand why it's not hiding the products that are associated with this vendor. \n\nA:\n\n{% for item in search.results %}\n{% if item.product.vendor == 'thevendor' %}\n{% else %}\n{% include 'search-result' %}\n{% endif %}\n{% endfor %}\n\nThis should work.\n\n"} +{"text": "Q:\n\nAnimate layout on different activities on android 4.4(kitkat) and higher\n\nNow this specific page does describe a way to animate between layouts of different activities, but the problem is that the API is only supported for android 5.0 and higher, so I'd like to know what are the ways in which animation(like transition or any other type of fade/slide in etc.) could be done for layouts in two different activities.\n\nA:\n\nYou can't set transitions on your theme prior to Lollipop version but you can still use animations programmatically. \nHere\u2019s an example with animations that slide the new activity in when first created, and the opposite movement when you press the back button. \nleft_in.xml\n\n\n //in milliseconds\n\n\nright_in.xml\n\n\n \n\n\nleft_out.xml\n\n\n \n\n\nright_out.xml\n\n\n \n\n\nOn your activities you can call the animations as follows:\nOn start: overridePendingTransition(R.anim.right_in, R.anim.left_out);\nOn Back Pressed: overridePendingTransition(R.anim.left_in, R.anim.right_out);\nOr any combination of the above.\nNote that the first animation on overridePendingTransition is for the incoming activity and the second for the outgoing activity.\n\n"} +{"text": "Q:\n\niOS Mapkit - Cache maps?\n\nI need maps of certain areas available when no internet connection is available.\nIt would be like this:\n\nUser loads app internet connection is available\nApp downloads list of coordinates and places pins on the map\nUser leaves their house and has no internet connection\nPins and map remain readily available for user to interact with, even without internet connection\n\nHow do I do this?\n\nA:\n\nYou probably won't use MKMapView and MapKit for that, but the Google Maps Static API that allows you to download static images (even with pins on it) directly.\nHere is the example given by the Google Maps API doc itself\nThen you can store this image and display it in an UIImageView in a UIScrollView for example.\n\n"} +{"text": "Q:\n\nUnits in Polynomial Rings\n\nGive an example of a natural number $n > 1$ and a polynomial $f(x) \u2208 \\Bbb Z_n[x]$ of degree $> 0$ that is a unit in $\\Bbb Z_n[x]$.\nI am trying to understand how units work in polynomial rings. My book doesn't really define it and I need a bit of help with this.\n\nA:\n\nHint: Note that $(2x+1)(2x+1)=1$ in $\\mathbb{Z}_4$.\nFor another example, use $\\mathbb{Z}_9$. Note that $(3x+1)(6x+1)=1$, so $3x+1$ has a multiplicative inverse.\n\n"} +{"text": "Q:\n\nUnable to assign data to specific index of array in javascript\n\nlet new_json = {\n sessions: []\n};\n\nnew_json.sessions[0][\"timing\"] = []\n\nError:\nVM73:1 Uncaught TypeError: Cannot set property 'timing' of undefined\n at :1:32\n(anonymous) @ VM73:1\n\nHere I am trying to add data to one index of the array\nBut, getting above error while doing this.\nIs there any way to do this?\nPlease have a look\n\nA:\n\nFirst initialize the object at 0th position and the add the value like this \nnew_json.sessions[0] = {};\nnew_json.sessions[0][\"timing\"] = []\n\n"} +{"text": "Q:\n\nWhat to do when I have energy loss due to distance\n\nI have to connect a total of 15 12 V, 2 A motors in parallel.\nThey are all going to be connected to a battery and I\u2019m trying to bring a line to connect all 15 of them. The distance between them is 25 meters. What can I do to reduce the energy loss due to the distance?\n\nA:\n\nEveryone seems to be suggesting the thicker wire route here.. but you do have a different option.\nYour other alternative is to either use a boost convertor to convert your 12V into a high DC voltage or use an invertor to make high voltage AC and transmit that down cheaper cabling instead. Then add DC-DC or AC-DC power regulators at each motor.\nThat may seem extreme, but you need to do a cost comparison of which is cheaper. Big beefy hard to manage cables, or cheap wiring and low cost convertors.\nThe other benefit of this route is you separate the power transfer efficiency issue from the target voltage-drop issue. That is, the system ought to be 100% functional despite the transmission costs.\n\n"} +{"text": "Q:\n\nMake an image clickable to expand\n\nI have a background image that I would like to expand when clicked. I have setup animations that will dim the background and prop the image to the center, but for some reason the image is not clickable. \nI have tried to implement a simple print(tapped) and when I tap I dont see anything as well. I am wondering if I have to declare my image view as something else?\nimport Foundation\nimport UIKit\n\nclass JobViewController: UIViewController {\n\nlet imageView: UIImageView = {\n let iv = UIImageView(image: #imageLiteral(resourceName: \"yo\"))\n iv.contentMode = .scaleAspectFill\n iv.isUserInteractionEnabled = true\n iv.translatesAutoresizingMaskIntoConstraints = false\n iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))\n return iv\n}()\n\n@objc func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {\n print(\"tap tap\")\n\n}\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n\n view.addSubview(imageView)\n imageView.fillSuperview() \n\n}\n}\n\nWhen I tap the image, I expect that it should at least print \"tap tap\"\nIs there something else that i am missing?\n\nA:\n\nDelete this line:\niv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))\n\nAnd add this to your viewDidLoad:\nimageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleZoomTap)))\n\n"} +{"text": "Q:\n\nAnyLogic 7: Excel access library (Apache POI) is not specified\n\nAnyLogic 7: Excel access library (Apache POI) is not specified\nI'm trying to use the AnyLogic ExcelFile class, but it appears that AnyLogic can't find the required Apache POI library:\nError during model startup:\nExcel access library (Apache POI) is not specified (or is specified incorrectly) in the classpath\nCaused by: org/apache/poi/openxml4j/exceptions/InvalidFormatException\nCaused by: org.apache.poi.openxml4j.exceptions.InvalidFormatException\njava.lang.RuntimeException: Excel access library (Apache POI) is not specified (or is specified incorrectly) in the classpath\n at com.xj.anylogic.engine.Engine.a(Unknown Source)\n at com.xj.anylogic.engine.Engine.start(Unknown Source)\n at com.xj.anylogic.engine.ExperimentSimulation.b(Unknown Source)\n at com.xj.anylogic.engine.ExperimentSimulation.run(Unknown Source)\n at generic_agent_based_model_with_births_and_deaths.Simulation.executeShapeControlAction(Simulation.java:107)\nCaused by: java.lang.NoClassDefFoundError: org/apache/poi/openxml4j/exceptions/InvalidFormatException\n at generic_agent_based_model_with_births_and_deaths.ExcelDataSource.onStartup(ExcelDataSource.java:668)\n at generic_agent_based_model_with_births_and_deaths.ExcelDataSource.start(ExcelDataSource.java:652)\n at generic_agent_based_model_with_births_and_deaths.Main.start(Main.java:1046)\n ... 4 more\nCaused by: java.lang.ClassNotFoundException: org.apache.poi.openxml4j.exceptions.InvalidFormatException\n at java.net.URLClassLoader$1.run(URLClassLoader.java:202)\n at java.security.AccessController.doPrivileged(Native Method)\n at java.net.URLClassLoader.findClass(URLClassLoader.java:190)\n at java.lang.ClassLoader.loadClass(ClassLoader.java:307)\n at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)\n at java.lang.ClassLoader.loadClass(ClassLoader.java:248)\n ... 7 more\n\nHow do I fix this? \nSome notes:\n\nI am working with a model initially developed by someone else. I am assuming the model was initially built for AnyLogic 6.9, but I am using AnyLogic 7.0.3.\nI assume that AnyLogic is supposed to import the POI library automatically: any idea what it did wrong / what I did wrong to cause AnyLogic to fail?\nTo head off any confusion, ExcelDataSource is a wrapper class I've created to simplify ExcelFile for our use case.\n\nThanks in advance! \n\nA:\n\nAnyLogic uses Apache POI library for working with Excel spreadsheets. But it is disabled by default as unnecessary. You should drop Excel File element from Connectivity palette to be able to use Apache POI methods. Another way - add the library to model dependencies list (see Dependencies section of the model properties view).\n\n"} +{"text": "Q:\n\nHow to use gwtbootstrap3 calendar with UiBinder\n\nCan we use gwtbootstrap3 fullcalendar mentioned at http://gwtbootstrap3.github.io/gwtbootstrap3-demo/#fullcalendar with UiBinder. \nI am trying to use it with UiBinder and nothing is appearing on that page. \ncode to my UiBinder class\n\n\n \n \n \n\ncode to the corresponding view class\npublic class EventView extends ReverseCompositeView implements IEventView {\n\n private static EventViewUiBinder uiBinder = GWT.create( EventViewUiBinder.class );\n\n interface EventViewUiBinder extends UiBinder {\n }\n\n @UiField\n HTMLPanel calendarContainer;\n\n @Override\n public void createView() {\n //don't create the view before to take advantage of the lazy loading mechanism\n initializeCalendar();\n initWidget( uiBinder.createAndBindUi( this ) );\n }\n\n private void initializeCalendar() {\n final FullCalendar fc = new FullCalendar(\"event-calendar\", ViewOption.month, true);\n fc.addLoadHandler(new LoadHandler() {\n @Override\n public void onLoad(LoadEvent loadEvent) {\n addEvents();\n }\n\n private void addEvents() {\n for (int i = 0; i < 15; i++) {\n Event calEvent = new Event(\"id \"+ i, \"this is event \"+i);\n int day = Random.nextInt(10);\n Date start = new Date();\n CalendarUtil.addDaysToDate(start, -1 * day);\n calEvent.setStart(start);\n if(i%3 ==0){\n calEvent.setAllDay(true);\n }else{\n Date d = new Date(start.getTime());\n d.setHours(d.getHours()+1);\n calEvent.setEnd(d);\n }\n fc.addEvent(calEvent);\n }\n }\n\n });\n\n calendarContainer.add(fc);\n }\n\n}\n\nand I am using mvp4g framework. \n\nA:\n\ninitializeCalendar();\ninitWidget( uiBinder.createAndBindUi( this ) );\n\nYou should first init the widget and then initialize the calendar. This is because you are adding your FullCalendar to the calendarContainer HTMLPanel in initializeCalendar. And before the call to initWidget, calendarContainer is null.\nI think you can go a step further and do it like this:\n\n\n \n \n \n\n\nAnd then in your EventView:\n@UiField(provided = true) FullCalendar fullCalendar;\n\n@UiField(provided = true) means it's up to you to initialize this widget before calling initWidget. So, in this case, the order:\ninitializeCalendar();\ninitWidget( uiBinder.createAndBindUi( this ) );\n\nis OK. Additionally, you don't have to add the FullCalendar to any panel anymore - it's already added, you just have to initialize it.\n\n"} +{"text": "Q:\n\nPassing Structures between Managed and Unmanaged Code\n\nI call c++/cli method from c# in this method:\n bool SetProperty(Element element, Node referencePoint, List materializers, List properties)\n {\n\n // Loop over STLs\n for (int i = 0; i < materializers.Count; i++)\n { \n Materializer materializer = materializers[i];\n PentalTreeNode pentalTreeRoot = pentalTreeDatasets[i].top;\n\n if (materializer.IsPointInside(referencePoint.X, referencePoint.Y, referencePoint.Z, pentalTreeRoot))\n {\n element.PropertyId = properties[i];\n return true;\n };\n\n }\n\n return false;\n }\n\nC++/cli method is this:\nbool IsPointInside(double x, double y, double z, PentalTreeNode ^root)\n {\n int intersectionCount = 0;\n\n Math3d::M3d rayPoints[2], intersectionPoint;\n\n rayPoints[0].set(x,y,z);\n rayPoints[1].set(x,y,1.0e6);\n\n if(_box->IsContainingPoint(x,y,z))\n { \n intersectionCount=CountIntersects(x,y,z,root);\n return (intersectionCount%2!=0);\n\n } \n\n }\n\nWhat is wrong, because c++/cli method doesn't return always the same result?\nHow to pin or marshal?\nMethod in c++/cli(Maybe this not ok?):\nint CountIntersects(double x, double y, double z, PentalTreeNode ^root)\n {\n\n Math3d::M3d rayPoints[2], intersectionPoint;\n\n rayPoints[0].set(x,y,z);\n rayPoints[1].set(x,y,1.0e6);\n\n if(!root) \n return 0;\n else\n {\n int special = CountIntersects(x,y,z,root->special);\n if (x <= root->xMax && x >= root->xMin && y <= root->yMax && y >= root->yMin)\n {\n\n if( _stlMesh->IsRayIntersectsPoly(root->index, rayPoints, intersectionPoint))\n {\n return (1 + special);\n }\n else \n return special;\n }\n else\n {\n if (y>root->yMax)\n {\n return (CountIntersects(x,y,z,root->top)+special);\n }\n else if(yyMin)\n {\n return (CountIntersects(x,y,z,root->bottom)+special);\n }\n else if(xxMin)\n {\n return (CountIntersects(x,y,z,root->left)+special);\n }\n else if(x>root->xMax)\n {\n return (CountIntersects(x,y,z,root->right)+special);\n }\n else \n return special;\n }\n\n }\n\n }\n\nA:\n\nif( _stlMesh->IsRayIntersectsPoly(root->index, rayPoints, intersectionPoint))\n\nThere's one possible flaw in this particular statement, you've never initialized intersectionPoint. C++ lets you get away with this, it doesn't have anything similar to C#'s definite assignment rules. It isn't 100% clear whether that's the real problem, the variable might be passed by reference.\nIn the Debug build, such an uninitialized variable will have a predictable value. Something you can easily see in the debugger when you switch it to hexadecimal display mode. Fields in this struct or class will contain the value 0xcccccccc, a value that's apt to generate nonsensical results or crash your code with an access violation. In the Release build, the /RTC option isn't turned on and you'll get entirely random values in the variable.\nWhich corresponds very well with the description of your problem, so high odds that this is indeed the problem. Be sure to use the debugger to find problems like this, you can easily see the value of local variables with the Autos debugger window as you single-step through the code.\n\n"} +{"text": "Q:\n\nHow many records does SNSEvent Object's getRecords() return?\n\nHow many records will be returned and how does it actually work?\npublic String handleRequest(SNSEvent snsEvent, Context context) {\n List records = snsEvent.getRecords();\n System.out.println(\"Size \"+ records.size());\n return \"success\";\n} \n\nA:\n\nRead the docs:\n\nQ: Will a notification contain more than one message?\nNo, all notification messages will contain a single published message.\n\n"} +{"text": "Q:\n\nError when using STXXL Autogrow\n\nI'm currently working on a project that requires about 20 vectors to be written to individual files. I also need my STXXL disk file to grow automatically to account for very large vectors. I understand that STXXL provides autogrow functionality for disk files if you specify the size in the .stxxl file to be 0. I have done this but I get an IO error when creating my first vector.\nMy .stxxl file is as follows:\ndisk=c:\\stxxl,0,wincall\nand I'm creating my vectors like so:\nstxxl::wincall_file file(\"file.dat\", stxxl::file::CREAT | stxxl::file::RDWR);\nstxxl::vector> vector1(&file, 1000000);\nCan anyone help me fix this?\nThanks!\n\nA:\n\nSo, to answer my own question here, I believe the problem was trying to create a disk file directly at the root of the C drive. Once I changed the path in my .stxxl file to an absolute path off my user directory, it worked no problem, autogrow and all!\n\n"} +{"text": "Q:\n\nPassing text-box value from view to action method and return true false on given condition\n\nI have a text box and a button. If I put \"adm\" in the text box and click on the button, the value will get passed to the controller to an action method. There it will check whether the given value in the text box is \"adm\" or not. If its \"adm\" then it will show \"true\" in an alert box and if its not \"adm\" then it will return \"false\" in an alert box.\nI am confused how to implement the whole thing. Please help.\nI have been told to use jquery for that by my faculty.\nThis is my Controller.\npublic class HomeController : Controller\n {\n public ActionResult Index()\n {\n return View();\n }\n public ActionResult Download(string name)\n {\n return View();\n }\n }\n\nThis is my view.\n\n\n\n\nA:\n\nYou need to change your controller method to\npublic ActionResult Download(string name)\n{\n if (name == \"adm)\n {\n return Json(true, JsonRequestBehavior.AllowGet);\n }\n else\n {\n return Json(false, JsonRequestBehavior.AllowGet);\n }\n}\n\nand then in the script\n$(document).ready(function () {\n var url = '@Url.Action(\"Download\")'; // add controller name is necessary\n $('#button1').click(function () {\n $.getJSON(url, { name: $('#text1').val() }, function(response) {\n alert(response);\n });\n });\n});\n\nalthough you could avoid the server call and just do the check on the client using\n$('#button1').click(function () {\n alert($('#text1').val() == 'adm')\n});\n\n"} +{"text": "Q:\n\nInsert an element into a sorted array\n\nI wrote this function to insert an element into a sorted array such that array would still be sorted after adding the element. \nBut something is wrong. I know that my code has a lot of edge cases and probably I'm over complicating the algorithm but I really want to fix it.\n\nMy Code :\n\nprivate static void insert(E e, E[] arr, int count, Comparator comp) {\n if (count == 0) arr[0] = e;\n\n for (int i = 0; i < count; i++) {\n if (comp.compare(arr[i], e) >= 0) {\n // we found an element that is >= to e\n // we want to add new element at index i, currently arr[i] is occupied\n // by larger element, so we need to adjust\n if (i != 0) {\n i--;\n } else {\n // do nothing\n }\n } else if (i + 1 == count) {\n // this is the last iteration of the loop so we want to add element at i + 1\n i++;\n } else {\n // keep looping to find an element\n continue;\n }\n\n // we need to move elements to the right to make space\n for (int j = count; j > i; j--) {\n arr[j] = arr[j - 1];\n }\n\n arr[i] = e;\n break;\n }\n}\n\nMy repo\n\nA:\n\nI fixed the code, I should have not decremented i\nprivate void insert(E e, E[] arr, int count, Comparator comp) {\n if (count == 0) {\n arr[0] = e;\n return;\n }\n\n for (int i = 0; i < count; i++) {\n if (comp.compare(arr[i], e) >= 0) {\n // we found an element that is >= to e\n // we want to add new element at index i, currently arr[i] is occupied\n // by larger element, so we need to adjust\n } else if (i + 1 == count) {\n // this is the last iteration of the loop so we want to add element at i + 1\n i++;\n } else {\n // keep looping to find an element\n continue;\n }\n\n // we need to move elements to the right to make space\n for (int j = count; j > i; j--) {\n arr[j] = arr[j - 1];\n }\n\n arr[i] = e;\n break;\n }\n}\n\n"} +{"text": "Q:\n\nThe $ dollar sign\n\nI have something simple like this:\n$(selector).append(\"somestuff\");\n\nBut since I'm going to reuse the selector I cache it with:\nvar $selector = $(selector);\n\nSo I end up with:\n$selector.append(\"somestuff\");\n\nMy question is, should I be doing that, or should I be doing:\nvar selector = $(selector);\nselector.append(\"somestuff\");\n\nTrying either one, both works. Which method is correct, and why? Is the $ in $selector unnecessary because the jquery object has already been declared in $(selector)?\n\nEdit\nThanks for the answers. It seems very simple and quite clear. Still, there seems to be disagreement over whether or not I should use $ in the variable. It would be nice for everyone to vote up an answer. :)\n\nA:\n\n$ is just a name - names in JavaScript can contain dollar signs, and can consist of just a dollar sign.\nWhether you use a dollar sign in your name isn't relevant to jQuery - there's nothing special about the dollar sign, except that jQuery defines a function called $.\n\nA:\n\nI've seen it done both ways. All you are doing is creating a variable with the name '$selector', so they are functionally equivalent. The nice thing about it is that it does make them easy to pick out as jQuery objects.\n\nA:\n\nThe cash sign is just an alias for the jQuery function. Starting the variable name with $ has no effect on that variable.\nIt is customary though, especially in jQuery plugin development, to use variables already wrapped in jQuery with a cash sign, so you know you can call jQuery methods, without having to wrap them.\n\n"} +{"text": "Q:\n\nStoryboard Zoom In/Out Keyboard Shortcut\n\nWhat shortcut key combination can I use in Xcode to zoom in and out? Yes, I know this is a silly question but a Google search didn't give me any result. Even the Xcode keyboard shortcuts didn't give me much info. Maybe I must ask for a better updated keyboard shortcut doc for Xcode 4.5\n\nA:\n\nYou can also double click with mouse on empty area of storyboard. First time will zoom out, second time - zoom in. Sometimes it's easier than use difficult hotkey.\n\nA:\n\nTry this\nZoom Out = shift+command+alt+{\nZoom In = shift+command+alt+}\nThis worked for me!\n\nA:\n\nFrom Mouse or Trackpad -> Right Click will show you options. Hope this will help\n\n"} +{"text": "Q:\n\nDrag and drop function is not working in chromedriver using selenium webdriver and Node js for Test automation\n\nIs there a way where I can make drag and drop to in selenium using Node.js? I am using the function shown below but it does not seem to work.\ndriver.actions().dragAndDrop(source,destination).perform())\n\nA:\n\nFirst of all, you forgot the build() method.\nSecond of all, inspect the html code and find if your drag&drop is into Iframe tag.\nIf it is, then you need to switch to that Iframe.\nSo: \ndriver.switchTo().frame(driver.findElement(By.xpath(\"PutYourXpathIframe\"))); \n\nActions a = new Actions(driver);\nWebElement source = driver.findElement(By.id(\"PutYourSourceId\"));\nWebElement target = driver.findElement(By.id(\"PutyourTargerId\"));\na.dragAndDrop(source,target).build().perform();\n\nIn the end you may want to switch back to default content: \ndriver.switchTo().defaultContent();\n\n"} +{"text": "Q:\n\n\u041a\u0440\u0430\u0441\u0438\u0432\u043e \u0438 \u044d\u0444\u0444\u0435\u043a\u0442\u0438\u0432\u043d\u043e \u043f\u0440\u043e\u0430\u043d\u0430\u043b\u0438\u0437\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u043c\u0430\u0441\u0441\u0438\u0432\n\n\u041c\u043e\u044f \u0437\u0430\u0434\u0430\u0447\u0430 \u0432 \u043f\u0440\u0438\u043d\u0446\u0438\u043f\u0435 \u0440\u0435\u0448\u0435\u043d\u0430, \u043d\u043e \u043c\u043d\u0435 \u043d\u0435 \u043d\u0440\u0430\u0432\u0438\u0442\u0441\u044f \u043a\u0430\u043a\u0438\u043c \u0441\u043f\u043e\u0441\u043e\u0431\u043e\u043c.\n\u0415\u0441\u0442\u044c \u043c\u0430\u0441\u0441\u0438\u0432 \u0434\u043b\u0438\u043d\u044b > 0 (\u043f\u0443\u0441\u0442\u044c \u0442\u0430\u043c \u0431\u0443\u0434\u0443\u0442 \u0440\u0430\u0437\u043d\u044b\u0435 \u0447\u0438\u0441\u043b\u0430 int \u0434\u043b\u044f \u043f\u0440\u043e\u0441\u0442\u043e\u0442\u044b, \u043d\u0435 \u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u044b). \u041c\u0435\u0442\u043e\u0434 \u0434\u043e\u043b\u0436\u0435\u043d \u0432\u0435\u0440\u043d\u0443\u0442\u044c true, \u0435\u0441\u043b\u0438 \u0432 \u043c\u0430\u0441\u0441\u0438\u0432\u0435 \u043f\u0440\u0438\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044e\u0442 \u0442\u043e\u043b\u044c\u043a\u043e 2 \u0433\u0440\u0443\u043f\u043f\u044b \u0447\u0438\u0441\u0435\u043b \u0438 \u0440\u0430\u0437\u043c\u0435\u0440\u044b \u044d\u0442\u0438\u0445 \u0433\u0440\u0443\u043f\u043f \u0440\u0430\u0432\u043d\u044b \u043b\u0438\u0431\u043e \u043e\u0442\u043b\u0438\u0447\u0430\u044e\u0442\u0441\u044f \u043d\u0430 1. \u041f\u0440\u0438\u043c\u0435\u0440\u044b, \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u044e\u0449\u0438\u0435 true: [3,3,5,5] - 2 \u0433\u0440\u0443\u043f\u043f\u044b: 3 \u0438 5 - \u0432\u0441\u0435 \u043f\u043e 2\u0448\u0442; \u0438\u043b\u0438 [8,8,8,8,2,2,2] - 2 \u0433\u0440\u0443\u043f\u043f\u044b: 8-4\u0448\u0442 \u0438 2-3\u0448\u0442.\n\u041f\u0440\u0438\u043c\u0435\u0440 \u0434\u043b\u044f false: [1,2,3,1,3] - \u0431\u043e\u043b\u044c\u0448\u0435 \u0447\u0435\u043c 2 \u0433\u0440\u0443\u043f\u043f\u044b \u0447\u0438\u0441\u0435\u043b\n\u0411\u0435\u0437 \u0441\u0442\u0440\u0438\u043c\u043e\u0432! \u041e\u0441\u0442\u0430\u043b\u044c\u043d\u043e\u0435 \u043c\u043e\u0436\u043d\u043e - \u0441\u0442\u0430\u043d\u0434\u0430\u0440\u0442\u043d\u044b\u0435 \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430 \u0434\u0436\u0430\u0432\u044b.\n\u041f\u043e\u043a\u0430 \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u043c\u043e\u0435 \u0442\u0430\u043a\u043e\u0435:\npublic boolean satisfiedBy(int[] mainCards) {\n Map rankFrequencies = new TreeMap<>();\n\n for (int rank : mainCards) {\n Integer count = rankFrequencies.get(rank);\n if (count == null)\n count = 0;\n rankFrequencies.put(rank, count + 1);\n\n // check if there is no more than 2 groups\n if (rankFrequencies.size() > 2)\n return false;\n }\n\n if (rankFrequencies.size() != 2)\n return false;\n\n // check if two groups's sizes differs no more than by 1\n Object[] entries = rankFrequencies.entrySet().toArray();\n if (Math.abs(((Map.Entry) entries[0]).getValue() - ((Entry) entries[1]).getValue()) > 1)\n return false;\n\n return true;\n}\n\n\u041d\u0435 \u043d\u0440\u0430\u0432\u0438\u0442\u0441\u044f Object[] entries = rankFrequencies.entrySet().toArray();\n\u0438 \u0435\u0433\u043e \u043f\u0440\u0438\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043a \u043d\u0443\u0436\u043d\u043e\u043c\u0443 \u0442\u0438\u043f\u0443:\nif (Math.abs(((Map.Entry) entries[0]).getValue() - ((Entry) entries[1]).getValue()) > 1)\n\nA:\n\n\u041c\u043d\u0435 \u043a\u0430\u0436\u0435\u0442\u0441\u044f, \u0447\u0442\u043e \u043d\u0430\u0438\u0431\u043e\u043b\u0435\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0439 \u0441\u043f\u043e\u0441\u043e\u0431 \u0432\u044b\u0433\u043b\u044f\u0434\u0438\u0442 \u0442\u0430\u043a:\n\n\u043e\u0431\u043e\u0437\u043d\u0430\u0447\u0438\u043c \u0437\u0430 array[0] \u043f\u0435\u0440\u0432\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442 \u043c\u0430\u0441\u0441\u0438\u0432\u0430\n\u043d\u0430\u0445\u043e\u0434\u0438\u043c \u043b\u044e\u0431\u043e\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442 x, \u043d\u0435 \u0440\u0430\u0432\u043d\u044b\u0439 array[0]\n\u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c, \u0447\u0442\u043e \u043a\u0430\u0436\u0434\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0440\u0430\u0432\u0435\u043d \u043b\u0438\u0431\u043e x, \u043b\u0438\u0431\u043e array[0]\n\u0441\u0447\u0438\u0442\u0430\u0435\u043c \u0447\u0438\u0441\u043b\u043e \u0432\u0445\u043e\u0436\u0434\u0435\u043d\u0438\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432 x \u0438 array[0]\n\u043f\u0440\u043e\u0432\u0435\u0440\u044f\u0435\u043c, \u0447\u0442\u043e \u043e\u043d\u0438 \u0440\u0430\u0437\u043b\u0438\u0447\u0430\u044e\u0442\u0441\u044f \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 \u0447\u0435\u043c \u043d\u0430 \u043e\u0434\u0438\u043d\n\n\u0412\u0430\u0440\u0438\u0430\u043d\u0442 \u0441 \u043e\u0434\u043d\u0438\u043c \u043f\u0440\u043e\u0445\u043e\u0434\u043e\u043c \u043f\u043e \u043c\u0430\u0441\u0441\u0438\u0432\u0443 (\u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 Ideone):\npublic static boolean satisfiedBy(int[] array) {\n Integer anotherValue = null;\n int numberOccurrencesOfFirstElement = 0;\n for (int value : array) {\n if (value == array[0]) {\n ++numberOccurrencesOfFirstElement;\n } else if (anotherValue != null && anotherValue != value) {\n return false;\n } else {\n anotherValue = value;\n }\n }\n return anotherValue != null && Math.abs(array.length - numberOccurrencesOfFirstElement * 2) <= 1;\n}\n\n\u0427\u0443\u0442\u044c \u0431\u043e\u043b\u0435\u0435 \u0447\u0438\u0442\u0430\u0435\u043c\u044b\u0439 \u0432\u0430\u0440\u0438\u0430\u043d\u0442 \u0441 \u0434\u0432\u0443\u043c\u044f \u043f\u0440\u043e\u0445\u043e\u0434\u0430\u043c\u0438 \u043f\u043e \u043c\u0430\u0441\u0441\u0438\u0432\u0443 (\u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 Ideone):\npublic static boolean satisfiedBy(int[] array) {\n int element0 = array[0];\n Integer element1 = null;\n\n for (int value : array)\n if (value != element0)\n element1 = value;\n if (element1 == null)\n return false;\n\n int count0 = 0;\n int count1 = 0;\n for (int value : array) {\n count0 += value == element0 ? 1 : 0;\n count1 += value == element1 ? 1 : 0;\n }\n\n return count0 + count1 == array.length && Math.abs(count0 - count1) <= 1;\n}\n\nA:\n\n\u0414\u0430\u0432\u043d\u043e \u0441 \u0434\u0436\u0430\u0432\u043e\u0439 \u043d\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u043b, \u043f\u043e\u0442\u043e\u043c\u0443 \u044d\u0434\u0430\u043a\u0438\u0439 java-\u043f\u0441\u0435\u0432\u0434\u043e\u043a\u043e\u0434\nMap out = new HashMap<>();\n\nfor (int value : array) {\n out.put(value, out.get(value) == null ? 1 : out.get(value) + 1);\n if( out.size() > 2 ) return false;\n}\n\nreturn Math.abs((out.get(out.keySet.toArray[0]) - out.get(out.keySet.toArray[1]))) < 2;\n\nUPD \u0421\u043d\u0430\u0447\u0430\u043b\u0430 \u043d\u0430\u043f\u0438\u0441\u0430\u043b \u043e\u0442\u0432\u0435\u0442, \u0430 \u043f\u043e\u0442\u043e\u043c \u0432\u043d\u0438\u043c\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u0432\u043e\u043f\u0440\u043e\u0441 \u043f\u0440\u043e\u0447\u0438\u0442\u0430\u043b. :) \u041a\u0430\u043a \u0432\u0438\u0434\u0438\u0442\u0435, \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u043f\u0440\u0430\u043a\u0442\u0438\u0447\u0435\u0441\u043a\u0438 \u043f\u043e\u043b\u043d\u043e\u0441\u0442\u044c\u044e \u0441\u043e\u0432\u043f\u0430\u0434\u0430\u0435\u0442, \u0437\u0430 \u0438\u0441\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\u043c \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u044b\u0445 \u043d\u044e\u0430\u043d\u0441\u043e\u0432. \u0420\u0435\u0448\u0438\u043b \u043d\u0435 \u0443\u0434\u0430\u043b\u044f\u0442\u044c, \u043f\u043e\u0442\u043e\u043c\u0443 \u043a\u0430\u043a \u0432\u0434\u0440\u0443\u0433 \u0447\u0435\u043c-\u0442\u043e \u0434\u0430 \u043f\u043e\u043c\u043e\u0436\u0435\u0442 \u043a\u043e\u0434 \u0443\u043b\u0443\u0447\u0448\u0438\u0442\u044c\n\n"} +{"text": "Q:\n\nXcode added folder in blue and related there files are not compiling\n\nFrom Xcode project right click and Add File to \"projectName\" there I created a NewFolder \"ABCD\" name and added to same \"ABCD\" empty folder to the project its in Blue colour, I expected its in Yellow Color, What the files which I added inside Blue Colour folder files are not compiling in X-Code all files which added in Blue Colour folder say file is not found after compiling the code.\nIs there any why that default, I added folder are link related to the project? \nIts very strange for me this issue, Your feedback is very helpful.\n\nA:\n\nIf you simply drag drop a file and choose Create Folder reference, it will add as a blue folder.\nPlease make sure you select Create Groups from the pop dialogue and make sure u have selected all the targets in Add To Targets section. \nLike this\n\nIt will be added as yellow\n\nGroup-> With groups, Xcode stores in the project a reference to each individual file. This can lead to problems:\nFolder references-> Folder references are simpler. You can spot a folder reference because it shows up in blue instead of yellow.\n\n"} +{"text": "Q:\n\nHow to get a navigation bar hight in iOS programatically\n\nI have to move up my view when keyboardwillshown then it back to it's normal place when keyboard will hide \nActually I have used this code on viewdidload method: \noverride func viewDidLoad() { \n\n NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(\"keyboardWillShow:\"), name: UIKeyboardWillShowNotification, object: nil)\n NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(\"keyboardWillHide:\"), name: UIKeyboardWillHideNotification, object: nil) \n\n}\n\nHere is the method which I used for move up and down \nfunc keyboardWillShow(notification:NSNotification){ \n\n print(\"keyboardwillshow\")\n let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()\n\n self.view.frame = CGRectMake(0.0, -keyboardSize!.size.height + (self.navigationController?.navigationBar.frame.size.height)! + 20 , self.view.frame.size.width, self.view.frame.size.height ) \n\n}\n\nfunc keyboardWillHide(notification:NSNotification){\n\n self.view.frame = CGRectMake(0.0,(self.navigationController?.navigationBar.frame.size.height)!, self.view.frame.size.width, self.view.frame.size.height)\n// self.view.frame.origin.y += 350\n\n}\n\nWhile I run this program, it will show a run time error that is \n\nunexpected found a nil while unwrapping \n\nPlease help me fix this.\n\nA:\n\nWith iPhone-X, height of top bar (navigation bar + status bar) is changed (increased). \nTry this if you want exact height of top bar (both navigation bar + status bar):\nObjective-C\nCGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +\n (self.navigationController.navigationBar.frame.size.height ?: 0.0));\n\nSwift 4\nlet topBarHeight = UIApplication.shared.statusBarFrame.size.height +\n (self.navigationController?.navigationBar.frame.height ?? 0.0)\n\nFor ease, try this UIViewController extension\nextension UIViewController {\n\n /**\n * Height of status bar + navigation bar (if navigation bar exist)\n */\n\n var topbarHeight: CGFloat {\n return UIApplication.shared.statusBarFrame.size.height +\n (self.navigationController?.navigationBar.frame.height ?? 0.0)\n }\n}\n\nSwift 3\nlet topBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height +\n(self.navigationController?.navigationBar.frame.height ?? 0.0)\n\n"} +{"text": "Q:\n\nHash function to iterate through a matrix\n\nGiven a NxN matrix and a (row,column) position, what is a method to select a different position in a random (or pseudo-random) order, trying to avoid collisions as much as possible?\nFor example: consider a 5x5 matrix and start from (1,2)\n0 0 0 0 0 \n0 0 X 0 0 \n0 0 0 0 0 \n0 0 0 0 0 \n0 0 0 0 0 \n\nI'm looking for a method like \n(x,y) hash (x,y);\n\nto jump to a different position in the matrix, avoiding collisions as much as possible\n(do not care how to return two different values, it doesn't matter, just think of an array).\nOf course, I can simply use \nrow = rand()%N;\ncolumn = rand()%N;\n\nbut it's not that good to avoid collisions.\nI thought I could apply twice a simple hash method for both row and column and use the results as new coordinates, but I'm not sure this is a good solution. \nAny ideas?\n\nA:\n\nCan you determine the order of the walk before you start iterating? If your matrices are large, this approach isn't space-efficient, but it is straightforward and collision-free. I would do something like:\n\nGenerate an array of all of the coordinates. Remove the starting position from the list.\nShuffle the list (there's sample code for a Fisher-Yates shuffle here)\nUse the shuffled list for your walk order.\n\n"} +{"text": "Q:\n\ndisable userinteraction for single tap on uitextview\n\nI've got a UITextView in a tableViewCell\nThe problem is that when I single tap on the textView it doesn't perform the didSelectRowAtIndexPath.\nBut I can't set userInteraction = NO because I want to be able to select the text on a long press event\nHow can I solve this?\n\nA:\n\nI don't think you can so that however if what you want is a way to copy content (text) of a cell how about using the UITableViewDelegate to use the official controls... (like in contacts app where you hold the cell)...\nYou can achieve it by implementing these methods:\n- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {\n\n if (indexPath.row == 1) { //eg, we want to copy or paste row 1 on each section\n return YES;\n }\n return NO; //for anything else return no\n}\n\n- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {\n\n if (action == @selector(copy:)) { //we want to be able to copy\n\n if... //check for the right indexPath\n return YES;\n\n }\n\n return NO; //return no for everything else\n\n}\n\n- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {\n\n if (action == @selector(copy:)) {\n\n //run the code to copy what you want here for indexPath\n\n }\n\n}\n\nJust wrote that from memory so @selector(copy:) might be @selector(copy) (no :) but try it out... You can also add addtional tasks like paste ect but I'll let you figure that out.\nGood luck\n\n"} +{"text": "Q:\n\nPath to publishing a technical book\n\nI'm 21 years old female from South India. I would like to publish a book which concentrates on any one latest computer technology. Now, I have completed my BE- Computer Science and Engineering. I'm going to work in an IT company for two years and after 4 years I would like to publish the book. What are the qualifications I need to publish a technical-oriented book? What is the procedure for that? Is it way too expensive? I don't have anyone for guidance. Kindly guide me.\n\nA:\n\nThere are three things you need to publish such a book:\n\nMastery of the subject matter.\nThe ability to write well, in an engaging, informative style and samples to prove that.\nA publisher.\n\nThe usual practice is to get an idea for a book that has not been covered to death, write a proposal, and submit it to various publishers along with samples of your writing on similar subjects. Blog writing on that or other topics will help, but be aware that the coverage should be thorough and detailed, not just a \"random thoughts\" kind of thing.\nIf you are a recognized expert in your field, so much the better. You may receive inquiries from publishers without solicitation. Absent that, you should be prepared for plenty of rejection.\n\n"} +{"text": "Q:\n\nSQL query to find rows with the same value in multiple columns\n\nI want to find rows in my table that have duplicate values accross columns in a the same row\nExample:\nid column_1 column_2 column_3\n1 123 44 100\n2 555 555 555\n3 101 396 100\n4 99 99 99\n5 123 44 100\n\nI need a query that returns rows 2 & 4. So far, I have only found questions with similar titles that refer to finding rows that have the same values in multiple columns that would for example return 1 & 5. That's not what I am looking for :)\n\nA:\n\nThis is your query:\nSELECT * FROM your_table WHERE column_1 = column_2 AND column_2 = column_3\n\n"} +{"text": "Q:\n\nStore a float as key in GhashTable\n\nHello I was wondering if it was possible to store a float as key into a GhashTable considering there is no GFLOAT_TO_POINTER macro methdod.\nI am following a tutorial I found online by IBM http://www.ibm.com/developerworks/linux/tutorials/l-glib/section5.html , but I can't seem to find a way to use an float as a key.\nAny help would be great thanks!\ntypedef struct Settings settings;\ntypedef struct Preset preset;\n\nstruct Gnomeradio_Settings\n{\n GList *presets;\n};\n\nstruct Preset\n{\n gchar *name;\n gfloat freq;\n};\n\nI want to put all freq from settings.presets list as key in a GHashTable\nGHashTable *hash;\nGList *node;\n\nhash = g_hash_table_new (g_double_hash, g_double_equal);\nfor (node = settings.presets; node; node = node->next) {\n preset *ps;\n gfloat *f;\n\n ps = (preset *) node->data;\n f = g_malloc0 (sizeof (gfloat));\n *f = ps->freq;\n g_hash_table_insert (hash, f, NULL);\n}\n\nvoid printf_key (gpointer key, gpointer value, gpointer user_data)\n{\n printf(\"\\t%s\\n\", (char *) key);\n}\n\nvoid printf_hash_table (GHashTable* hash_table)\n{\n g_hash_table_foreach (hash_table, printf_key, NULL);\n}\n\nprintf_hash_table (hash);\n\nbut without success!\nthis print:\n\ufffd\ufffd\ufffdB\nff\ufffdB\nff\ufffdB\n\ufffd\ufffd\ufffdB\nff\ufffdB\nf\ufffd\ufffdB\nf\ufffd\ufffdB\n\ufffd\ufffd\ufffdB\n33\ufffdB\nff\ufffdB\n\ufffdL\ufffdB\n\ufffd\ufffd\ufffdB\n\ufffd\u0332B\n\nA:\n\nYour code looks correct to me except for the routine that prints out key values. I think you meant this, which will output each gfloat value as a string:\nvoid printf_key (gpointer key, gpointer value, gpointer user_data)\n{\n printf(\"\\t%f\\n\", *(gfloat *) key);\n}\n\nTo avoid memory leaks, you should probably also be creating your hash table like this so the memory you allocate for each key is automatically released when the table is destroyed (or a duplicate key is inserted):\nhash = g_hash_table_new_full (g_double_hash, g_double_equal, g_free, NULL);\n\n"} +{"text": "Q:\n\nIntercepting PHP mail() with a Java class\n\nI have a LAMP setup. I'm trying to intercept the mail() command and call my own Java code instead of calling sendmail etc. I've altered the php.ini\nsendmail_path = /home/jlarkins/Desktop/CustomMail\n\nwhich is my Java class file. Problem is, whenever I try to test this via a PHP test emailer, nothing happens. Can someone help me out, point me to the proper log file for Java errors or correct the syntax I'm using? I don't care that it won't send the email, I don't want the email going out anyways. I just want to trap it and analyze via my own Java code.\n\nA:\n\nFirst, check your PHP/Apache error log file to see if anything can be found there.\nIs \"CustomMail\" a .class file? If yes, it is not an executable file, thus PHP cannot run it. You'll have to point your sendmail_path variable on an executable file which will load your Java program and forward its arguments.\nSomething like this should work:\n#!/bin/sh\n[ -r CustomMail.class ] && java CustomMail $@\n\n"} +{"text": "Q:\n\nHow to use the REST API to get array from the Opportunity Object in JSON format from the Opportunity object using SOQL?\n\nI'd just like to get an array of the opportunity data within Salesforce Visualforce so that I can manipulate it in Javascript.\nBelow is the query that I'd like to use to pull in the array: \nselect name,amount,closedate from Opportunity where stagename = 'Closed Won'\nIt seems like this should be pretty straightforward if I'm pulling this information in within Visualforce, so I wouldn't need to set up authorization.\n\nA:\n\nAdapting Marty's answer, since you want this in JSON:\nA controller method can return a string with a JSON representation of the data - you can then manipulate it in JavaScript however you want.\nOpportunitiesIndex.page\n\n

\n Closed Opportunities from JavaScript\n

\n
    \n
\n \n
\n\nOpportunitiesController.class\npublic class OpportunitiesController {\n public String getOpportunities() {\n return JSON.serialize([\n select name,amount,closedate\n from Opportunity\n where stagename = 'Closed Won'\n ]);\n }\n}\n\nReferences\n\nApex Properties shows you how to define properties that can be pulled into a Visualforce page.\nBuilding a Custom Controller shows another example of a custom controller used to provide data for a Visualforce page.\n\n"} +{"text": "Q:\n\nDisplay data in list into table\n\nI have one table in my web page, and I want to display my image in row1, and detail of image in row1. When the image is called, I add detail of the image in to list. There are 27 images with 9 rows of table. After the images are ready, I start to display the detail of it, those are stored in the list.\n<% \n if (Model.Item.Count() < 1) return;\n\n int iIntialColum = 3;//set number of column per table \n\n if (Model.Item.Count < 3)\n iIntialColum = Model.Item.Count(); \n\n int iNumCollum = iIntialColum; //further use \n\n int iNumRow = 0;\n int iLastRow = 0;\n\n iNumRow = (Model.Item.Count() / iNumCollum);//find number of row to interate\n iLastRow = (Model.Item.Count() % iNumCollum);//find last row if exist\n\n if(iLastRow > 0)\n iNumRow += 1;\n\n int iStartIndex = 0; \n%>\n\n
\n \n\n <% \n List list = new List();\n for(int j = 0; j < iNumRow; j++) { %>\n \n <% for(int i = iStartIndex; i < iNumCollum; i++) {\n string _linke = \"\";\n\n if(string.IsNullOrEmpty(Request.QueryString[\"ws\"])) {\n _linke = Url.Action(Model.ActionName, Model.ControllerName, \n new { \n id = Model.Item[i].ID, \n dep = Model.Item[i].DepartmentID, \n cat = Model.Item[i].CategoryID, \n tab = Model.Tab \n }\n ); \n }\n else {\n _linke = Url.Action(Model.ActionName, Model.ControllerName, \n new { \n id = Model.Item[i].ID, \n dep = Model.Item[i].DepartmentID, \n cat = Model.Item[i].CategoryID, \n tab = Model.Tab, \n ws = Request.QueryString[\"ws\"].ToString() \n }\n );\n } %>\n\n \n <% }\n\n iStartIndex = iNumCollum; \n iNumCollum += iIntialColum;\n\n if (iNumCollum > Model.Item.Count())//make sure that Index is not out of range { \n iNumCollum = Model.Item.Count() ; \n } %> \n \n\n <% \n int k = 0;\n foreach(var bb in list) {\n if (k % 3 == 0) { %>\n \n \n <% }\n else { %>\n \n <% }\n k++; \n }\n %>\n \n <% \n iStartIndex = iNumCollum; \n iNumCollum += iIntialColum;\n\n if (iNumCollum > Model.Item.Count()) { //make sure that Index is not out of range \n iNumCollum = Model.Item.Count() ; \n } \n %> \n \n\n <% if (j < iNumRow - 1) { }\n\n }\n
\n
\n <% if ((Model.Item[i].Brand.IsAuthorized == true) && ((HelperClass.ICEContact.PathBrandImages+ Model.Item[i].Brand.Image)!= null)) { %>\n
\n \" width = \"85px\"/>\n
\n <%}\n else {%>\n
\n          \n
\n <% } %>\n\n \n
\n \n\n <% list.Add(Model.Item[i]);%>\n \n
\n
\n <% Response.Write(bb.Name); %>\n \n <%Response.Write(bb.Name);%>\n

\n
\n\nA:\n\nIf you are going to do it this way, you can simplify your approach by using the asp:repeater control: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx\nTake a look at this example:\nhttp://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater(v=vs.71).aspx\nYou can then avoid the looping and structure your table in the ASPX, which will make maintenance a lot easier.\nFor example:\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n\n \n
CompanySymbol
\n \n\n
\n\nIn the code behind, handle the Repeater1_ItemDataBoundEvent, and you can do things like check to see if you have an object you expect, and look for the controls in the ItemTemplate,\nSee http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx\nYou can find the image control by doing:\nvar image = e.Item.FindControl(\"MyImage\") \n\nAnd set the src appropriately.\nLots of options, and you have a cleaner separation of presentation and code.\n\n"} +{"text": "Q:\n\nThe constructor BaseEncoding() is not visible when extending Guava libraries\n\nThere are different questions already available related to this error, but none is realted to this specific class i.e BaseEncoding\nWhen i am extending BaseEncoding on my class, I am getting this error,\n\nThe constructor BaseEncoding() is not visible\n\nhere is the code,\nimport com.google.common.io.BaseEncoding;\n\npublic class TheRace extends BaseEncoding{\n\n public TheRace() {\n super();\n }\n}\n\nfrom this answer, Constructor not visible \nI understand that BaseEncoding() constructor must be expecting some parameters, but when I visit its official documentation, there is no constructor defined.\nHow can I pass the parameters to solve my issue when there is no parametrized constructor in the BaseEncoding class ?\n\nA:\n\nBaseEncoding isn't meant to be subclassed; its constructor is deliberately made private and not visible outside the class. You're supposed to acquire instances of it using its factory methods like base16().\n\n"} +{"text": "Q:\n\nCan there be a power series that converges for all reals but not for the complex numbers?\n\nLet $z = x + i y$, and consider the following function:\n$$\nf(z) = e^{\\frac{1}{1 + z^2}} \\qquad z \\in \\mathbb{C}\n$$\nNote that at $z = \\pm i$ the function does not converge.\nWe see that on $\\mathbb{R}$ when $y = 0$, this becomes:\n$$\nf(x) = e^{\\frac{1}{1 + x^2}} \\qquad x \\in \\mathbb{R},\n$$\nwhich converges nicely for all values $x \\in \\mathbb{R}$.\nFurthermore, this function is analytic on $\\mathbb{R}$, and so there exists some power series of form:\n$$\nf(x) = \\sum_{n = 0}^{\\infty} a_n (x - x_0)^n \\qquad a_n, x, x_0 \\in \\mathbb{R}\n$$\nthat converges for all $x \\in \\mathbb{R}$.\nDoes this power series naturally extend to the complex plane if we have $x \\mapsto z$, i.e.:\n$$\nf(z) = \\sum_{n = 0}^{\\infty} b_n (z - z_0)^n \\qquad z \\in \\mathbb{C}, \\quad z_0 = x_0 + i0, \\quad b_n = a_n + i 0\n$$\nIn this case, would the function shown above thus demonstrate that a complex-valued power series that converges on all of $\\mathbb{R}$ not necessarily converge in $\\mathbb{C}$?\n\nA:\n\nNo. If a power series converges on all $\\mathbb{R}$, it(s extension) converges for all complex numbers. One quick way to see why this holds is considering the formula for the radius of convergence and recalling that one proves absolute convergence with it, thus holding for $\\mathbb{C}$ as well.\n\nA:\n\nNo. You might have heard the term \"radius of convergence\" before - in this case, that isn't an abuse of language. Power series converge within open disks in the complex plane, and the radius of convergence is the distance to the nearest singularity. In this case, since you require your series to converge on $\\mathbb{R}$, the radius of convergence would have to be $\\infty$, so that the series would converge on all of $\\mathbb{C}$\n\nA:\n\nThe fundamental flaw in your analysis is this (but see @AloizioMacedo's comment):\n\nWe see that on $\\mathbb{R}$ when $y = 0$, this becomes:\n$$ f(x) = e^{\\frac{1}{1 + x^2}} \\qquad x \\in \\mathbb{R}, $$\nwhich converges nicely for all values $x \\in \\mathbb{R}$.\n\nThe problem is that the function you've written can't \"converge\" because it's not a series. \nThere is a power-series for $e^x$, and there's one for $\\frac{1}{1+x^2}$. But that latter series only converges for $x^2 < 1$, so there isn't an everywhere convergent power series for that function on the reals (or at least \"the obvious one isn't everywhere convergent\").\n\n"} +{"text": "Q:\n\njs regex result expression assignment issue\n\nI have a js string, for example:\n\"h\" + \"e\" + \"l\" + \"l\" + \"o\" \n\nwhich is being derived from a regex query. The string appears between [..] therefore I'm using the following to derive it:\nvar txt = '\"blahblahblah[\"h\"+\"e\"+\"l\"+\"l\"+\"o\"]foobarfoobarr\"';\nvar re = /[^\\[\\]]+(?=\\])/g;\nvar squareParen = re.exec(txt); // squareParen[0] contains ' \"h\" + \"e\".. etc'\n\n// i assumed by assigning the string to a var \n// it would show me the product of its output\nvar result = squareParen[0];\nconsole.log (result);\n\nnow, following my question here, if I hard code my string (as a test) and assign it, when I output to console it reads 'hello' as expected. However, when I use the output of the regex query assigned to a variable, it's outputting the result as is, i.e. \"h\"+\"e\"+\"l\"+\"l\"+\"o\" and not \"hello\".\nI'm confused as to why.\n\nA:\n\nThe value you're storing in result is actually a string that looks like:\n'\"h\"+\"e\"+\"l\"+\"l\"+\"o\"'\n\nWhich is distinct from the expression \"h\"+\"e\"+\"l\"+\"l\"+\"o\"; that expression is a series of string concatenations which evaluates to the string \"hello\".\nBe cautious about using the output from console.log as a definitive guide; it renders the given values in a way that aesthetically valuable, but not always precise.\nI'm curious what you're actually trying to do.\n\n"} +{"text": "Q:\n\nList only common parent directories for files\n\nI am searching for one file, say \"file1.txt\", and output of find command is like below.\n/home/nicool/Desktop/file1.txt\n/home/nicool/Desktop/dir1/file1.txt\n/home/nicool/Desktop/dir1/dir2/file1.txt\n\nIn above cases I want only common parent directory, which is \"/home/nicool/Desktop\" in above case. How it can be achieved using bash? Please help to find general solution for such problem.\n\nA:\n\nThis script reads lines and stores the common prefix in each iteration:\n# read a line into the variable \"prefix\", split at slashes\nIFS=/ read -a prefix\n\n# while there are more lines, one after another read them into \"next\",\n# also split at slashes\nwhile IFS=/ read -a next; do\n new_prefix=()\n\n # for all indexes in prefix\n for ((i=0; i < \"${#prefix[@]}\"; ++i)); do\n # if the word in the new line matches the old one\n if [[ \"${prefix[i]}\" == \"${next[i]}\" ]]; then\n # then append to the new prefix\n new_prefix+=(\"${prefix[i]}\")\n else\n # otherwise break out of the loop\n break\n fi\n done\n\n prefix=(\"${new_prefix[@]}\")\ndone\n\n# join an array\nfunction join {\n # copied from: http://stackoverflow.com/a/17841619/416224\n local IFS=\"$1\"\n shift\n echo \"$*\"\n}\n\n# join the common prefix array using slashes\njoin / \"${prefix[@]}\"\n\nExample:\n$ ./x.sh < values = new ArrayList();\n for (Object value : (Collection) propertyValue) {\n values.add(createValue(value, factory));\n }\n node.setProperty(propertyName, values.toArray(new Value[values.size()]));\n } else {\n throw new IllegalArgumentException(\"Something wrong\");\n }\n}\n\n@Test\npublic void test() {\n Node node = createNode(\"test\");\n setProperty(node, \"name\", \"name\");\n}\n\nA:\n\nMy idea would be to encapsulate the job of casting and converting into some kind of a Strategy pattern.\nI would use an enum for that, namely NodeSettingStrategy:\npublic static enum NodeSettingValueStrategy {\n UNKNOWN(null) {\n @Override\n public void set(Node node, String propertyName, Object value) {\n throw new IllegalArgumentException(\"Cannot set property to a value of type \" + value.getClass());\n }\n },\n\n DATE(Date.class) {\n @Override\n public void set(Node node, String propertyName, Object value) {\n node.setProperty(propertyName, (Long) value);\n }\n\n },\n\n LONG_PRIMITIVE(long.class) {\n @Override\n public void set(Node node, String propertyName, Object value) {\n node.setProperty(propertyName, (long) value);\n }\n },\n\n LONG(Long.class) {\n @Override\n public void set(Node node, String propertyName, Object value) {\n node.setProperty(propertyName, (Long) value);\n }\n },\n\n STRING(String.class) {\n @Override\n public void set(Node node, String propertyName, Object value) {\n node.setProperty(propertyName, (String) value);\n }\n },\n\n NODE(Node.class) {\n @Override\n public void set(Node node, String propertyName, Object value) {\n node.setProperty(propertyName, (Node) value);\n }\n };\n\n private final Class supportedType;\n\n private NodeSettingValueStrategy(Class supportedType) {\n this.supportedType = supportedType;\n }\n\n public static NodeSettingValueStrategy of(Class type) {\n for (NodeSettingValueStrategy strategy : NodeSettingValueStrategy.values()) {\n if (strategy.supportedType == type) {\n return strategy;\n }\n\n }\n return NodeSettingValueStrategy.UNKNOWN;\n }\n\n public abstract void set(Node node, String propertyName, Object value);\n}\n\nThen I want to hide this NodeSettingStrategy by a thin abstraction, namely NodeSetter:\npublic static class NodeValueSetter {\n private final NodeSettingValueStrategy strategy;\n private final String propertyName;\n private final Object value;\n\n private NodeValueSetter(NodeSettingValueStrategy strategy, String propertyName, Object value) {\n this.strategy = strategy;\n this.propertyName = propertyName;\n this.value = value;\n }\n\n public void setTo(Node node) {\n strategy.set(node, propertyName, value);\n }\n\n public static NodeValueSetter of(final String propertyName, final Object value) {\n NodeSettingValueStrategy settingStrategy = NodeSettingValueStrategy.of(value.getClass());\n return new NodeValueSetter(settingStrategy, propertyName, value);\n }\n\n}\n\nCombine them together:\n@Test\npublic void should_able_to_set_property() throws Exception {\n Node node = new Node();\n\n Node givenNode = new Node();\n String someString = \"The brown fox jumps over a lazy dog\";\n long givenLong = 234234234234L;\n\n for (NodeValueSetter setter : Arrays.asList(\n NodeValueSetter.of(\"a-string\", someString),\n NodeValueSetter.of(\"a-number\", givenLong),\n NodeValueSetter.of(\"a-node\", givenNode))) {\n setter.setTo(node);\n }\n\n assertThat(node.getProperty(\"a-string\"), is(someString));\n assertThat(node.getProperty(\"a-number\"), is(givenLong));\n assertThat(node.getProperty(\"a-node\"), is(givenNode));\n }\n\n"} +{"text": "Q:\n\nAutomatically hide LinqPad query\n\nI wrote a simple tool to decode JWT tokens and I'd like to use it in a similar way as the Interactive Regex Evaluator.\nIs there a way to either automatically hide a query (e.g., via the Util class) or to even register it to something like Ctrl+Shift+F2?\n\nA:\n\nUnfortunately that functionality doesn't exist.\nYou'll notice when using the Interactive Regex Evaluator it's opening the sample of the same name but doing extra work to hide the query panel. Looking at LinqPads code using it's own ILSpy, there's a method called LINQPad.UI.MainForm.miRegex_Click and it's calling the method LINQPad.UI.QueryControl.ToggleFullPaneResults which does that functionality but unfortunately the method is internal.\nIf you'd like to suggest the feature head over to the LinqPad forums over at http://forum.linqpad.net/ and make the suggestion. Joseph is good at getting back to people.\n\n"} +{"text": "Q:\n\nProve that function is not uniformly convergent\n\nI am in a trouble of showing that the sequence of function \n$$f_n(x) = \\frac{e^{-nx}}{3n^2x^2+1}, \\ \\ n = 1, 2, \\cdots$$ \ndoes not converge uniformly on $[0,\\infty)$.\nI tried to show that $f_n(x)$ does not point wise converge with $f(x)$ or $\\sup|f_n(x)-f(x)|$ is not equal to zero as $n$ goes to infinity. But I couldn't end up with a satisfied answer. \nPlease help.\n\nA:\n\nThe given sequence is point-wise convergent to the function $f$ defined by $f(x)=0$ for $x>0$ and $f(0)=1$ and since $f$ isn't continuous at $0$ while the functions $f_n$ are continuous then the convergence isn't uniform on $[0,+\\infty)$.\n\n"} +{"text": "Q:\n\nSyntaxError: Unterminated parenthetical, how to handle \"( )\"\n\nI am trying to clean up a string (anything that contains unwanted characters, diacritics, etc.) entered by a user and replace with just one string with no spaces. \nI came across this error: \n\nExecution failed: SyntaxError: Unterminated parenthetical. \n\nIt stopped at this line: idoff = accented.search(a2.charAt(i));\nI was able to update our old legacy code when we encountered several accented letters (diacritics). I saw a code that I could use to resolve it but somehow I cannot figure out to how fix this one. \nfunction clean(a2) {\n\n/* if string contains accented letters, index below and use regular text */\n\nvar accented = '\u00c1\u00c0\u00c2\u00c3\u00c4\u00c4\u00c5\u00c6\u00e1\u00e0\u00e2\u00e3\u00e4\u00e5\u0105\u00c7\u00e7\u0107\u010d\u00d0\u00c9\u00c9\u00ca\u00cb\u00e8\u00e9\u00ea\u00eb\u00f0\u0119\u00cd\u00cd\u00ce\u00cf\u00ed\u00ee\u00ef\u0142\u00d1\u00f1\u0144\u00d6\u00d3\u0150\u00d3\u00d4\u00d5\u00d8\u00f6\u00f3\u0151\u00f4\u00f5\u00f8\u00dc\u0170\u00d9\u00da\u00db\u00dc\u00fc\u0171\u00fa\u00fb\u0160\u0161\u0178\u00ff\u00fd\u017d\u017e\u017b\u017c\u0141';\nvar regularText = 'AAAAAAAAaaaaaaaaCcccDEEEEeeeeeeIIIIiiilNnnOOOOOOOooooooUUUUUUuuuuSSYyyZzZzL';\nvar idoff = -1,new_text = '';\nvar lentext = a2.toString().length -1\n\nfor (i = 0; i <= lentext; i++) {\n idoff = accented.search(a2.charAt(i));\n if (idoff == -1) {\n new_text = new_text + a2.charAt(i);\n } else {\n new_text = new_text + regularText.charAt(idoff);\n }\n}\n// return new_text; \n\n/* Locate where in the string that contains \":\", remove it including spaces and change string to lowercase */\n\nvar space = new_text.indexOf(\":\");\n if (space > -1) {\n var answer = new_text.substring(space);\n answer = answer.replace(/[\\.,-\\/#!$%\\^&\\*;:{}=\\-_`~()\"'+@<>?]/g,\"\")\n answer = answer.replace(/ /g,\"\");\n answer = answer.toLowerCase();\n } else {\n var answer = new_text;\n answer = answer.replace(/[\\.,-\\/#!$%\\^&\\*;:{}=\\-_`~()\"'+@<>?]/g,\"\")\n answer = answer.replace(/ /g,\"\");\n answer = answer.toLowerCase();\n }\n return answer;\n }\n\nIf string is like this ABC-XYZ-LMN (AB12): XxxX Set \u00c7ompan\u00ff I want to clean it up to this xxxxsetcompany.\n\nA:\n\nString.prototype.search expects a regular expression, but you're passing in a character (string). As you iterate over a2 you eventually come across an open parenthesis (the one surrounding \"AB12\"). An open parenthesis is not a valid regex.\nTo fix this you could use String.prototype.includes instead.\nHowever, I think a more elegant solution to your issue may look something like this:\n\nfunction clean(a2) {\n /* if string contains accented letters, index below and use regular text */\n const accented = '\u00c1\u00c0\u00c2\u00c3\u00c4\u00c4\u00c5\u00c6\u00e1\u00e0\u00e2\u00e3\u00e4\u00e5\u0105\u00c7\u00e7\u0107\u010d\u00d0\u00c9\u00c9\u00ca\u00cb\u00e8\u00e9\u00ea\u00eb\u00f0\u0119\u00cd\u00cd\u00ce\u00cf\u00ed\u00ee\u00ef\u0142\u00d1\u00f1\u0144\u00d6\u00d3\u0150\u00d3\u00d4\u00d5\u00d8\u00f6\u00f3\u0151\u00f4\u00f5\u00f8\u00dc\u0170\u00d9\u00da\u00db\u00dc\u00fc\u0171\u00fa\u00fb\u0160\u0161\u0178\u00ff\u00fd\u017d\u017e\u017b\u017c\u0141';\n const regularText = 'AAAAAAAAaaaaaaaCcccDEEEEeeeeeeIIIIiiilNnnOOOOOOOooooooUUUUUUuuuuSSYyyZzZzL'.split('');\n\n let answer = '';\n\n a2.split('').forEach((char) => {\n let accentIndex = accented.indexOf(char);\n\n if (accentIndex > -1) {\n answer += regularText[accentIndex];\n } else {\n answer += char;\n }\n });\n\n answer = answer.replace(/\\W/gi, '');\n\n return answer.toLowerCase();\n}\n\nconsole.log(clean('ABC-XYZ-LMN (AB12): XxxX Set \u00c7ompan\u00ff'));\n\n"} +{"text": "Q:\n\nUse and meaning of \"to VERB\" clause\n\nI am often confused about the construction of clauses with to.\n\nI saw that there was not much water left in the bottle, so I picked it up went to the kitchen refilled it.\n\nIs this a possible contraction of the previous sentence? Is it acceptable?\n\nI picked up the bottle to refill it.\n\nSimilarly, is the following sentence acceptable?\n\nI saw the show to talk about it next morning at work.\n\nA:\n\nYour first sentence requires at least one comma and an and:\n\nI picked it up, went to the kitchen and refilled it.\n\n\"So* looks back to the previous clause to supply a reason\u2014because the bottle was almost empty\u2014for doing all three things which follow, but does not explicitly state that you picked it up in order to refill it.\nConsequently, it cannot be regarded as a \u2018contraction\u2019 (I think what you mean here is an ellipsis): it is a restatement, which asserts a purpose leaves out its realization in the two following actions: taking the bottle to the kitchen and actually refilling it. The sequence might have been interrupted before you completed it. \nLikewise, the second sentence, I saw the show to talk about it next morning at work, asserts only your viewing and your purpose; it does not assert that you did in fact talk about the show the next morning.\n\nA:\n\nI saw that there was not much water left in the bottle, so I picked it up went to the kitchen refilled it.\n\nThere is a problem with this sentence: you need to add commas.\n\nI saw that there was not much water left in the bottle, so I picked it up, [I] went to the kitchen, [and] [I] refilled it.\n\nIn very casual, informal writing you might leave out and, but it is normally compulsory. Leaving out I in the second and third clauses is perfectly normal and not informal at all. There is nothing unusual about to: it just introduces the direction of went, an adverbial phrase of direction.\n\nI picked up the bottle [in order] to refill it.\n\nThis is perfectly normal. You don't need in order: it means exactly the same thing. In a simple, clear sentence like this, using to to introduce a purpose with to + infinitive is standard. It has nothing directly to do with to as in the first sentence, where it introduces a direction.\n\nI saw the show to talk about it next morning at work.\n\nThis sentence is of the same type as the previous one: the reason/purpose why you saw the show is that you could talk about it the next morning. The situation is a bit unusual (is that really the main reason why you saw the show? Isn't that a bit silly?), but the grammar is fine.\n\n"} +{"text": "Q:\n\nSelenium create multiple chrome threads for each item in array(list) and execute function simultaneously\n\nI'm trying to create multiple chrome threads for each item in the list and execute the function for each item from list simultaneously, but having no idea where to even start any help will be much appreciated.\nCode Snippet\nimport sys\n\ndef spotify(elem1, elem2, elem3):\n\n print(\"proxy: {}, cc: {}, cvc: {}\".format(elem1, elem2, elem3))\n\ndef get_cc():\n cc = ['5136154545452522', '51365445452823', '51361265424522']\n return cc\n\ndef get_cvc():\n cvc = ['734', '690', '734']\n return cvc\n\ndef get_proxies():\n proxies = ['51.77.545.171:8080', '51.77.254.171:8080', '51.77.258.82:8080']\n return proxies\n\nproxArr = get_proxies()\nccArr = get_cc()\ncvcArr = get_cvc()\nyeslist = ['y','yes']\n\nfor elem in zip(proxArr, ccArr, cvcArr):\n spotify(elem[0], elem[1], elem[2])\n restart=input(\"Do you wish to start again: \").lower()\n if restart not in yeslist:\n sys.exit(\"Exiting\")\n\nA:\n\nSimilar to the answer here, you can start multiple threads of Chrome.\n\nDefine a function which executes your Selenium code, execute_chrome in this case\nAdd all required arguments to the function definition\nPass the arguments as a tuple in your Thread call, e.g. args=(elem, )\nSave the script with a name which is not identical to another Python package, e.g. my_selenium_tests.py\nrun the script preferably from the command line and not from an interactive environment (e.g. a Jupyter notebook)\nfrom selenium import webdriver\nimport threading\nimport random\nimport time\n\nnumber_of_threads = 4\n\ndef execute_chrome(url):\n chrome = webdriver.Chrome()\n chrome.get(url)\n time.sleep(1 + random.random() * 5)\n driver.quit()\n\nurls = ('https://www.google.com', \n 'https://www.bing.com', \n 'https://www.duckduckgo.com', \n 'https://www.yahoo.com')\n\nthreads = []\nfor i in range(number_of_threads):\n t = threading.Thread(target=execute_chrome, args=(urls[i], ))\n t.start()\n threads.append(t)\n\nfor thread in threads:\n thread.join()\n\n"} +{"text": "Q:\n\nHow to randomly place div inside parent with JavaScript?\n\nI have a parent div (fieldbox) and a child div (potbox). \nInside the parent I want to place the child div with a random position on every page refresh.\nFor some reason, my solution does not work. I think the style is not defined. But I don't see why...\n\nconst potboxRandom = document.querySelector('potbox')\n\nconst fieldWidth = 600;\nconst fieldHeight = 500;\n\nrandomTop = getRandomNumber(0, fieldWidth);\nrandomLeft = getRandomNumber(0, fieldHeight);\n\npotboxRandom.style.top = `${randomTop}px`\npotboxRandom.style.left = `${randomLeft}px`\n\nfunction getRandomNumber(min, max) {\n return Math.random() * (max - min) + min;\n}\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n}\n\n.fieldbox {\n height: 500px;\n width: 600px;\n position: relative;\n background: lightskyblue;\n}\n\n.potbox {\n height: 20px;\n width: 20px;\n position: absolute;\n top: 100px;\n left: 100px;\n background: hotpink;\n}\n
\n
\n
\n\nA:\n\nThere's just a selector problem in querySelector, use .potbox instead of potbox\n\nconst potboxRandom = document.querySelector('.potbox')\n\nconst fieldWidth = 600;\nconst fieldHeight = 500;\n\nrandomTop = getRandomNumber(0, fieldHeight - potboxRandom.clientHeight);\nrandomLeft = getRandomNumber(0, fieldWidth - potboxRandom.clientWidth);\n\npotboxRandom.style.top = `${randomTop}px`\npotboxRandom.style.left = `${randomLeft}px`\n\nfunction getRandomNumber(min, max) {\n return Math.random() * (max - min) + min;\n}\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n}\n\n.fieldbox {\n height: 500px;\n width: 600px;\n position: relative;\n background: lightskyblue;\n}\n\n.potbox {\n height: 20px;\n width: 20px;\n position: absolute;\n top: 100px;\n left: 100px;\n background: hotpink;\n}\n
\n
\n
\n\n"} +{"text": "Q:\n\nHow does ammonium nitrate explode on its own?\n\nI thought ammonium nitrate was an oxidizer that needed to be mixed with fuel to form a high explosive (e.g., ANFO). But apparently there have been accidental explosions involving just the \"fertilizer\". Are these explosions also detonations? What is the chemical formula for the process?\n$$\\ce{NH4NO3 -> ???}$$\nPart of my motive for asking is the news today (Aug 4, 2020) of an explosion in Beirut. Initial reports say it was caused by \"2750 tons of stored ammonium nitrate\".\n\nA:\n\nIt is known that ammonium nitrate decompose exothermically when heated to form nitrous oxide and water. This paper1 notes that the irreversible decomposition of ammonium nitrate occurs at the temperature range of $\\pu{230-260 ^\\circ C}$.\n$$\\ce{NH4NO3 ->[t >230 ^\\circ C] N2O + 2H2O}$$\nThey also further noted that beyond $\\pu{280 ^\\circ C}$, $\\ce{NH4NO3}$ is capable of rapid, self-accelerating decomposition (to the point of detonation).\nBut at the detonation temperature, $\\mathrm{t_d}$ (the temperature at which compounds detonate), ammonium nitrate fully decomposes to nitrogen, oxygen and water releasing a tremendous amount of energy.\n$$\\ce{2NH4NO3 ->[t_d] 2N2 + O2 + 4H2O}$$\nIn the context of Beirut explosion, the question that raised was \"when did ammonium nitrate reached detonation temperature, and why did it suddenly explode?\". According to a news report from cnet.com:\n\nWhen heated to above 170 degrees Fahrenheit, ammonium nitrate begins\nto undergo decomposition. But with rapid heating or detonation, a\nchemical reaction can occur that converts ammonium nitrate to nitrogen\nand oxygen gas and water vapor. The products of the reaction are\nharmless -- they're found in our atmosphere -- but the process\nreleases huge amounts of energy.[...]\nAdditionally, in the explosion, not all of the ammonium nitrate is\nused up and exploded. Some of it decomposes slowly creating toxic\ngases like nitrogen oxides. It's these gases that are responsible for\nthe red-brown plume of smoke seen in the aftermath of the Beirut\nexplosion, Rae said.\n\nSo, my theory is that ammonium nitrate started heating (from the fire) releasing all sorts of nitrogen oxides (the red fumes). This fire further accelerated the reaction, further heating the remaining ammonium nitrate to the point of detonation and that's when ammonium nitrate exploded instantaneously releasing tremendous amount of energy which send shockwaves around the site along with a white mushroom shaped cloud (from @DDuck's comment) which could probably be nitrogen and/or water vapours where the humid air (water vapor laden air) condensed due to the explosion(@StianYttervik) with release of nitrogen. It is a sad and quite devastating incident.\nReferences\n\nOn the Thermal Decomposition of Ammonium Nitrate. Steady-state Reaction\nTemperatures and Reaction Rate By George Feick and R. M. Hainer, 1954 (PDF)\nReaction Rates of Ammonium Nitrate in Detonation\nMelvin A. Cook, Earle B. Mayfield, and William S. Partridge\nThe Journal of Physical Chemistry 1955 59 (8), 675-680\nDOI: 10.1021/j150530a002 (PDF)\nhttps://en.wikipedia.org/wiki/2020_Beirut_explosions\n\nA:\n\nAmmonium nitrate ($\\ce{NH4NO3}$) is widely used in the fertilizer industry and is one of the most concentrated forms of nitrogen fertilizer (35% of $\\ce{N}$). At the same time, it has also been widely used as an explosive material for detonation in mines. Because of its explosiveness, $\\ce{NH4NO3}$ is associated with various hazards including fire and explosion, which have occurred repeatedly in the past (more than 70 incidents during 20th century, more than half of them occurred in the US soil). Regardless, $\\ce{NH4NO3}$ is not considered a flammable or combustible material at ambient temperature and pressure (Ref.1). However, it is a strong oxidizing agent that can detonate under certain conditions such as temperature, fire, confinement, and presence of impurities (e.g., $\\ce{KCl}$), which can be act as a promoter to detonate (Ref.2).\nTo use as an explosive or a blasting reagent, $\\ce{NH4NO3}$ is mixed with fuel oil, which is called ammonium nitrate fuel-oil (ANFO; Ref.1). According to Ref.2, during the explosion, following exothermic reaction would take place (hydrocarbon is represented by $\\ce{CH2}$):\n$$\\ce{3NH4NO3 + CH2 -> 3N2 + 7 H2O + CO2} \\quad \\Delta H = \\pu{-4017 kJ/kg} \\tag1$$\nInterestingly, this can be compared with TNT, the heat of combustion of which is $\\Delta H = \\pu{-4196 kJ/kg}$. Without fuel oil, can be detonated under certain conditions. It is believed that the vaporization of molten $\\ce{NH4NO3}$ leads to the formation of ammonia and nitric acid, which could initiate the decomposition of $\\ce{NH4NO3}$ through following reaction:\n$$\\ce{NH4NO3 <=> HNO3 + NH3} \\quad \\Delta H = \\pu{176 kJ/mol} \\tag2$$\nAt higher temperatures (i.e., between $\\pu{170 ^\\circ C}$ and $\\pu{280 ^\\circ C}$) exothermic irreversible reactions (equations $(3)-(5)$) occur:\n$$\\ce{NH4NO3 -> N2O + 2H2O } \\quad \\Delta H = \\pu{-59 kJ/mol} \\tag3$$\n$$\\ce{NH4NO3 -> 1/2N2 + NO + 2H2O } \\quad \\Delta H = \\pu{-2597 kJ/mol} \\tag4$$\n$$\\ce{NH4NO3 -> 3/4N2 + 1/2NO2 + 2H2O } \\quad \\Delta H = \\pu{-944 kJ/mol} \\tag5$$\nIf the material is suddenly heated up, there will be explosive decompositions as shown in equations $(6)$ and $(7)$):\n$$\\ce{2NH4NO3 -> 2N2 + O2 + 4H2O } \\quad \\Delta H = \\pu{-1057 kJ/mol} \\tag6$$\n$$\\ce{8NH4NO3 -> 5N2 + 4NO + 2NO2 + 16H2O } \\quad \\Delta H = \\pu{-600 kJ/mol} \\tag7$$\nKeep in mind that all of these reactions except for $(2)$ are exothermic. Also, most products are gases. I attached PDF file if Ref.2 if a reader is interested in how explosions happen during right conditions (otherwise, it is a broad field to explain). For instance, the reaction $(3)$ can be made more exothermic ($\\pu{789 kJ/mol}$) with more gaseous products, if some oxidisable fuel is added such as $\\ce{C}$ (Ref.3):\n$$\\ce{2NH4NO3 (s) + C (s) -> 2N2 (g) + CO2 (g) + 4H2O (g)} \\tag8$$\nIt is evident from the past incidents involving $\\ce{NH4NO3}$ that the presence of impurities and environmental conditions have a huge effect on the detonation of $\\ce{NH4NO3}$ during storage. For example, one of the deadliest industrial incidents in US history occurred on April 16, 1947, in Texas City, Texas where an $\\ce{NH4NO3}$ explosion involving $\\pu{2300 tons}$ of $\\ce{NH4NO3}$ caused 581 fatalities and thousands of injuries. The fire was caused by the initial explosion of $\\ce{NH4NO3}$ on a ship, which resulted in subsequent chain reactions of fires and explosions in other ships and facilities nearby. The exploded $\\ce{NH4NO3}$ was coated with (carbon based) wax to prevent caking (See equation $(8)$ above). After this accident, the new technologies and safe practices introduced in the 1950s eliminated the use of wax coatings (Ref.2).\nReferences:\n\nGuy Marlair, Marie-Astrid Kordek, \"Safety and security issues relating to low capacity storage of AN-based fertilizers,\" Journal of Hazardous Materials 2005, 123(1\u20133), 13-28 (https://doi.org/10.1016/j.jhazmat.2005.03.028).\nZhe Han, \"Thermal Stability Studies of Ammonium Nitrate,\" Ph.D. Dissertation, Texas A&M University, TX, 2016 (PDF).\nAlex M. Djerdjev, Pramith Priyananda, Jeff Gore, James K. Beattie, Chiara Neto, Brian S. Hawkett, \"The mechanism of the spontaneous detonation of ammonium nitrate in reactive grounds,\" Journal of Environmental Chemical Engineering 2018, 6(1), 281-288 (https://doi.org/10.1016/j.jece.2017.12.003).\n\nA:\n\nFirst,\nammonium nitrate is a kind of mixture between an oxidizer - the nitrate part - and a reducer - the ammonium one. This is at the core of your question.\nThe direct decomposition correctly mentioned in the answers is nevertheless a process in which something gets oxidised and something gets reduced.\nIn ammonium nitrate basically you have all you need - the \"fuel\u201c and the \u201coxygen\u201c analogues of what is involved in a standard, explosive or not, combustion.\nStill the other answers are valid and more detailed from a chemical mechanicist viewpoint. One point out the presence of NO2 clearly seen by its red brownish colour before the second powerful explosion.\nBut the straight answer to your question is that the oxidizer and the reducing stuffs are already within the salt.\n\nSide note: ammonium nitrate can decompose by mechanical shock, so there were enough conditions to trigger the second powerful blast.\n\n"} +{"text": "Q:\n\nHow to refer a job candidate when you're planning to leave for a new job soon\n\nI've been offered and accepted a new job, which I'm excited about. The offer is conditional on a background check, so I'm waiting to give my two weeks notice and should be doing that next week.\nRecently, a friend has been looking for a new job and I was able to convince them to apply for a position on my project. Personally, I think he would be a decent replacement for myself.\nWill it come across as dishonest if I submit them as a referral and then resign a few days later? Will my impending resignation reflect poorly on my friend? Is there any reason for me to suggest them as a candidate after I give notice?\nI tried to find a referral tag, but couldn't.\n\nA:\n\nThe fact that you have made other plans theoretically shouldn't interfere with the recommendation. People are people and someone may be grumpy about it, but the recommendation is still more likely to help your friend than tonhurt him or her.\n\n"} +{"text": "Q:\n\nHow to list all row of sql?\n\nHy!\nI want to list all row of my table, but it is not works :( \nMy function.php:\nfunction getCharacterAdminJails($account_id) {\n global $connection;\n $stmt = $connection->pdo->prepare(\"SELECT * FROM adminjails WHERE jailed_accountID = :account_id\");\n $stmt->bindParam(\":account_id\", $account_id);\n $stmt->execute();\n $adminjail_data = $stmt->fetch(PDO::FETCH_ASSOC);\n return $adminjail_data;\n}\n\nMy example.php, where I list my rows:\n \n \n \n \n \n \n \n \n \n \n \n \n\n \n
Admin neve:Indok:Perc:Id\u0151pont:
\n\nHow can I list all rows of my table?\n\nA:\n\nI would suggest you change this line of code in your php function from\n$adminjail_data = $stmt->fetch(PDO::FETCH_ASSOC);\n\nTo this:\n$adminjail_data = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\nAs fatchAll will return an array of all the results from your query and then in your html page do this:\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Admin neve:Indok:Perc:Id\u0151pont:
\n\nThis is from PHP.net documentation about fetchAll:\nPDOStatement::fetchAll \u2014 Returns an array containing all of the result set rows\n\nYou can refer to the full php documentation about PDOs fetchAll here: https://secure.php.net/manual/en/pdostatement.fetchall.php\n\n"} +{"text": "Q:\n\ngetting the C python exec argument string or accessing the evaluation stack\n\nIn my python debugger I have a way of remapping a string to a filename so that when you are stepping through an exec'd function inside the debugger you can list lines pygmentized, or view them along inside an editor like Emacs via realgud.\nSo I'd like to be able to extract the string in an exec statement when CPython is stopped inside evaluating that. \nI already have a mechanism that can look back in the call frame to see if the caller was an EXEC_STMT and I can look back one instruction to see if the previous instruction was say DUP_TOP. So I'd be home free if I could just figure out a way to read the stack entry at the time of the call and that gives the string evaluated. There is probably a way to drop into C to get this, but my knowledge of CPython internals lacking, and would prefer not to do this. If there's a package out there, maybe I could include that optionally. \nCPython already provides access to function arguments, and local variables but of course since this is a built-in function this isn't recorded as a function parameter. \nIf there are other thoughts at how to do the same thing, that'd be okay too. I feel a less good solution would be to somehow try to overload or replace exec since debuggers can be brought in late in the game. \nI understand that CPython2 and CPython3 may be a little bit different here, but to start off either would do. \n\nA:\n\nI think I've now found a way. \nInside the debugger I go up the call stack one level to get to the exec statement. Then I can use uncompyle6 to get a syntax tree of the source code. (A change may be needed in uncompyle6 to make this easier.)\nThe tree at the point of call will have something like exec_stmt -> expr .... That expression will have the text of the expression which is not necessarily the value of the expression. The expression could be a constant string value, but it could be something complex like \"foo\" + var1. \nSo then the debugger can evaluate that string in the context of the debugger which knows how to evaluate expressions up the call stack.\nThis still has a problem of the reevaluating the expression may have side effects. But that's bad programming practice, right? ;-)\nSo instead what I do is just decompile the code from the bytecode if the source isn't there. This has a disadvantage in that the line numbers mentioned in the bytecode don't always line up with those in the bytecode. For that the method of recreating the string above is better. \nIn closing, I hope to give some idea why writing a really good debugger is hard and why the vast number of debuggers have a number of limitations on even simple things like getting the source text at the point you are currently stopped.\nA totally different approach would be to stop early and switch to an sub-interpreter like byterun (or some suitably modified Python C module) which would have access to a stack. \n\n"} +{"text": "Q:\n\nfork() bomb explanation in terms of processes?\n\nI am just wondering how a fork bomb works, I know that there are similar questions but the answers aren't quite what I am looking for (or maybe I just haven't been able to come across one)\nHow does it work in terms of processes? \nDo children keep being produced and then replicating themselves? is the only way to get out of it is by rebooting the system? \nAre there any long lasting consequences on the system because of a fork bomb? \nThanks!\n\nA:\n\nHow does it work in terms of processes?\n\nIt creates so many processes that the system is not able to create any more.\n\nDo children keep being produced and then replicating themselves?\n\nYes, fork in the name means replication.\n\nis the only way to get out of it is by rebooting the system?\n\nNo, it can be stopped by some automated security measures, eg. limiting the number of processes per user.\n\nAre there any long lasting consequences on the system because of a fork bomb?\n\nA fork bomb itself does not change any data but can temporarily (while it runs) cause timeouts, unreachable services or OOM. A well-designed system should handle that but, well, reality may differ.\n\n"} +{"text": "Q:\n\nFluentd + Elasticsearch = Connection refused\n\nI'm trying to connect fluentd with elasticsearch and I'm getting this error when I start the td-agent service.\ntd-agent.log:\nCould not communicate to Elasticsearch, resetting connection and trying again. Connection refused - connect(2) for 127.0.0.1:9092 (Errno::ECONNREFUSED)\ntd-agent.conf\n\n @type elasticsearch\n host localhost\n port 9092\n logstash_format true\n\n\nMy elasticsearch is running because I can check on http://localhost:9200/ and also the fluentd plugin\nplugin 2020-05-21 12:57:55 -0300 [info]: gem 'fluent-plugin-elasticsearch' version '4.0.8'\n\nA:\n\nIf you can access elasticsearch from localhost:9200 then the .conf will look like:\n\n @type elasticsearch\n host localhost\n port 9200\n logstash_format true\n\n\n"} +{"text": "Q:\n\nException ORA-08103: object no longer exists on using setfetchsize of Hibernate\n\nI'm using Hibernate. I need to fetch around 1000000 records and it will cause timeout exception. So I'm using setfetchsize for 6000 records, so that it will distribute the operation in multiple transactions each of 6000 records.\nIt will take around 21 hours to fetch all.\nBut meanwhile retrieving records if somebody deletes one of the record which was to be fetched then I get ORA-08103: object no longer exists.\nNow I want to skip that object which is deleted while retrieving. How can I do this?\n\nA:\n\nMost likely that a cursor is opened based on a global temporary table(GTT), which had been created with ON COMMIT DELETE ROWS option. And the cause of the ORA-08103: object no longer exists error is commit statement that followed right after the delete statement. Here is a simple example:\n SQL> declare\n 2 type t_recs is table of number;\n 3 l_cur sys_refcursor; -- our cursor\n 4 l_rec t_recs; \n 5 \n 6 begin\n 7 \n 8 -- populating a global temporary table GTT1 with sample data \n 9 insert into GTT1(col)\n 10 select level\n 11 from dual\n 12 connect by level <= 1000;\n 13 \n 14 open l_cur -- open a cursor based on data from GTT1\n 15 for select col\n 16 from GTT1;\n 17 \n 18 -- here goes delete statement\n 19 -- and\n 20 commit; <-- cause of the error. After committing all data from GTT1 will be\n 21 -- deleted and when we try to fetch from the cursor\n 22 loop -- we'll face the ORA-08103 error\n 23 fetch l_cur -- attempt to fetch data which are long gone.\n 24 bulk collect into l_rec;\n 25 exit when l_cur%notfound;\n 26 end loop;\n 27 \n 28 end;\n 29 /\n\nORA-08103: object no longer exists\nORA-06512: at line 24\n\nRecreation of global temporary table with on commit preserve rows clause will allow to safely fetch data from a cursor that is based on that table without being afraid of facing ORA-08103: error.\n\n"} +{"text": "Q:\n\nHow can a sine function be transformed to have flat peaks?\n\nI'm trying to create a sine function that will fit a geochron clocks day/night line. Right now I just started with a simple sine function, using map coordinates, which is this y=69sin(x-15)+2 but the peaks of the function should be flat which was not achieved with this function. Any advice on how to relatively easily transform the function to get this effect? \nThis is the online geochron clock that I was looking at http://www.fourmilab.ch/cgi-bin/Earth\n\nA:\n\nYou could just use min and max to cut off the function at the top and bottom. If $\\alpha$ is the minimum value and $\\beta$ the maximum then try\n$$\ny(x) = \\min(\\max(A\\cos(k(x-x_0))+c,\\alpha ) , \\beta) \n$$\nfor appropriate values of $A$, $k$, $x_0$, $c$, $\\alpha$, $\\beta$, where\n\\begin{gather}\nA>0\n\\\\\nk>0\n\\\\\nc-A<\\alpha<\\beta div {\n /* background: #ddd; */\n padding: 1em; /*<-- Remove this*/\n}\n\nHope that helps\n\n"} +{"text": "Q:\n\nset something on GUI form and thread sleep\n\nI have a GUI window form. I want to set image to pictureBox and next sleep 3 seconds.\n pictureBox.Image = image;\n Thread.Sleep( 3000 );\n\nBut if I do it like my code above, my form try to set image, next go to sleep for 3 seconds, and just after that my form draws itself. So my picture show after this 3 seconds. How can I set image, show it and just after that \"go to sleep\" ?\nedit 1\nexactly I want to do something like that:\nI have two thread, UI and GUI. UI reads from net socket and call right method from GUI. And can be script like that:\n\nUI call on GUI: set image\nUI call on GUI: do something (then GUI must clear image)\n\nBut I want to have sure, that I will be able to see this image. So after GUI set image, I call this thread for 3 seconds. So, how can I do it?\nExample:\n(function from GUI)\npublic void f1() {\n MethodInvoker method = () => {\n pictureBox.Image = image;\n pictureBox.Update();\n // do something more\n };\n\n if ( InvokeRequired ) {\n Invoke( method );\n } else {\n method();\n }\n\n }\n\npublic void f2() {\n MethodInvoker method = () => {\n pictureBox.Image = null;\n pictureBox.Update();\n // do something more\n };\n\n if ( InvokeRequired ) {\n Invoke( method );\n } else {\n method();\n }\n\n }\n\nAnd other function f3...fn\n public void f3() {\n MethodInvoker method = () => {\n // do something \n };\n\n if ( InvokeRequired ) {\n Invoke( method );\n } else {\n method();\n }\n\n }\n\nAnd, I my UI thread call function f1 and after it f2, I want to be sure that my user will be able to see this picture. But if my UI thread call function f1 and some between f3..fn call it normally.\nedit 2\nNo I make it that:\nI define function in GUI form (which is called by UI ):\n public void f1() {\n MethodInvoker method = () => {\n pictureBox.Image = image;\n pictureBox.Update();\n };\n\n MethodInvoker method2 = () => {\n // something\n }\n\n if ( InvokeRequired ) {\n Invoke( method );\n Thread.Sleep( 3000 ); // sleep UI thread\n Invoke( method2 );\n } else {\n method();\n method2();\n }\n }\n\nIt works, but it isn't the best solution. If will be script like this:\n- UI call f1\n- UI call f3\n\nUI will be sleep for 3 seconds and I don't expect it.\nWhat is the best solution for my problem?\n\nA:\n\nYou should never let your GUI sleep. At least not the way you are doing. If you use Thread.Sleep or other blocking mechanisms you will prevent the UI from doing what it is suppose to be doing; dispatching and processing messages.\nIf you really want to cause a delayed action then you would be better off using a System.Windows.Forms.Timer. Here is what I think you need to do. This of course is based on my vague understanding of what you mean by \"go to sleep\".\n\nSet your image.\nThen immediately disable all of the controls necessary that simulates whatever \"go to sleep\" means for you.\nThen start the timer.\nFinally in the Tick event add code that reverses whatever \"go to sleep\" means for you.\n\nA:\n\nTry one of these:\nForm.Refresh ();\nApplication.DoEvents;\n\nApplication.DoEvents\nI'm assuming WindowsForms.\n\n"} +{"text": "Q:\n\nUpdating the ListBox Items\n\nI have a TreeView with nodes, so when I click on one of the nodes I will be updating the ListBox with items bounded to an Observable Collection, which works fine. Next when I click another node in my tree view I will have to update the ListBox with different data(which is also an Obsv.Collection). Any Ideas on how to proceed with this? \n\n \n \n \n \n \n \n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\nCode Behind:\nprivate void Handle_Click1(object sender, MouseButtonEventArgs e) // tree view Item\n{\n ListBox1.DataContext = Clips Items;\n // Clips Items is an Obs v. Collection \n}\n\nI have a another Obs v Collection Still Items which I have to bound it to the List box to show another view \n\nA:\n\nYou can try the following:\n \n \n \n \n \n\n \n \n \n \n \n\nThe Binding will retrieve the items displayed in the ListBox from the SelectedItem in the TreeView using the Path SomeItems. This assumes the SelectedItem is something like this:\npublic class MyTreeViewItem\n{\n\n public string Name { get; private set; }\n public ObservableCollection SomeItems { get; private set; }\n\n public MyTreeViewItem(string name)\n {\n if (name == null)\n throw new ArgumentNullException(\"name\");\n\n this.SomeItems = new ObservableCollection();\n this.Name = name;\n }\n\n}\n\nWhen you select an item in the TreeView the children are displayed in the ListBox.\nEdit:\nTo populate the TreeView use the following code:\n MyTreeViewItem a = new MyTreeViewItem(\"A\");\n a.SomeItems.Add(new MyTreeViewItem(\"A1\"));\n a.SomeItems.Add(new MyTreeViewItem(\"A2\"));\n a.SomeItems.Add(new MyTreeViewItem(\"A3\"));\n\n MyTreeViewItem b = new MyTreeViewItem(\"B\");\n b.SomeItems.Add(new MyTreeViewItem(\"B1\"));\n b.SomeItems.Add(new MyTreeViewItem(\"B2\"));\n b.SomeItems.Add(new MyTreeViewItem(\"B3\"));\n\n this.MyTreeView.ItemsSource = new MyTreeViewItem[] { a, b };\n\n"} +{"text": "Q:\n\nIs there a way to make css letter-spacing: 0.5 px?\n\nI ran across the problem, I need to make it easy for users to read the text, so I used letter-spacing of 1 px, but it looks ugly, so I thought I'll use half a pixel so 0.5px, but it doesn't work, I tried using em attributes, but didn't achieve the task.\nSo is there a way to make letter spacing half pixel (cross browser solution if possible)\n\nA:\n\nThis bug has been reported back in 2008 and is confirmed. So if someone feels like hacking into webkit that would make a lot of designers happy.\nhttps://bugs.webkit.org/show_bug.cgi?id=20606\n\nA:\n\nSub-pixel letter spacing works fine on FF, but not on WebKit (at least on Windows). See this test case:\nhttp://jsfiddle.net/fZYqL/2/\nThis test also shows that it is not the sub-pixel literal value that is a problem. Using fractional em values that result in less than 1px of letter-spacing are also not honored on Webkit, but work just as well on Firefox.\n\nA:\n\nThis bug has been fixed in Chromium and landed in Chrome 30. So fractional values are now supported by Firefox, Chrome and Opera.\n\n"} +{"text": "Q:\n\nASP.NET core model validation doesn't work as expected\n\nAccording to Microsoft documentation, if a model property is not-nullable, it is considered required by default, so there's no need to explicitly add the [Required] attribute.\n\nBy default, the validation system treats non-nullable parameters or properties as if they had a [Required] attribute. Value types such as decimal and int are non-nullable.\n https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#required-attribute\n\nBut that's not practically true. Let's say I have the following model:\npublic class Model\n{\n [Required]\n public string Name { get; set; }\n public int Age { get; set; }\n}\n\nIf the request doesn't contain Age in its body, a 0 is bound to the Age property and model validation doesn't fail. Even with [Required], model validation still doesn't fail and 0 is assigned to Age. So how do I make properties with not-nullable types really \"required\"?\n\nA:\n\nThree options imho: \n\nValidate yourself that Age is not the default value\nUse a Range attribute\nMake it required and nullable\n\n[Required]\npublic int? Age { get; set; }\n\nIt depends very much on your circumstances if nullable-required is a nice solution or just a dirty workaround.\n\n"} +{"text": "Q:\n\ndsPIC33 ADC: Why is the minimum TAD interval such an oddly-specific number (117.6ns) for 12-bit conversion?\n\nI'm writing the firmware for a data-acquisition board using the dsPIC33FJ64GP804 MCU and I noticed something strange reading the electrical characteristics for 12-bit A/D conversion:\n\nThe ADC clock period (emphasis mine) is listed as 117.6ns, which is an oddly-specific number, especially considering there's no direct hardware obstacle to try running your ADC much faster, e.g. with TAD = FCY, which could be as low as 25ns at the highest officially allowed clock speed. So the limit doesn't come from there.\nThe characteristics for 10-bit conversion seems more like it's been derived from actual characterization testing:\n\nSo where does this weird value come from? Something related to the settling time of the sample&hold capacitor (esp. considering TSAMP = 3 TAD for 12-bit and TSAMP = 2 TAD for 10-bit)?\nEdit\nTo clarify, I understand TAD = 25ns would be asking for trouble. My main questions are:\n\nWhy is TAD different for the 10-bit and the 12-bit case at all?\nWhere does the 12-bit number come from, could IC characterization (which I guess involves statistical methods and uncertainty) really produce a number that precise?\n\nA:\n\nThere are some clues in the datasheet.\nFor instance:\n\nThe AD12B bit (AD1CON1<10>) allows each of the ADC modules to be\n configured by the user as either a 10-bit, 4-sample/hold ADC (default\n configuration) or a 12-bit, 1-sample/hold ADC.\n\nThen this:\n\n\u2022 In the 12-bit configuration, conversion speeds of up to 500 ksps are\n supported \n\u2022 There is only one sample/hold amplifier in the 12-bit\n configuration, so simultaneous sampling of multiple channels is not\n supported\n\nI agree the unusually precise value is odd, but if you convert that to a sample rate it yields about 607K samples per second (a bit above the maximum stated rate) (14 ADC periods are required for a 12 bit conversion).\nIn the ADC reference manual there is a schematic of the effective ADC input in the two modes;\n\nNote the difference in the input capacitance; this is necessary as the sample capacitor has to hold the charge for a longer period of time for the conversion to be accurate and will therefore require a longer time to actually charge up during the sample period.\nLooking at the values, it appears that the effective capacitance for 12 bit mode is formed of all 4 sample and hold capacitors (4 * 4.4 = 17.6, 18 when rounded) and that makes sense of the statement that there is only one sample and hold in 12 bit mode. Probably achieved by switches isolating the other channel sample and holds from their caps and switching them in to form a single effective device.\nHence a longer ADC period (longer charge time and a longer hold time). \nThe value in the datasheet may be from calculations or experimentation (I do not know which).\n\n"} +{"text": "Q:\n\nCan you determine if the user just unlocked the mobile device using biometrics?\n\nI have an app that currently requires a user to provide a PIN code upon opening, or to unlock the app using biometrics such as face recognition or fingerprint identification.\nWhen the app receives a push notification on iOS, it seems quite redundant however to have the user unlock the phone with FaceId and then immediately require the user to do this again to enter the app and view the notification details.\nThe same would presumably hold true using TouchId or Android fingerprint identification.\nIs there a reasonable way that I could detect that the device was biometrically unlocked, and thus skip the redundant pin/biometric check?\n\nA:\n\nReading through what you've written I had a thought in my mind: why exactly are you pivoting around biometric unlock? For your purposes, I guess, any kind of unlock will do. Give this thread a shot Android - detect phone unlock event, not screen on\n\n"} +{"text": "Q:\n\nXMLHTTP: Internal server error - issue with GET?\n\nI'm trying to retrieve some data from a MySQL database that I have stored on a server. I'm using PHP, Javascript and AJAX to get the data.\nWhen I run the HTML file (New.html) in Chrome and look at the code using developer tools, it says;\n\nGET http://example.net/Example/getuser.php?q=2 500 (Internal Server Error)\nshowUser @ New.html:31onchange @ New.html:52\n\nI think this refers to xmlhttp.onreadystatechange, and there is a red X beside the .send() line.\n\n\n New\n \n //Javascript Code\n\n //CSS for HTML table\n\n\n \n\n
\n \n
\n
\n
MySQL Data should go here
\n\n\n\nDoes anyone know how to solve these issues? Perhaps the .open() needs to be placed earlier in the code? Or maybe a handler of some kind is needed?\nPHP File:\n\n\n Latest Attempt\n\nconnect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n }\n echo \"Connected successfully\";\n \n mysqli_select($conn,\"ajax_demo\");\n $sql=\"SELECT * FROM my_DB WHERE id = '\".$q.\"'\";\n $result = mysqli_query($conn,$sql);\n \n echo \"\n \n \n \n \n \n \n \";\n while ($row = mysqli_fetch_array($result)) {\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n echo \"\";\n }\n echo \"
FirstNameLastNameAgeHometownJob
\" . $row['FirstName'] . \"\" . $row['LastName'] . \"\" . $row['Age'] . \"\" . $row['Hometown'] . \"\" . $row['Job'] . \"
\";\n mysqli_close($conn);\n?>\n\n\nA:\n\nYou have a few misspells in your code which if you fix them your code will work perfectly:\nIn you JavaScript\nAt this line\ndocument.getElementById(\"txtHint\").innerHTML = this.reponseText;\n\nYou have misspelled reponseTextand it should be responseText so This line will be like:\ndocument.getElementById(\"txtHint\").innerHTML = this.responseText;\n\nIn your PHP\nYou have to remove all these extra html tags from the top of the page:\n\n\n Latest Attempt\n\n\nand this tag from the bottom of the page:\n\n\nThen you in this line:\n$q = intval($_get['q']);\n\nYou have to type $_GET in capital so it will be like:\n$q = intval($_GET['q']);\n\nAnd finally mysqli does not have mysqli_select() function, so you have to remove this line completely:\nmysqli_select($conn,\"ajax_demo\");\n\nAnd now you are good to go :)\n\n"} +{"text": "Q:\n\nIntegrals Clarification Needed\n\nMissed a couple days of class, can't seem to figure out how to get the numbers marked with the blue arrows. Other than that I understand the concept.\n\nA:\n\nAlright, I've done this problem on ms paint. This is how the answer is $-136$\nWe have the definite integral of \n$\\int^4_2 (10+4x-3x^3)\\,dx$\nBefore we can evaluate the definite integral, we need to take the antiderivative of $10+4x-3x^3$. To take the antiderivative we need to add one to the exponent and divide by the new exponent number. Since we only have $10$, the antiderivative is $10x$. \nHow did we get $10x?$\nWell, when we had $10$, there was no exponent, so when we add the exponent $x$ that's $x^1$ but we don't write it that often, and divide by the new exponent number, so we have $\\frac{10x^1}{1} \\rightarrow 10x$\nFor $4x$, we add one to the exponent so that becomes $4x^{1+1}$. Since we have $4x^2$, we need to divide by the new exponent number which is 2. $\\frac{4x^2}{2}$ and that becomes $2x^2$.\nFor $3x^3$ the new exponent number is $4$ and we divide by $4$. There is nothing to reduce, so we're done. \n$3x^{3+1} \\rightarrow 3x^4 \\rightarrow \\frac{3x^4}{4}$\nSo now we have $10x+2x^2 -\\frac{3x^4}{4}$\nYou can check to see if it's correct by taking the derivative, and it will be $10 +4x-3x^3$\n$\\int^4_2 (10x+2x^2-\\frac{3x^4}{4})\\,dx$\nNow we evaluate using $F(b) -F(a)$ where $b=4 $ and $ a=2$.\nFor $F(4)-F(2)$, we have\n$10(4)+2(4)^2-\\frac{3(4)^4}{4}-[10(2)+2(2)^2-\\frac{3(2)^4}{4}]$\n$40+2(16)-\\frac{256(3)}{4}-[20+8-\\frac{48}{4}]$\n$40+32-\\frac{768}{4}-[20+8-12]$\n$72-192-[28-12]$\n$72-192-28+12$\n$-148+12$\n$-136$\n\n"} +{"text": "Q:\n\nReduce Parse PFFile, images and text\n\nI have a UItextView which I place images and type text into, and once I have finished with the TextView I then upload the contents of that textView to Parse.\nIf I only add 1 image to the textView it lets me upload the UITextView contents to Parse without any problems, but when I add more than 1 Image I get the error \"data is larger than 10mb etc...\".\nNow I am wondering how I can reduce the size of this PFFile?\nOr is their a way to reduce the size of the images before or after adding the to the textView? possibly extract the from th etextView and reduce there size before uploading to Parse?\nThis is my code:\nHere is where the text & images from the textView are stored:\nvar recievedText = NSAttributedString()\n\nAnd here Is how I upload it to Parse:\nlet post = PFObject(className: \"Posts\")\n let uuid = NSUUID().UUIDString\n post[\"username\"] = PFUser.currentUser()!.username!\n post[\"titlePost\"] = recievedTitle\n let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(recievedText)\n post[\"textPost\"] = PFFile(name:\"text.txt\", data:data)\n post[\"uuid\"] = \"\\(PFUser.currentUser()!.username!) \\(uuid)\"\n if PFUser.currentUser()?.valueForKey(\"profilePicture\") != nil {\n post[\"profilePicture\"] = PFUser.currentUser()!.valueForKey(\"profilePicture\") as! PFFile\n }\n\n post.saveInBackgroundWithBlock ({(success:Bool, error:NSError?) -> Void in\n })\n\nBest regards.\nHow I add the images\nimage1.image = images[1].imageWithBorder(40)\n let oldWidth1 = image1.image!.size.width;\n let scaleFactor1 = oldWidth1 / (blogText.frame.size.width - 10 )\n image1.image = UIImage(CGImage: image1.image!.CGImage!, scale: scaleFactor1, orientation: .Up)\n let attString1 = NSAttributedString(attachment: image1)\n blogText.textStorage.insertAttributedString(attString1, atIndex: blogText.selectedRange.location)\n\nA:\n\nYou should to resize the picture to make sure it is small size for upload. See this answer\n\n"} +{"text": "Q:\n\nhibernate DAO design\n\ndo i have to open and close session and transcation in each function (make object ,delete object ,findbyID)\ncan u give me a DAO implenetation for findall (lazy initialization ).\n\nA:\n\nYou should have a transaction for each complete business operation. I For instance: The operation includes selecting some values, updating it and inserting others. If each of the elementary operations create their own transaction, you will fail writing a multi-user application.\nYou should create the session at the beginning of the business operation, create a transaction, then perform all the operations (you \"functions\") within that transaction, and commit or rollback them all together.\nTransactions are defined in the business layer.\n\n"} +{"text": "Q:\n\nA question about differentiability\n\nDoes there exist a continuous function $f:\\mathbb{R}\\to\\mathbb{R}$ so that $f$ is differentiable exactly at one point?\n\nA:\n\nYes. Idea: choose a function which is continuous but nowhere differentiable. Then multiply it with $x^2$, say.\n\n"} +{"text": "Q:\n\nAutomatically restart a python if it closes or crashes\n\nI have 3 python files, 1.py, 2.py, 3.py and I'm trying to make a bat batch file that restarts my python files in case they break or close for some reason.\nI'm trying with the following code, but it is not working very well:\n@echo off\n:Restart\nstart \"1\" /wait \"C:\\Users\\PC\\Desktop\\test\\1.py\"\nstart \"2\" /wait \"C:\\Users\\PC\\Desktop\\test\\2.py\"\nstart \"3\" /wait \"C:\\Users\\PC\\Desktop\\test\\3.py\"\ngoto Restart\n\nmy goal is, with just a bat file, to automatically restart any of my 3 files in case any of them close or crash.\nif only one of them has closed, restart only it, or if two of them close, restart both, so on\n\nA:\n\nI am just copying-pasting my answer from your another dublicate question (Batch that monitors and restarts a python):\nA combination of an \"infinite loop\" which is needed in your case and python files will overload your CPU a lot I think. Have a revised piece of code (working only in single file extensions (*.bat, *.txt)). See below for something more general.\n@echo off\nsetlocal EnableExtensions\n\n:start_python_files\nstart \"1st\" \"test1.py\"\nstart \"2nd\" \"test2.py\"\nstart \"3rd\" \"test3.py\"\n\n:check_python_files\ncall:infinite 1st test1.py\ncall:infinite 2nd test2.py\ncall:infinite 3rd test3.py\ngoto:check_python_files\n\n:infinite\ntasklist /FI \"WINDOWTITLE eq %1 - %2\" | findstr /c:PID > nul\nrem findstr /c:PID command added above to confirm that tasklist has found the process (errorlevel = 0). If not (errorlevel = 1).\nif %errorlevel% EQU 1 (start \"%1\" \"%2\")\n\nWell, this way may last some time, so if a file is closed (~2-3 secs depending on your CPU overload).\nPlease notify me if it is not working for you. I haven't python installed and I don't know how they are named when they are opened :).\nSo, now as you have (kindly???) requested complete answers let me explain my code:\n\nI enable extensions (setlocal EnableExtensions) to change call command as follows:\n\nCALL command now accepts labels as the target of the CALL. The syntax\n is:\nCALL :label arguments\n\nFrom call /? command. You should type it in a fresh cmd for more information\n\nI specify the window title with the start command, so my code will work. Type start /? in a fresh cmd window.\nI call the infinite subroutine sending to it arguments (window title and filename). These can be accessed with %1 (first argument) and %2 (second argument).\nIn the infinite subroutine, I search for window title (WINDOWTITLE) EQUAL (eq) to format window title - filename. Even if it doesn't exist tasklist will return errorlevel value 0 with the message:\n\nINFO: No tasks are running which match the specified criteria.\n\nAs here PID string doesn't exist (if it is found it will exist), we put findstr to search for it. If found, errorlevel will be 0. Else, it would be 1.\n\nIf the errorlevel is 1, that means that process not found, which means that the file is closed. So, we reopen it with the arguments sent (start \"window title (%1)\" \"filename (%2)\").\nAs we have called the infinite subroutine, after its end, we will return to check_python_files subroutine doing all of these above infinitely, until user termination or computer shutdown.\n\nAs later discussed in chat, when we run python files standardly (with start \"window title\") window title will be the full path to python.exe file. I found a way to fix it: start the cmd /c command. A revised piece of code:\n@echo off\nsetlocal EnableExtensions\n\n:start_python_files\nstart \"1st\" \"cmd /c test1.py\"\nstart \"2nd\" \"cmd /c test2.py\"\nstart \"3rd\" \"cmd /c test3.py\"\n\n:check_python_files\ncall:infinite 1st test1.py\ncall:infinite 2nd test2.py\ncall:infinite 3rd test3.py\ngoto:check_python_files\n\n:infinite\ntasklist /FI \"WINDOWTITLE eq %1\" | findstr /c:PID > nul\nrem findstr /c:PID command added above to confirm that tasklist has found the process (errorlevel = 0). If not (errorlevel = 1).\nif %errorlevel% EQU 1 (start \"%1\" \"cmd /c %2\")\n\nI have just added only a cmd /c extra (and remove %2) from window title as it was not needed.\ncmd /c tells system to run a new cmd which will carry out the command specified by string and then it will terminate.\nSynopsis:\n\nCommands should be run to get more information about how they work:\n\ncall /?\nstart /?\ngoto /?\ntasklist /?\nfindstr /?\ncmd /?\n\nI suggest to run the above in a fresh new cmd window.\n\nSome interesting references:\n\nhttps://ss64.com/nt/start.html\nHow do I pass command line parameters to a batch file?\nSet Windows command-line terminal title in Python\n\nI am really sorry for putting you into this mess. In anyway, thank you for providing such good information for me to understand where I was wrong.\n\n"} +{"text": "Q:\n\nJava set string as class name to run\n\nI have a question, i have a code like below:\ncontroller.start(c.class, 1);\n\nbut i want to set \"c\" from console. I can get/set it from args on main method . but how can i put it on c.class ? I mean how can i do that? \nString a = \"c\";\ncontroller.start(a.class,1);\n\nOf course it doesnt work , but i hope i can tell u about my problem\nOn php we can use $$string to set/get string to variable, but i dont know how can we do it on Java ? \n\nA:\n\nMore commonly used (and more secure) way of addressing this is using maps:\nprivate static final Map> NAME_TO_CLASS = new Map<>();\nstatic {\n NAME_TO_CLASS.put(\"c\", c.class);\n ...\n}\n\nstatic void main(String[] args) {\n ...\n controller.start(NAME_TO_CLASS.get(args[0]), 1);\n}\n\nOf course in real life you'd want to check if argument is correct and is in the map NAME_TO_CLASS.contains(your_arg);\n\n"} +{"text": "Q:\n\nGeneral approaches and techniques for developing good explanatory models for nonlinear data\n\nVarious recent efforts of mine on modelling some data through logistic regression have been... not successful. While there is still more data to look at, I've been wanting to explore nonlinear dependencies in the data too.\nAre there techniques out there that have better fitting capabilities than logistic regression (or linear regressions in general) that still retain easy interpretability and explanatory power (i.e. are not neural networks or other 'black box' techniques)?\nMy initial intuition is to apply transforms to the individual variables and combinations thereof. For the variables $ x_1...x_n $, possibilities include taking $log(x_i)$, $x_i^m$, $\\sqrt[m]x_i $ or $x_i * x_j$ etc. Third order relationships (i.e. $x_i *x_j *x_k$) would be omitted as they aren't easy to visualise or graph.\nNeedless to say, even for a smallish number of variables, the number of these transformed variables could easily balloon to unwieldy sizes, and the number of combinations of these variables to systematically try would be similarly huge. Furthermore, there would be issues of multicolinearity between the various transforms of a given variable $x_i$. \nEDIT:\nI'm now considering using orthogonal polynomials for the continuous variables and logical combinations ( $x_i & x_j* ) for the categorical variables of different types. I feel like I'm reinventing the wheel here, yet still haven't found useful information on doing this sort of stuff sensibly. Any help would be greatly appreciated.\n\nA:\n\nI think it is worth considering the use of generalised additive models (GAMs). GAMs are able to encapsulate non-linear relations between the response variable and the outcome variables and are straight-forward to explain. They are well-understood and widely used within the Statistics community.\nIn totally informal manner: GAMs are practically GLMs with a out-of-the-box, semi-automated basis expansion module strapped in. No need to define quirky $x^{\\frac{1}{4}}, \\sin(2\\pi x)$, etc. transformations, the best non-linear relation will be automatically selected. GAM are great to visualise the (potentially) varying influence of $x$ on the outcome $y$.\nThere is an abundance of good resources on using GAMs online (e.g. here and here), in print (e.g. here and here) and CV has literally dozens of insightful questions and answers on generalized additive models.\nR has two extremely good GAM packages gam and mgcv. I would suggest you start with mgcv as a matter of convenience.\nI would suggest you also look at the FAT/ML (Fairness, Accountability, and Transparency in Machine Learning) initiative. It has some great novel ideas. In relation with GAMs I would point you to the 2017 invited talk by Rich Caruana on \"Friends Don\u2019t Let Friends Deploy Black-Box Models\"; it shows an application of an extension of GAMs (called GA2M) that is used instead of standard ML techniques (random forests) and gives results of similar accuracy but also being fully interpretable.\n\n"} +{"text": "Q:\n\nWon't Vimeo.com Run out of ID's very soon?\n\nI recently noticed that the Vimeo id's are a string of 8 integers. That means that, at most, the scheme can accomodate 10^8 videos - or 100 Million Videos. Sure, that's a huge number, but still very very finite. Won't they run out of space very soon? Do I have to plan my applications for when they add more integers or if they change to letters and integers or something? Or is there something I'm missing?\n\nA:\n\nThere are videos with less than 8 digits, so it would seem they're just increasing the number by 1 for each video. You should in other words definitely plan for a 9'th digit.\nPersonally, I'd store the whole URL for videos as a string, which would let you handle any future video numbering scheme they can think up. Counting on them always being numeric for ever is probably not a good idea, everybody seems to be doing vanity URL's by now :)\n\nA:\n\nNo, they won't. They can just add more digits if necessary.\nAlso note that Vimeo's URIs are largely conforming to the W3C's recommendations for URIs in that they don't reveal internal implementation details - so you cannot say for certain that video IDs truly are 8-digit integer strings.\n\n"} +{"text": "Q:\n\nHow to save/export array as PDF in MATLAB\n\nI have a large cell array which I want to export as report-like format. Is it possible to export arrays (strings and numbers) as a PDF file?\nFor example, say I have this cell array\ndata = {'Frank' 'Diana' '06-May-2018'}\n\nand I want to export the this array content to a PDF file. In this case it should simply create a PDF file with the text:\n\nFrank Diana 06-May-2018\n\nA:\n\nThe only way I know of for MATLAB to generate a PDF file is through a figure window. You can write text to a figure window, and print it to a PDF file:\nfh = figure;\nah = axes('parent',fh,'position',[0,0,1,1],'visible','off',...\n 'xlim',[0,1],'ylim',[0,40],'ydir','reverse',...\n 'fontsize',14);\ntext(0.01,1,'text line 1','parent',ah);\ntext(0.01,2,'text line 2','parent',ah);\nprint(fh,'-dpdf','output.pdf')\n\nThe MATLAB File Exchange has a bunch of submissions that can help you print text to a figure window. Search for the tag \"fprintf\".\nAn alternative solution is to write the data to e.g. a Word document, or a Markdown or LaTeX file, and call appropriate programs from within MATLAB to convert those to PDF. The File Exchange has a submission to control Word. The pandoc or pdflatex external programs can be invoked through the ! or system functions.\n\n"} +{"text": "Q:\n\nContinuous bijective function between $\\Bbb{R}$ and $[0,1]$?\n\nDoes a continuous bijective function from $\\Bbb{R}$ to $[0,1]$ exist? If not please explain. Here $[0,1]$ and $\\Bbb{R}$ have the usual topology.\n\nA:\n\nHint: Injective continuous functions $\\Bbb R\\to\\Bbb R$ must be monotone. \n\n"} +{"text": "Q:\n\nFormatar nomes de arquivos usando Express\u00e3o Regular\n\nEstou tentando renomear alguns arquivos usando Express\u00e3o Regular, mas estou empacado em um formato especifico. Tenho arquivos de v\u00eddeo nesse formato:\n\nYu.Yu.Hakusho Ep.001 - A Morte\n\nPreciso formatar usando regex para:\n\nYu.Yu.Hakusho.S01E01 - A Morte\n\nTentei usando ([^ ]+)*.(\\w{0,2}).([0-9]+)*.(.*.) para capturar somente aquilo que preciso e formatar, como pode ser visto logo abaixo:\n$texto = \"Yu.Yu.Hakusho Ep.001 - A Morte\";\n$regex = \"/([^ ]+)*.(\\w{0,2}).([0-9]+)(.*.)/\";\npreg_match($regex,$texto,$m); \n\necho $m[1].\".S01E\".$m[3].$m[4];\n\nE a saida \u00e9 \n\nYu.Yu.Hakusho.S01E001 - A Morte\n\nn\u00e3o estou sabendo como deixar a sequencia 001 apenas com os dois \u00faltimos digitos.\nComo fa\u00e7o essa substitui\u00e7\u00e3o com regex?(n\u00e3o posso usar replace, preciso fazer apenas com ER mesmo)\n\nObs.: usei o php como exemplo, mas preciso necess\u00e1riamente aplicar uma\n regex, independente de linguagem, como pode ser visto aqui nesse link:\n https://regex101.com/r/dC3aN4/1\n\nA:\n\nCriei outro pattern de regex do zero, porque achei o seu um pouco \"desorganizado.\"\nPattern: (.*?) .*?\\d?(\\d{2}).*?(\\w.*)\nSubstitui\u00e7\u00e3o: \\1.S01E\\2 - \\3\nSe preferir usar o mesmo pattern que j\u00e1 estava usando, eu fiz uma vers\u00e3o modificada dele: ([^ ]+)* (\\w{0,2})\\.\\d?(\\d{1,2})*.(.*.)\" A substitui\u00e7\u00e3o continua a mesma.\n\n"} +{"text": "Q:\n\nCreate iterable list from very large number of entries\n\nI have a file that has well over 600,000 entries. It basically contains:\nuser1 choice1\nuser1 choice2\nuser2 choice3\nuser2 choice1\n.\n.\n.\n.\nuser400000 choice60\n\nWhen I try to create a dictionary by usual methods (shown below), idle stops responding.\nd = {}\nwith open(\"file.txt\") as f:\n for line in f:\n (key, val) = line.split()\n d[key] = val\n\nI want an easily and quickly manipulatable list/dictionary from this large file of entries. What would be the most efficient way to get that? \n\nA:\n\npandas allows to manipulate this amount of data easily. Your data is a series of user labels with a scalar data point associated to it.\nimport pandas as pd\ns = pd.read_csv('file.txt', sep=' ', header=None, index_col=0, squeeze=True)\n\nThis instruction asks pandas to load the file data into a Series object:\n\ncolumns are space separated (sep=' ')\nthe file has no title header and the first line is already data (header=None)\nwe want to manipulate the date with the first column as an index (index_col=0)\nby default, pandas builds a DataFrame object, but if it contains a single column of data, we can ask for a Series instead (squeeze=True)\n\ns is a Series object indexed on the user labels we can now use to access the data:\nIn [37]: s.head()\nOut[37]: \n0\nuser0 104106\nuser1 31024\nuser2 82993\nuser3 211414\nuser4 499070\nName: 1\n\nIn [38]: s['user3']\nOut[38]: 211414\n\nWith a 'file.txt'of 600000 lines, it took around a second to load s. Following dict-like accesses on s are immediate.\n\n"} +{"text": "Q:\n\nClearest way to cast a string bool value to bool\n\nI have a function that returns a string true/false value as a bool, what is the best/clearest way to return this? I want to default that anything other than 0 or a case insensitive false is true. This is what I have, but I feel its poorly readable yet functional. \nbool isTrue = !resultString.Equals(\"FALSE\", StringComparison.OrdinalIgnoreCase);\nif(isTrue)\n isTrue = !resultString.Equals(\"0\");\nreturn isTrue;\n\nI feel there has to be a better way to go about this.\n\nA:\n\nAnother option is Convert.ToBoolean();\nbool isTrue;\ntry\n{\n isTrue = Convert.ToBoolean(resultstring);\n}\ncatch\n{\n isTrue = true;\n}\n\nSee: https://docs.microsoft.com/en-us/dotnet/api/system.convert.toboolean?view=netframework-4.8#System_Convert_ToBoolean_System_String_\n\n"} +{"text": "Q:\n\nGeneralized Induction Verification\n\nConsider the following simple exercise.\n\nProve or disprove: $\\gcd(km, kn) = k \\gcd(m, n)$, where $m, n, k$ are natural numbers.\n\nNow, this is easy to prove using prime factorization. Knowing that this proposition was true, I decided to try and prove it just using induction and the Euclidean algorithm.\nI only recently learned about generalized induction, so I was wondering if someone could look this over and tell me if it is valid or not.\n\nSince the $\\gcd$ function is symmetric with respect to its arguments, we can assume without loss of generality that $m \\le n$. We proceed by strong induction using a lexicographical ordering $(<<)$ on $\\mathbb{N}^2$.\nFor $m = n = 0$, the result is trivial. Assume true for all $(m', n') < < (m, n)$. Then\n \\begin{align*}\n k\\gcd(m, n) &= k \\gcd(n \\!\\!\\!\\!\\mod m, m) & \\textit{By the Euclidean algorithm}\\\\\n &= \\gcd( k (n \\!\\!\\!\\!\\mod m), k m) & \\textit{By induction}\\\\\n &= \\gcd( k n \\!\\!\\!\\!\\mod k m, k m) & \\textit{Property of mod function} \\\\\n &= \\gcd( k m, k n) & \\textit{By the Euclidean algorithm}\\\\\n \\end{align*}\n The reader will forgive the slight abuse of notation: $n \\!\\!\\mod m = n - m \\lfloor n / m\\rfloor$. Thus the result holds for all pairs of natural numbers. \n\nA:\n\nYour proof is very close. The problem is with the base case. You cannot take a number modulo $0$, and you do not eliminate the possibility that $m=0$. Instead of proving just the case $(m',n')=(0,0)$ (and is that trivial by the way? ... I have never seen anyone take the GCD of $0$ and $0$), I would take as base case all $(0,n)$ for $n\\in\\mathbb{N}$. This is easy since $$k\\gcd(0,n)=kn, \\quad\\gcd(k\\cdot0,k\\cdot n)=\\gcd(0,kn)=kn.$$ Now the next case must have $m\\ge 1$, so your proof follows through validly.\n\nIf this is your first time using strong induction, I have always found it very helpful to make things \"concrete\" to aid my understanding. I like to actually \"visualize\" the transition that happens from base case to case I, from case I to case II, etc. Your proof is a sort of \"algorithm\" which we can follow to make each transition.\nHere, we have established the case $(0,0)$. Next in line is $(0,1)$. You proof tells us to write down $$k\\gcd (0,1)=k\\gcd (1\\bmod 0,0)=\\gcd(k\\bmod (k0),k\\cdot 0)$$ But already this is making no sense. What is $1\\bmod 0$?\nNow assume that we have strengthened our base knowledge to all $(0,n)$. Next in line is $(1,0)$. We write $$k\\gcd(1,0)=k\\gcd(0\\bmod 1,1)$$ By induction (i.e. previous knowledge) this is $$\\gcd(k\\cdot 0\\bmod 1,k\\cdot 1)=\\gcd(k\\cdot 0\\bmod (k\\cdot 1),k\\cdot 1)=\\gcd(k\\cdot 1,k\\cdot 0)$$ and we have proven the case! You can see how each case follows naturally from a previous one.\n\n"} +{"text": "Q:\n\nHow to disable Ctrl-Space selecting chinese keyboard on windows 7?\n\nI would like to use both chinese keyboard and eclipse ctrl-space for suggestions popup. Since I use chinese very rare, I would like just to disable ctrl-space selecting this language.\nI have removed this combination from windows' chinese keyboard setup, but it either returns (if I remove) or just works without setting (if chaged).\nHot to disable ctrl-space totally for keyboard?\n\nA:\n\nI've been aware of this Windows bug for years. After tons of unsatisfying workarounds and fruitless searching the one or two times a year I attempt to find a solution, I finally have it!\nProcedure\n\nGo to Start > Type in regedit and start it\nNavigate to HKEY_CURRENT_USER/Control Panel/Input Method/Hot Keys\nSelect the key named:\n\n00000070 for the Chinese (Traditional) IME - Ime/NonIme Toggle hotkey\n00000010 for the Chinese (Simplified) IME - Ime/NonIme Toggle hotkey\n\nIn the right sub-window, there are three subkeys.\n\nKey Modifiers designate Alt/Ctrl/Shift/etc and is set to Ctrl (02c00000).\nVirtual Key designates the finishing key and is set to Space (20000000).\n\nChange the first byte in Key Modifiers from 02 to 00\nChange the first byte in Virtual Key from 20 to FF\nLog off and log back on. I don't think it's necessary to restart.\nDo not change the Hot keys for input languages in Control Panel, unless you want to do this all over again.\n\nNotes: Symptoms\nEach registry key (thing that looks like a folder) is for each specific hotkey setting that you would normally find in Control Panel > Region and Language > Keyboards and Languages > Change keyboards... > Advanced Key Settings > Hot keys for input languages. The recurring bug is the hotkey being automatically reset to Ctrl+space even if changed via the GUI.\nThis is for Windows 7 64-bit, though from my research, it looks like it may work for XP and Vista as well.\nSources:\nTraditional Chinese Pocket IME Hot Key Registry Settings \nSimplified Chinese MSPY 3.0 IME Hot Key Registry Settings \n\n"} +{"text": "Q:\n\nHow to make the program give an error message when an incorrect ticker symbol is entered in a program that scrapes websites for stock data\n\nI am coding a project in which the user inputs the ticker of a stock, and then the program scrapes information about that stock from a specific website and returns the data. I have a fully working program, but an issue I have is that if the user enters a nonexistent stock ticker, the program gives an error and stops working. How can I fix this? Here is the relevant code segment for reference:\ndef make_url(ticker_symbol): #making a function that returns a URL when a ticker is passed through it\nreturn \"https://www.bloomberg.com/quote/%s:US\" % ticker_symbol\n\ndef Calculation():\nlower_stock = Ticker_entry.get()\nstock = lower_stock.upper()\nurl = make_url(stock)\npage = requests.get(url) #requesting the HTML code of the website\nsoup = BeautifulSoup(page.content, \"lxml\") #Converting the HTML code of the website into a beautifulsoup object\n\nHow do I make it such that if the user enters a nonexistent stock, the program gives a message saying \"Please enter a valid stock ticker.\"?\nHere is the full code for reference:\nimport matplotlib\nimport sys\nfrom requests.exceptions import ConnectionError\nimport matplotlib.dates as dates\nfrom tkinter import *\nfrom bs4 import BeautifulSoup\nimport requests\nimport lxml\nimport datetime\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib import pyplot as plt\n\n#Graphical User Interface\n#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nroot = Tk()\nroot.title(\"Stock Price\")\nroot.configure(background=\"white\")\n\nCalculator = Frame(root, height=300, width=700, bg=\"white\").grid(column=0, row=2)\ntitle = Label(root, bg=\"white\", text=\"Stock Price Calculator\", font=\"Sans 25 bold\", fg=\"black\").grid(row=0)\n\nStock_ticker = Label(root, text=\"Input stock ticker here:\", font=\"Sans 18 bold\")\nStock_ticker.place(x=7, y=60)\nTicker_entry = Entry(root, width=10)\nTicker_entry.place(x=235, y=64)\n\nStock_price = Label(root, text=\"Current stock price:\", font=\"Sans 15\")\nStock_price.place(x=7, y=100)\n\nStock_price_output = Entry(root, width=10)\nStock_price_output.place(x=160, y=100)\n\nStock_price_day = Label(root, text=\"Opening price for the day:\", font=\"Sans 15\")\nStock_price_day.place(x=7, y=140)\n\nStock_price_day_output = Entry(root, width=10)\nStock_price_day_output.place(x=195, y=141)\n\nLast_closing_price = Label(root, text=\"Last closing price:\", font=\"Sans 15\")\nLast_closing_price.place(x=7, y=180)\n\nLast_closing_price_output = Entry(root, width=10)\nLast_closing_price_output.place(x=180, y=181)\n\nStock_news = Label(root, text=\"News about stock:\", font=\"Sans 15\")\nStock_news.place(x=7, y=220)\n\nStock_news_output1 = Entry(root, width=50)\nStock_news_output1.place(x=150, y=221)\n\nStock_news_output2 = Entry(root, width=50)\nStock_news_output2.place(x=150, y=242)\n\nStock_news_output3 = Entry(root, width=50)\nStock_news_output3.place(x=150, y=263)\n\nSubmit = Button(root, text=\"Submit\", font=\"Sans 14\", command = lambda: Calculation())\nSubmit.place(x=165, y=300)\n\nReset = Button(root, text=\"Reset\", font=\"Sans 14\", command = lambda: Cleaning(Ticker_entry, Stock_price_output, Stock_price_day_output, Last_closing_price_output, Stock_news_output1, Stock_news_output2, Stock_news_output3))\nReset.place(x=250, y=300)\n#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef make_url(ticker_symbol): #making a function that returns a URL when a ticker is passed through it\n return \"https://www.bloomberg.com/quote/%s:US\" % ticker_symbol\n\ndef make_historical_url(ticker_symbol):\n return \"https://www.nasdaq.com/symbol/%s/historical\" % ticker_symbol\n\ndef Calculation():\n lower_stock = Ticker_entry.get()\n stock = lower_stock.upper()\n url = make_url(stock)\n page = requests.get(url) #requesting the HTML code of the website\n soup = BeautifulSoup(page.content, \"lxml\") #Converting the HTML code of the website into a beautifulsoup object\n\n #Finding and inserting the current price\n current_number = soup.find('span', attrs={'class':'priceText__1853e8a5'})\n current_price = current_number.text\n Stock_price_output.insert(0, \"$\")\n Stock_price_output.insert(1, current_price)\n\n #Finding and inserting opening price\n opening_number = soup.find('div', attrs={'class':'value__b93f12ea'})\n opening_price = opening_number.text\n Stock_price_day_output.insert(0, \"$\")\n Stock_price_day_output.insert(1, opening_price)\n\n #Finding and inserting last closing price\n closing_numbers = soup.find_all('div', attrs={'class':'value__b93f12ea'})\n closing_number = closing_numbers[1]\n closing_price = closing_number.text\n Last_closing_price_output.insert(0, \"$\")\n Last_closing_price_output.insert(1, closing_price)\n\n #Finding and inserting news\n news = soup.find_all('div', attrs={'class':'headline__07dbac92'})\n news_1 = news[1].text\n news_2 = news[2].text\n news_3 = news[3].text\n\n Stock_news_output1.insert(0, news_1)\n Stock_news_output2.insert(0, news_2)\n Stock_news_output3.insert(0, news_3)\n\n #Drawing the graph of the stock\n historical_url = make_historical_url(stock)\n historical_page = requests.get(historical_url)\n soup_2 = BeautifulSoup(historical_page.content, \"lxml\")\n all_numbers = soup_2.find('tbody')\n all_nums = all_numbers.text\n all_nums_1 = all_nums.split()\n length = len(all_nums_1)\n\n prices = []\n dates = []\n\n current_time = datetime.datetime.now()\n current_time_format = current_time.strftime(\"%m/%d/%Y\")\n all_nums_1[0] = current_time_format\n\n for t in range(int(length/6)):\n index = t * 6 + 4\n prices.append(all_nums_1[index])\n\n for t in range(int(length/6)):\n index = t * 6\n date_str = all_nums_1[index]\n format_str = '%m/%d/%Y'\n datetime_object = datetime.datetime.strptime(date_str, format_str)\n dates.append(datetime_object)\n\n final_dates = matplotlib.dates.date2num(dates)\n\n #plotting the graph of the last 3 months of stock price\n plt.plot_date(final_dates, prices, '-o')\n plt.xticks(rotation=90)\n plt.xlabel('Date')\n plt.ylabel('Price ($)')\n plt.suptitle(\"Price of the %s stock in the last 3 months\" % stock)\n plt.show()\n\ndef Cleaning(writing_area1, writing_area2, writing_area3, writing_area4, writing_area5, writing_area6, writing_area7):\n writing_area1.delete(0, END)\n writing_area2.delete(0, END)\n writing_area3.delete(0, END)\n writing_area4.delete(0, END)\n writing_area5.delete(0, END)\n writing_area6.delete(0, END)\n writing_area7.delete(0, END)\n\nroot.mainloop()\n\nThanks!\n\nA:\n\nI initially suggested monitoring HTTP status code, however this is a non-starter as Bloomberg will automatically redirect you to a simple page to state that a ticker is invalid. However, this page has a standardised message: \nThe search for XYZ:US produced no matches. Try the symbol search.\nThus, searching for a portion of that string will do the trick, don't even need to specifiy the exact ticker value: \nimport requests, lxml\nfrom bs4 import BeautifulSoup\n\nr = requests.get('https://www.bloomberg.com/quote/XYZ:US')\nsoup = BeautifulSoup(r.content, \"lxml\")\n\nf = soup.find_all(\"div\", \"premium__message\")\n\nif 'produced no matches' in str(f):\n # do something\n\n"} +{"text": "Q:\n\nPHP code for inserting non-duplicate values into MySQL\n\nI have basic PHP/MySQL experience, having taken an introductory class. My knowledge is literally limited to the following PHP codes:\nif(!($stmt = $mysqli->prepare...)\nif(!($stmt->bind_param...)\nif(!$stmt->execute...)\n\nI'm currently trying to write a program that allows a user to enter a new password, and checks the password against existing passwords in the database.\nHere is what I have:\n\n\nI got the code from this post: Check for duplicates before inserting\nI'm not sure if the code itself has problems or if I need to add anything else to my PHP code to get this working, as it's currently producing an \"Error 500\".\n\nA:\n\nI decided to go an entirely different route, which is to set the Password column as unique.\nThen I did a simple INSERT that would prompt an error if the user attempts to add a duplicate:\nprepare(\"INSERT INTO Heroes(HeroName, FirstName, LastName, Age, HomeCountry, RoleID) VALUES (?,?,?,?,?,?)\"))){\n echo \"Prepare failed: \" . $stmt->errno . \" \" . $stmt->error;\n }\n if(!($stmt->bind_param(\"sssisi\",$_POST['HeroName'],$_POST['FirstName'],$_POST['LastName'],$_POST['Age'],$_POST['HomeCountry'],$_POST['RoleID']))){\n echo \"Bind failed: \" . $stmt->errno . \" \" . $stmt->error;\n }\n if(!$stmt->execute()){\n echo \"Execute failed: \" . $stmt->errno . \" \" . $stmt->error;\n } else {\n echo \"Added \" . $stmt->affected_rows . \" row to Heroes.\";\n }\n?>\n\n"} +{"text": "Q:\n\ncreate array by conditions\n\nI want to insert numbers to an array by the next following:\n\nthe number should be between 1-5\nthe first number can't be 1, the second can't be 2, etc..\nchosen number can't be inserted to another index\n\nfor example:\n[1,2,3,4,5]\nI randomize the first number: 1 [condition 2 doesn't exists: 1 can't be in the first index, so I randomize again and got 4).\nso new array:\n0 - 4\n1 - \n2 - \n3 - \n4 - \n\nI randomize a number to the second cell and got 4, but 4 was inserted to the first element [condition 3], so I randomize again and got 2, but 2 can't be the second element [condition 2], so I randomize again and got 5.\n0 - 4\n1 - 5\n2 - \n3 - \n4 - \n\netc\nI tried to init a vec by the numbers (1-5):\nvar array = new Array();\n\narray[0] = 1;\narray[1] = 2;\narray[2] = 3;\narray[3] = 4;\narray[4] = 5;\n\nvar newarr = new Array();\n\nfunction getRandomInt (min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\n$(document).ready(function() {\n for (var i = 0; i < 5; i++) {\n var rand;\n // check condition 2\n while((rand = getRandomInt(1, 5)) == (i+1)); \n newarr[i] = rand;\n //array.splice(i, 1);\n }\n\n // print the new array\n for (var i = 0; i < 5; i++) {\n alert((i+1) + '->' + newarr[i]); \n }\n});\n\nbut I need to add condition 3 to my code,\nany help appreciated!\n\nA:\n\nTry this:\n$(document).ready(function() {\n for (var i = 0; i < 5; i++) {\n var rand;\n // check condition 2\n while((rand = getRandomInt(1, 5)) == (i+1) || $.inArray(rand, newarr)) // Also check, if generated number is already in the array\n newarr[i] = rand;\n //array.splice(i, 1);\n }\n\n // print the new array\n for (var i = 0; i < 5; i++) {\n alert((i+1) + '->' + newarr[i]); \n }\n});\n\nBut beware. If you generate for example this array: \n[2, 1, 4, 3]\n\nYou will end up having an endless while loop, since the only available number is 5, but it can't be inserted in that position. \n\n"} +{"text": "Q:\n\nc++ overloading function including bool and integer arguments\n\na simple and I guess easy to answer question (if I did not already got it myself). The following overloaded functions:\nvoid BR(const bool set) { backwardReaction_[nReac_] = set; }\nbool BR(const int reactionNumber) const { return backwardReaction_[reactionNumber]; }\n\nThe first function is a setter and the second a getter function. backwardReaction_ is of type std::vector. The problem occurs whenever I want to call the second function. Here I get a compiler error overload function BR(xy) ambigious.\nint main()\n.\n.\nconst int i = 3;\nbool a = chem.BR(i);\n\nThe compiler error is equal to:\nchemistryTestProg.cpp: In function \u2018int main()\u2019:\nchemistryTestProg.cpp:74:34: error: call of overloaded \u2018BR(const int&)\u2019 is ambiguous\n const bool a = chem.BR(i);\n ^\nIn file included from ../../src/gcc/lnInclude/chemistryCalc.hpp:38:0,\n from ../../src/gcc/lnInclude/chemistry.hpp:38,\n from chemistryTestProg.cpp:35:\n../../src/gcc/lnInclude/chemistryData.hpp:266:18: note: candidate: void AFC::ChemistryData::BR(bool)\n void BR(const bool);\n ^~\n../../src/gcc/lnInclude/chemistryData.hpp:322:22: note: candidate: bool AFC::ChemistryData::BR(int) const\n bool BR(const int) const;\n ^~\n\nI guess that I get the problem because of the types bool and int which are identically (true => int(1), false => int(0). As I am changing the getter name to, e.g., bool getBR(const int reactionNumber) {...} everything works fine. So I guess the problem is about the similarities of the bool and int treatment within c++. I also tried a variety of different calls such as:\nconst bool a = chem.BR(4)\nconst bool a = chem.BR(int(5))\nconst bool a = chem.BR(static_cast(2))\nbool a = chem.BR(...)\n\nThus, I think it is really related to the bool andint overloading arguments. Nevertheless, I made a quick search and did not find too much about these two overload types and resulting problems. Tobi\n\nA:\n\nThis is because you declared BR(int), but not BR(bool), to be const. Then when you call BR(int) on a non-const object, the compiler has two conflicting matching rules: parameter matching favours BR(int), but const-ness matching favours BR(bool).\n\n"} +{"text": "Q:\n\nDatepart logic for custom sql agent job schedule\n\nWanted help in code for below logic.\n\nJob A needs to be run on 8th of month.\nJob B needs to be run on Tuesday only.\nJob c needs to be run on Daily(Minus Tuesday & Sunday).\nAnd If Its Tuesday and 8Th Job A takes the precedence of Job.\n\ni have coded logic for half of it.\nElse If Begin logic,\n--Tuesday Logic(0=Monday,1=Tuesday,2=Wed,3=Thu,4=Friday,5=Saturday,6=Sunday)\nIF (SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE())/7*7,0) + 1)=1 -- If it is tuesday execute the Weekly+Daily Job\n Print 'executing weekly and daily tables'\n\nELSE\nBEGIN\n Print 'executing daily job'\nEND\nEND\n\nA:\n\nHere is my logic:\nBEGIN\n--FULL REFRESH Cycle\ndeclare @EightDayofMonth datetime =(DATEADD(DAY, 8-DAY(GETDATE()), CONVERT(date, GETDATE())));\ndeclare @actuladayofmonth datetime = CONVERT(date, getdate());\n\n----checking for 8th day --condition 1 ( 8th of month and NOT Tuesday and not sunday) if any other day job executes\nIF (@actuladayofmonth=@EightDayofMonth) AND (DATEPART(WEEKDAY,GETDATE())<>3 OR DATEPART(WEEKDAY,GETDATE())<>1)\n\nBEGIN\nPrint 'disabe daily job'\nprint 'executing full job'\n END\n\n--checking for monthly 8th is tuesday logic\nELSE IF (@actuladayofmonth=@EightDayofMonth) AND DATEPART(WEEKDAY,GETDATE())=3\nBEGIN\n\nPrint 'Disable Tuesday Weekly'\nprint 'Disable Daily on tuesday'\nPrint 'Executing full job'\n END\n\nELSE IF (@actuladayofmonth=@EightDayofMonth) AND DATEPART(WEEKDAY,GETDATE())=1\nBEGIN\nPrint 'Execute disable sunday'\n END\n END\n\n"} +{"text": "Q:\n\nHow to add array to JSON object in javascript?\n\nI am trying to create a json string that has an array element:\n\nvar arrays = [0,1,2];\nvar obj = new Object();\nobj.data = arrays;\nconsole.log(JSON.stringify(obj));\n\nI get this result: \n{\"data\":{\"0\":0,\"1\":1,\"2\":2}}\n\nI want this JSON string: \n{\"data\": [0,1,2,3,4,5,6,7], \"name\":\"number\"}\n\nHow can I add an array element to a JSON Object?\n\nA:\n\nYou can just use JSON.stringify like so:\n\nvar myObj = {\"data\": [0,1,2,3,4,5,6,7], \"name\":\"number\"};\nvar myJSON = JSON.stringify(myObj);\n\nconsole.log(myJSON);\n\nAnd you can convert it back using JSON.parse:\n\nvar myObj = {\"data\": [0,1,2,3,4,5,6,7], \"name\":\"number\"};\nvar myJSON = JSON.stringify(myObj);\n\nconsole.log(JSON.parse(myJSON));\n\n"} +{"text": "Q:\n\nWhere is the svnbook for latest Subversion (1.9.4)?\n\nThe official svnbook site contains online versions of the book for 1.7 and for the \"nightly build\" 1.8. Not sure how 1.8 counts as nightly when 1.9.4 exists, but whatever :)\nWhere can I find an online version of the svnbook for the latest Subversion (1.9.4)?\n\nA:\n\nUse SVNBook 1.8 for now, it's mostly ready. SVNBook 1.9 hasn't been started yet and there are not so much differences between 1.8 and 1.9.\n\n"} +{"text": "Q:\n\nUsing the stix font for \\mathcal and \\mathscr only\n\nHow do I limit the stix font package to only affect certain symbols? In my case I want to only change the font associated to \\mathcal{} and \\mathscr{}.\n\nA:\n\nOne has to go to stix.sty and extract the relevant information:\n\\documentclass{article}\n\\usepackage{amsmath}\n\n\\makeatletter\n\\DeclareFontEncoding{LS1}{}{}\n\\DeclareFontEncoding{LS2}{}{\\noaccents@}\n\\DeclareFontSubstitution{LS1}{stix}{m}{n}\n\\DeclareFontSubstitution{LS2}{stix}{m}{n}\n\\makeatother\n\n\\DeclareMathAlphabet\\mathscr{LS1}{stixscr}{m}{n}\n\\SetMathAlphabet\\mathscr{bold}{LS1}{stixscr}{b}{n}\n\\DeclareMathAlphabet\\mathcal{LS2}{stixcal}{m}{n}\n\\SetMathAlphabet\\mathcal{bold}{LS2}{stixcal}{b}{n}\n\n\\begin{document}\n\nThis is \\verb|\\mathscr|: $\\mathscr{A}\\mathscr{B}$\n\nThis is \\verb|\\mathcal|: $\\mathcal{A}\\mathcal{B}$\n\n\\boldmath\n\nThis is \\verb|\\mathscr|: $\\mathscr{A}\\mathscr{B}$\n\nThis is \\verb|\\mathcal|: $\\mathcal{A}\\mathcal{B}$\n\n\\end{document}\n\nOutput of pdffonts:\nname type emb sub uni object ID\n------------------------------------ ----------------- --- --- --- ---------\nHHWGLO+CMR10 Type 1 yes yes no 4 0\nDTZOCG+CMTT10 Type 1 yes yes no 5 0\nLUIFQC+STIXMathScript-Regular Type 1 yes yes no 6 0\nOBDLAV+STIXMathCalligraphy-Regular Type 1 yes yes no 7 0\nGYLRUW+STIXMathScript-Bold Type 1 yes yes no 8 0\nUVZWHB+STIXMathCalligraphy-Bold Type 1 yes yes no 9 0\n\nFor comparison\n\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{mathrsfs}\n\n\\begin{document}\n\nThis is \\verb|\\mathscr|: $\\mathscr{A}\\mathscr{B}$\n\nThis is \\verb|\\mathcal|: $\\mathcal{A}\\mathcal{B}$\n\n\\boldmath\n\nThis is \\verb|\\mathscr|: $\\mathscr{A}\\mathscr{B}$\n\nThis is \\verb|\\mathcal|: $\\mathcal{A}\\mathcal{B}$\n\n\\end{document}\n\n"} +{"text": "Q:\n\nHow can I get the hostname, aliases, ip address, and canonical name of a device (without asking a library to read /etc/hosts) using python?\n\nI want to get these fields about a device given an identifier:\nhostname, aliases, ip address, & canonical name\nI can get these by using socket:\nsocket.gethostbyaddr('machine-name')\n\nHowever, every socket call opens the hosts file (/etc/hosts) and reads it in. I want to skip this step. \nEither I want socket to only open the hosts file once (and save the data), or I want socket to skip looking in the hosts file and do a DNS lookup (and I will read the hosts file myself).\nI tried to do this with dnspython's resolver, but I can't figure out how to parse the returned result for my wanted fields.\n\nA:\n\nI ended up achieving this with pycares. It allowed me to resolve 100,000+ dns queries in under 18 seconds. \nFor the hosts file, I parsed it myself. \n\n"} +{"text": "Q:\n\nIs there any way to check which baud rates are supported on a serial device?\n\nIs there any way to check which baud rates are supported for a serial device on Linux? \nI've poked around the /sys/class/tty/ttyS0 directory, but I can't see anything in there that lists this type of information.\n\nA:\n\nLittle bash script:\nFrom sawdust's answer, there is my solution:\nfor bauds in $(\n sed -r 's/^#define\\s+B([1-9][0-9]+)\\s+.*/\\1/p;d' < \\\n /usr/include/asm-generic/termbits.h ) ;do\n echo $bauds\n stty -F /dev/ttyS0 $bauds && echo Ok.\ndone 2>&1 |\n pr -at2\n\nWill render on my host:\n50 Ok.\n75 Ok.\n110 Ok.\n134 Ok.\n150 Ok.\n200 Ok.\n300 Ok.\n600 Ok.\n1200 Ok.\n1800 Ok.\n2400 Ok.\n4800 Ok.\n9600 Ok.\n19200 Ok.\n38400 Ok.\n57600 Ok.\n115200 Ok.\n230400 Ok.\n460800 Ok.\n500000 Ok.\n576000 Ok.\n921600 Ok.\n1000000 Ok.\n1152000 Ok.\n1500000 Ok.\n2000000 stty: /dev/ttyS0: unable to perform\n2500000 stty: /dev/ttyS0: unable to perform\n3000000 stty: /dev/ttyS0: unable to perform\n3500000 stty: /dev/ttyS0: unable to perform\n4000000 stty: /dev/ttyS0: unable to perform\n\nThat is, but this won't mean it will work!\nYou have to test them with your cable and your device...\n\nA:\n\nYou can check the device baud rate using the \"stty\" command on the console:\n$ stty < /dev/tty.. (where tty... is the device file you are listening) \n\noutput: \nspeed 9600 baud; line = 0;\n-brkint -imaxbel\n\nYou can also change the baud rate with the following command: \n$ sudo stty -F /dev/tty... 9600 (or whatever baud rate number)\n\nA:\n\nYou seem to be asking two different questions.\n\nIs there any way to check which baud rates are supported on a serial device?\n\nThe answer would depend on (1) the capabilities of the hardware, i.e. the UART/USART/SCC, and the range of divisors that the device driver can use in the baud rate generator; consult the device data sheet; (2) the frequency of the clock/oscillator connected to the serial port device; consult the board documentation.\n\nIs there any way to check which baud rates are supported on Linux?\n\nThe one of the defined baud rates in include/asm-generic/termbits.h for the c_cflag member of the terminal control structure is the typical method that the serial port (i.e. UART/USART) device driver receives for the baud rate configuration value.\n#define B0 0000000 /* hang up */\n#define B50 0000001\n#define B75 0000002\n#define B110 0000003\n#define B134 0000004\n#define B150 0000005\n#define B200 0000006\n#define B300 0000007\n#define B600 0000010\n#define B1200 0000011\n#define B1800 0000012\n#define B2400 0000013\n#define B4800 0000014\n#define B9600 0000015\n#define B19200 0000016\n#define B38400 0000017\n\n#define BOTHER 0010000\n#define B57600 0010001\n#define B115200 0010002\n#define B230400 0010003\n#define B460800 0010004\n#define B500000 0010005\n#define B576000 0010006\n#define B921600 0010007\n#define B1000000 0010010\n#define B1152000 0010011\n#define B1500000 0010012\n#define B2000000 0010013\n#define B2500000 0010014\n#define B3000000 0010015\n#define B3500000 0010016\n#define B4000000 0010017\n\nSerial port drivers typically do not have any means of reporting/advertising which of these baud rates are actually supported/configurable/implemented. There is a capabilities value for attributes like FIFO and sleeping but not for baud rates. A driver could define an ioctl() call to configure (nonstandard) baud rates, although that would make programs using it non-portable. \n\n"} +{"text": "Q:\n\n403 Forbidden in codeigniter\n\nThis is my jquery:\n\n\nWhile doing npm run dev or compiling the asset file I'm getting and error:\n\nCannot use v-for on stateful component root element because it renders multiple elements.\n\nI don't know where I'm doing mistake, help me out in this.\nThanks\n\nA:\n\nWhen creating a component there needs to be 1 root element, try wrapping your code in a
tag. It should solve the issue;\ni.e.\n
\n
\n // Your code...\n
\n
\n\nA:\n\nBecause vue2.0 use latest grammar is to do\u3002\nfor example:\n\n\n"} +{"text": "Q:\n\nVimdiff: displaying the total number of changes\n\nWhen diffing two files in (g)vim, is it possible to display the total number of changes? I suppose this is equivalent to counting the number of folds, but I don't know how to do that either.\nIdeally I would like a message which says something like \"Change 1 of 12\" which would update as I cycled through the changes with ]c.\nI am having great success converting some members of my office to the wonders of Vim, but Vimdiff is a consistent bugbear.\n\nA:\n\nHere is a slightly more refined solution. It uses the same technique as my previous answer to count the diffs, but it stores the first line of each hunk in a list asigned to a global variable g:diff_hunks. Then the number of hunks below the cursor can be found by finding the position of the line number in the list. Also notice that I set nocursorbind and noscrollbind and reset them at the end to ensure we don't break mouse scrolling in the diff windows.\nfunction! UpdateDiffHunks()\n setlocal nocursorbind\n setlocal noscrollbind\n let winview = winsaveview() \n let pos = getpos(\".\")\n sil exe 'normal! gg'\n let moved = 1\n let hunks = []\n while moved\n let startl = line(\".\")\n keepjumps sil exe 'normal! ]c'\n let moved = line(\".\") - startl\n if moved\n call add(hunks,line(\".\"))\n endif\n endwhile\n call winrestview(winview)\n call setpos(\".\",pos)\n setlocal cursorbind\n setlocal scrollbind\n let g:diff_hunks = hunks\nendfunction\n\nThe function UpdateDiffHunks() should be updated whenever a diff buffer is modified, but I find it sufficient to map it to CursorMoved and BufEnter. \nfunction! DiffCount()\n if !exists(\"g:diff_hunks\") \n call UpdateDiffHunks()\n endif\n let n_hunks = 0\n let curline = line(\".\")\n for hunkline in g:diff_hunks\n if curline < hunkline\n break\n endif\n let n_hunks += 1\n endfor\n return n_hunks . '/' . len(g:diff_hunks)\nendfunction\n\nThe output of DiffCount() can be used in the statusline, or tied to a command.\n\n"} +{"text": "Q:\n\nCannot make static reference to the non-static type t\n\nI am trying to create a static method that returns a Generic Object of the same class which the static method is a member of but there is compilation error on the return type as \n\nCannot make a static reference to the non-static type T\n\nLooking at other solutions on stack overflow I found this \n(Generics)Cannot make a static reference to the non-static type T\nwhere a responder has provided an answer which says that for static methods, we must also include the target type before the return type but even this does not work\npublic class Condition {\n\nprivate boolean isInitialized=false;\nprivate ConditionType type;\nprivate NodeType nodeType;\nprivate String propertyName;\nprivate Predicate onlyIfTest;\nprivate Predicate predicates;\n\nprivate Condition() {\n\n}\n\n//Here at the return type i get the error Cannot make static...\npublic static Condition include(NodeType type,String propertyName) {\n Condition condition = new Condition(); //and an error here too\n condition.type = ConditionType.INCLUDE;\n condition.nodeType = type;\n condition.propertyName = propertyName;\n condition.isInitialized =true;\n return condition;\n}\n\nThe error that i get is Cannot make a static reference to the non-static type T. How can i make it work with a static method.\n\nA:\n\nYou've already had your answer:\n\nwe must also include the target type before the return type\n\nbut didn't apply it.\npublic static Condition include(NodeType type, String propertyName)\n\n"} +{"text": "Q:\n\nIs it permited to download javascript code to iPhone\n\nI have an hybrid application, it's basically a website running from the application folder inside a UIWebview.\nThe problem is that I was planning to update my website by downloading the whole website from internet and then replacing the old website.\nToday I found that Apple now provides the App Store Review Guidelines and among others there are the following rules:\n\n2.7 Apps that download code in any way or form will be rejected\n2.8 Apps that install or launch other executable code will be rejected\n\nBecause my site has html, css and javascript, does that mean that my app will be rejected or is there any chance to be accepted?\nWhat are your thoughts on that?\n\nA:\n\nFrom the new text of of the application developer agreement, regarding downloading executable code:\n\nThe only exception to the foregoing is scripts and code downloaded and run by Apple's built-in WebKit framework.\n\nThis includes javascript and hybrid applications, so you should be fine.\nAlthough, taking all of this into account, why didn't you just allow your app to take advantage of the iPhone webapp stuff? You still get an icon on the home screen, and get rid of the browser chrome without having to get Apple to approve your app.\n\n"} +{"text": "Q:\n\nAnimating KnockoutJS template changes\n\nI'm using a dynamic template name. So I cant change out the template based on some selected values. What I'd like to do is fade out (or any animation for that mater) the old template elements before rendering the new one. There is this concept if you are iterating over a list but not for the root template itself. Has anyone tried this or got this to work?\n\nA:\n\nYou could write your own binding handler:\nko.bindingHandlers.fadeTemplate = {\n init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n return ko.bindingHandlers['template']['init'](element, valueAccessor, allBindings);\n },\n update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {\n var value = valueAccessor();\n $(element).fadeOut(function() {\n ko.bindingHandlers['template']['update'](element, valueAccessor, allBindings, viewModel, bindingContext);\n $(this).fadeIn();\n });\n }\n};\n\nhttp://jsfiddle.net/xP7uy/\n\n"} +{"text": "Q:\n\nUnknown Directory Shortcut File or Mount | VISTA\n\nI have this weird mount icon after a trojan cleanup days ago for a client. The icon when clicked takes you to the My Computer guid. The file properties are Type: File, Location: C:\\, Size: 6.76. If we try to delete it will not complete. I search registry for a reference and couldn't find. They ran utility for virus removal 'combofix', sdfix, smithfraud, ect. Im gessing this could be related (mount).\nThe icon on the file structure in My Computer shows a device similar icon. When this icon is clicked it goes back to my computer browser.\ni77.photobucket.com/albums/j65/speedcoder/snap.jpg\nHow can I take this guy off?\n\nA:\n\nWhen you need to clean a system infected with malicious code:\n1) Archive the user data\n2) Some some other system, or at least some kind of rescue CD, to scan the data for traces of malicious code.\n3) Clean install the system, including MBR on the disk. For the paranoid, re-flash BIOS code on all components.\n4) Restore the scanned/cleaned user data to the rebuilt system.\nIn my opinion, do not waste time trying to clean a compromised system in place - with today's malicious code, e.g., root kits, this is impossible.\n\n"} +{"text": "Q:\n\nLocating resource in Jar\n\nI am having difficulty creating the image icon. I want to package a jar and have the images available to be displayed in the gui. Both of the following throw null pointer exceptions. The path is a path directly to a package in my Eclipse project that contains the necessary images. \nImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource(\n \"/TicTacToe/src/edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png\")\n .getPath());\n\nand\nImageIcon icon = new ImageIcon(getClass().getResource(\n \"/TicTacToe/src/edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png\"));\n\nI can't see to be able to access the appropriate package. Any suggestions?\n\nA:\n\nImageIcon icon = new ImageIcon(this.getClass().getClassLoader()\n .getResourceAsStream(\"edu/luc/tictactoe/gui/resources/images/TicTacToeOIcon.png\");\n\n"} +{"text": "Q:\n\nlxml install on windows 7 using pip and python 2.7\n\nWhen I try to upgrade lxml using pip on my windows 7 machine I get the log printed below.\nWhen I uninstall and try to install from scratch I get the same errors.\nAny ideas?\n\nDownloading/unpacking lxml from\n https://pypi.python.org/packages/source/l/lxml/l\n xml-3.2.4.tar.gz#md5=cc363499060f615aca1ec8dcc04df331 Downloading\n lxml-3.2.4.tar.gz (3.3MB): 3.3MB downloaded Running setup.py\n egg_info for package lxml\n Building lxml version 3.2.4.\n Building without Cython.\n ERROR: Nazwa 'xslt-config' nie jest rozpoznawana jako polecenie wewn\u0119trzne l ub zewn\u0119trzne,\n program wykonywalny lub plik wsadowy.\n** make sure the development packages of libxml2 and libxslt are installed *\n\n*\nUsing build configuration of libxslt\nD:\\software\\Python27\\lib\\distutils\\dist.py:267: UserWarning: Unknown distrib ution option: 'bugtrack_url'\n warnings.warn(msg)\n\nwarning: no files found matching 'lxml.etree.c' under directory 'src\\lxml'\nwarning: no files found matching 'lxml.objectify.c' under directory 'src\\lxm l'\nwarning: no files found matching 'lxml.etree.h' under directory 'src\\lxml'\nwarning: no files found matching 'lxml.etree_api.h' under directory 'src\\lxm l'\nwarning: no files found matching 'etree_defs.h' under directory 'src\\lxml'\nwarning: no files found matching '*.txt' under directory 'src\\lxml\\tests'\nwarning: no files found matching 'pubkey.asc' under directory 'doc'\nwarning: no files found matching 'tagpython*.png' under directory 'doc'\nwarning: no files found matching 'Makefile' under directory 'doc' Installing collected packages: lxml Found existing installation:\n\nlxml 2.3\n Uninstalling lxml:\n Successfully uninstalled lxml Running setup.py install for lxml\n Building lxml version 3.2.4.\n Building without Cython.\n ERROR: Nazwa 'xslt-config' nie jest rozpoznawana jako polecenie wewn\u0119trzne l ub zewn\u0119trzne,\n program wykonywalny lub plik wsadowy.\n** make sure the development packages of libxml2 and libxslt are installed *\n\n*\nUsing build configuration of libxslt\nbuilding 'lxml.etree' extension\nD:\\software\\Microsoft Visual Studio 9.0\\VC\\BIN\\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG\n\n-Ic:\\users\\x\\appdata\\local\\temp\\pip_build_x\\lxml\\src\\lxml\\inc ludes -ID:\\software\\Python27\\include -ID:\\software\\Python27\\PC\n /Tcsrc\\lxml\\lxml. etree.c\n /Fobuild\\temp.win32-2.7\\Release\\src\\lxml\\lxml.etree.obj\n lxml.etree.c\n c:\\users\\x\\appdata\\local\\temp\\pip_build_x\\lxml\\src\\lxml\\includes\\etree_d\n efs.h(9) : fatal error C1083: Cannot open include file:\n 'libxml/xmlversion.h': N o such file or directory\n D:\\software\\Python27\\lib\\distutils\\dist.py:267: UserWarning: Unknown distrib ution option: 'bugtrack_url'\n warnings.warn(msg)\n error: command '\"D:\\software\\Microsoft Visual Studio 9.0\\VC\\BIN\\cl.exe\"' fai led with exit status 2\n Complete output from command D:\\software\\Python27\\python.exe -c \"import setu\n ptools;file='c:\\users\\x\\appdata\\local\\temp\\pip_build_x\\lxml\\setu\n p.py';exec(compile(open(file).read().replace('\\r\\n', '\\n'),\n file, 'exec' ))\" install --record c:\\users\\x\\appdata\\local\\temp\\pip-pyyuss-record\\install-r ecord.txt\n --single-version-externally-managed:\n Building lxml version 3.2.4.\nBuilding without Cython.\nERROR: Nazwa 'xslt-config' nie jest rozpoznawana jako polecenie\n wewn\u0119trzne lub z ewn\u0119trzne,\nprogram wykonywalny lub plik wsadowy.\n** make sure the development packages of libxml2 and libxslt are installed **\nUsing build configuration of libxslt\nrunning install\nrunning build\nrunning build_py\ncreating build\ncreating build\\lib.win32-2.7\ncreating build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\builder.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\cssselect.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\doctestcompare.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\ElementInclude.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\pyclasslookup.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\sax.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\usedoctest.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml_elementpath.py -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml__init__.py -> build\\lib.win32-2.7\\lxml\ncreating build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes__init__.py ->\n build\\lib.win32-2.7\\lxml\\includes\ncreating build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\builder.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\clean.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\defs.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\diff.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\ElementSoup.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\formfill.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\html5parser.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\soupparser.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html\\usedoctest.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html_diffcommand.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html_html5builder.py ->\n build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html_setmixin.py -> build\\lib.win32-2.7\\lxml\\html\ncopying src\\lxml\\html__init__.py -> build\\lib.win32-2.7\\lxml\\html\ncreating build\\lib.win32-2.7\\lxml\\isoschematron\ncopying src\\lxml\\isoschematron__init__.py ->\n build\\lib.win32-2.7\\lxml\\isoschema tron\ncopying src\\lxml\\lxml.etree.h -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\lxml.etree_api.h -> build\\lib.win32-2.7\\lxml\ncopying src\\lxml\\includes\\c14n.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\config.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\dtdvalid.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\etreepublic.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\htmlparser.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\relaxng.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\schematron.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\tree.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\uri.pxd -> build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\xinclude.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\xmlerror.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\xmlparser.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\xmlschema.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\xpath.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\xslt.pxd ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\etree_defs.h ->\n build\\lib.win32-2.7\\lxml\\includes\ncopying src\\lxml\\includes\\lxml-version.h ->\n build\\lib.win32-2.7\\lxml\\includes\ncreating build\\lib.win32-2.7\\lxml\\isoschematron\\resources\ncreating build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\rng\ncopying src\\lxml\\isoschematron\\resources\\rng\\iso-schematron.rng ->\n build\\lib.win 32-2.7\\lxml\\isoschematron\\resources\\rng\ncreating build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\ncopying src\\lxml\\isoschematron\\resources\\xsl\\RNG2Schtrn.xsl ->\n build\\lib.win32-2 .7\\lxml\\isoschematron\\resources\\xsl\ncopying src\\lxml\\isoschematron\\resources\\xsl\\XSD2Schtrn.xsl ->\n build\\lib.win32-2 .7\\lxml\\isoschematron\\resources\\xsl\ncreating\n build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xsl\n t1\ncopying\n src\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xslt1\\iso_abstract_e\n xpand.xsl ->\n build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\\iso-schematron\n -xslt1\ncopying\n src\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xslt1\\iso_dsdl_inclu\n de.xsl ->\n build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xs\n lt1\ncopying\n src\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xslt1\\iso_schematron\n _message.xsl -> build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\\iso-schemat\n ron-xslt1\ncopying\n src\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xslt1\\iso_schematron\n _skeleton_for_xslt1.xsl -> build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\\\n iso-schematron-xslt1\ncopying\n src\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xslt1\\iso_svrl_for_x\n slt1.xsl ->\n build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-\n xslt1\ncopying\n src\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xslt1\\readme.txt\n -> build\\lib.win32-2.7\\lxml\\isoschematron\\resources\\xsl\\iso-schematron-xslt1\nrunning build_ext\nbuilding 'lxml.etree' extension\ncreating build\\temp.win32-2.7\ncreating build\\temp.win32-2.7\\Release\ncreating build\\temp.win32-2.7\\Release\\src\ncreating build\\temp.win32-2.7\\Release\\src\\lxml\nD:\\software\\Microsoft Visual Studio 9.0\\VC\\BIN\\cl.exe /c /nologo /Ox\n /MD /W3 /GS\n - /DNDEBUG -Ic:\\users\\x\\appdata\\local\\temp\\pip_build_x\\lxml\\src\\lxml\\include s -ID:\\software\\Python27\\include -ID:\\software\\Python27\\PC\n /Tcsrc\\lxml\\lxml.etre e.c\n /Fobuild\\temp.win32-2.7\\Release\\src\\lxml\\lxml.etree.obj\nlxml.etree.c\nc:\\users\\x\\appdata\\local\\temp\\pip_build_x\\lxml\\src\\lxml\\includes\\etree_defs.\n h(9) : fatal error C1083: Cannot open include file:\n 'libxml/xmlversion.h': No su ch file or directory\nD:\\software\\Python27\\lib\\distutils\\dist.py:267: UserWarning: Unknown\n distributio n option: 'bugtrack_url'\nwarnings.warn(msg)\nerror: command '\"D:\\software\\Microsoft Visual Studio\n 9.0\\VC\\BIN\\cl.exe\"' failed with exit status 2\n---------------------------------------- Rolling back uninstall of lxml Cleaning up... Command D:\\software\\Python27\\python.exe -c \"import\n setuptools;file='c:\\user\n s\\x\\appdata\\local\\temp\\pip_build_x\\lxml\\setup.py';exec(compile(open(_\n file_).read().replace('\\r\\n', '\\n'), file, 'exec'))\" install --record c:\\u sers\\x\\appdata\\local\\temp\\pip-pyyuss-record\\install-record.txt\n --single-versio n-externally-managed failed with error code 1 in c:\\users\\x\\appdata\\local\\temp \\pip_build_x\\lxml Traceback (most\n recent call last): File\n \"D:\\software\\Python27\\Scripts\\pip-script.py\", line 9, in \n load_entry_point('pip==1.4.1', 'console_scripts', 'pip')() File \"D:\\software\\Python27\\lib\\site-packages\\pip__init__.py\", line 148, in\n ma in\n return command.main(args[1:], options) File \"D:\\software\\Python27\\lib\\site-packages\\pip\\basecommand.py\", line 169,\n in main\n text = '\\n'.join(complete_log) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa9 in position 72: ordinal not in range(128)\n\nA:\n\nIf you have a compiler installed (tested with VS C++ 2008 Express), you can simply run:\nset STATICBUILD=true && pip install lxml\n\nAs pointed out on documentation, setting STATICBUILD will tell to lxml's installer to automatically download all its binary dependencies before build.\nThese lxml binary dependencies, that should be present when installing from source, will be downloaded and build together by the installer:\n\nlibxslt\niconv\nzlib\nlibxml2\n\nBonus: It also works inside a virtualenv.\n\nA:\n\nThis question is older but still pops up in google. I tried the other answers to this question and they did not work for one reason or another and I did't want to track down and install all the dependencies to compile on Windows.\nI noticed on pypi some of the lxml releases offer windows wheels and others do not.\nSo the simplest solution for me was to specify a version that did... i.e. pip install lxml==3.6.0 since 3.6.0 offered a wheel while the newer 3.6.4 did not\n\nA:\n\nFor your problem, there is a single line solution. Somehow, this is working means suppose you are doing scraping at low level then this will work.\nAfter 8 hours of research, I found this as working nothing else \npip install lxml==3.6.0\n\nNothing else is required.\nAll things above are applicable for Windows.\nComment if some other type of problem is persisting happy to help.\nHere is my success after 8 hours:\n\n"} +{"text": "Q:\n\nHow to get the child of child using Python's ElementTree\n\nI'm building a Python file that communicates with a PLC. When compiling, the PLC creates a XML file that delivers important information about the program. The XML looks more less like this:\n\n \n my_visu\n english\n \n 2\n 45.6\n \"hello\"\n \n\n\nThe important part is found under child \"vars\". Using Python I want to make a file that when sending argument \"input2\" it will print \"45.6\".\nSo far I can read all children of \"visu\", but don't know how to actually tell Python to search among \"the child of child\". Here's is what I got so far:\ntree = ET.parse(\"file.xml\")\nroot = tree.getroot()\nfor child in root:\n if child.tag == \"vars\":\n .......\n if ( \"childchild\".attrib.get(\"name\") == \"input2\" ):\n print \"childchild\".text\n\nAny ideas how I can complete the script? (or maybe a more efficient way of programming it?)\n\nA:\n\nYou'd be better of using an XPath search here:\nname = 'input2'\nvalue = root.find('.//vars/var[@name=\"{}\"]'.format(name)).text\n\nThis searches for a tag directly below a tag, whose attribute name is equal to the value given by the Python name variable, then retrieves the text value of that tag.\nDemo:\n>>> from xml.etree import ElementTree as ET\n>>> sample = '''\\\n... \n... \n... my_visu\n... english\n... \n... 2\n... 45.6\n... \"hello\"\n... \n... \n... '''\n>>> root = ET.fromstring(sample)\n>>> name = 'input2'\n>>> root.find('.//vars/var[@name=\"{}\"]'.format(name)).text\n'45.6'\n\nYou can do this the hard way and manually loop over all the elements; each element can be looped over directly:\nname = 'input2'\nfor elem in root:\n if elem.tag == 'vars':\n for var in elem:\n if var.attrib.get('name') == name:\n print var.text\n\nbut using element.find() or element.find_all() is probably going to be easier and more concise.\n\n"} +{"text": "Q:\n\nFind x when the function equals 0\n\nI must solve for x for this function. \n$e^x-20x=0$\nI'm not sure what to do here. I've tried this so far but it makes no sense:\n$$\\begin{align*}\ne^x&=20x\\\\\nx\\ln e&=\\ln20+\\ln x\\\\\n\\frac{x}{\\ln20}&=\\ln x\n\\end{align*}$$\nI tried this as well but I'm not sure if this is right either:\n$$\\begin{align*}\ne^x&=20x\\\\\n\\ln e^x&=\\ln20x\\\\\nx&=\\ln20+\\ln x\n\\end{align*}$$\nI've got more confidence in the second try, although I don't know how to solve for an actual number. \nThe answer is a decimal. \n\nA:\n\nThis equation cannot be solved in terms of elementary functions. You can either use numeric methods like Newton's, or solve in terms of Lambert W function:\n\\begin{align*}\ne^x - 20x &= 0 \\\\\n20x &= e^x \\\\\nxe^{-x} &= \\frac{1}{20} \\\\\n-x e^{-x} &= -\\frac{1}{20} \\\\\n-x &= W\\left(-\\frac{1}{20}\\right) \\\\\nx &= -W\\left(-\\frac{1}{20}\\right)\n\\end{align*}\n\n"} +{"text": "Q:\n\nPDO bind parameters\n\nI'm building simple query builder, and I have two questions:\n\nIs it possible to secure mysql queries with normal functions to the similar level as it is done using ->execute(array(':param:' => ... ?\nIs it possible to use many variables in one query, give them the same names (the ones after the semicolon), and then bind them one by one?\n\nA:\n\nIf I understand you correctly, you would like to know if it possible to replicate the functionality of bindParam with the standard mysql_* functions?\nShort answer is no. Please do not use the mysql functions at all, use mysqli or PDO as these provide you with the true security when it comes to prepared statements. They can also provide much better query performance as the SQL is able to be pre-optimised for the database.\n\nYou will have to define each parameter separately (even if it is the same value). You could also pass a simple array to the execute() method call, but you do not then have the option to explicitly define the parameter types.\n\nWithin your function use some thing like this:\n$name = \"fred\";\n$statement = $pdo->prepare(\"SELECT id FROM contacts WHERE first_name = ? OR last_name = ?\");\nfor ($x = 1; $x <= 2; $x++) {\n $statement->bindParam($x, $name, PDO::PARAM_STR);\n}\n$statement->execute();\n\n"} +{"text": "Q:\n\nWhy I'm getting Invalid arguments for the function when using double-quotes?\n\nI'm trying to insert a filename into text as below:\n:put=expand(\"%\")\n\nbut I've the following errors:\n\nE116: Invalid arguments for function expand(\n E15: Invalid expression: expand(\n\nWhy this doesn't work?\nWhat's most surprising thing is that it works when using single-quote instead, e.g.:\n:put=expand('%')\n\nSo I'm trying to understand:\n\nIs there any differences between using double-quotes or single-quotes? If so, what kind?\n\nI'm using Vim v7.4.\n\nA:\n\nFrom :help :put:\n\nThe register can also be = followed by an optional expression. The expression continues until the end of the command. You need to escape the | and \" characters to prevent them from terminating the command.\n\nFor the difference between \" and ' in the context of an expression, see :help expr-quote and :help expr-'.\n\n"} +{"text": "Q:\n\nIntroducing Brevity Into C# / Java\n\nBackground\nCurrently, if I want to create a new object in C# or Java, I type something similar to the following:\n\nList listOfInts = new List(); //C#\nArrayList data = new ArrayList(); //Java\n\nC# 3.0 sought to improve conciseness by implementing the following compiler trick:\n\nvar listofInts = new List();\n\nQuestion\nSince the compiler already knows that I want to create a new object of a certain type (By the fact that I'm instantiating it without assigning it a null reference or assigning a specific method to instantiate it), then why can't I do the following?\n //default constructors with no parameters:\n List listOfInts = new(); //c#\n ArrayList data = new(); //Java\n\nFollow Up Questions:\n\nWhat are possible pitfalls of this approach. What edge cases could I be missing?\nWould there be other ways to shorten instantiation (without using VB6-esque var) and still retain meaning?\n\nNOTE: One of the main benefits I see in a feature like this is clarity. Let say var wasn't limited. To me it is useless, its going to get the assignment from the right, so why bother? New() to me actually shortens it an gives meaning. Its a new() whatever you declared, which to me would be clear and concise.\n\nA:\n\nC# saves in the other end:\nvar listOfInts = new List();\n\nA:\n\nWhat edge cases could I be missing?\n\nI briefly discussed this possible C# syntax on my blog in January. See the comments to that post for some reader feedback on the pros and cons of the syntax.\n\nWould there be other ways to shorten instantiation (without using VB6-esque var) and still retain meaning? \n\nPossibly, yes.\n\"var\" in C#, however, is nothing like \"variant\" in VB6. \"var\" does not mean the same thing as \"object\", nor does it introduce dynamic typing or duck typing. It is simply a syntactic sugar for eliminating the redundant stating of the type of the right hand side.\n\nA:\n\nIn C# 3 there's already the mirror image for local variables, implicitly typing:\nvar listOfInts = new List();\n\nThis doesn't work for non-local variables though.\nIn Java, type inference takes into the assignment target into account, so using static imports and cunning libraries such as the Google Java Collections you can write code such as:\nList integers = newArrayList();\n\nNote that that keeps the variable interface-based while specifying the implementation in the construction side, which is nice.\n\n"} +{"text": "Q:\n\nFixing Macbook Pro keyboard key\n\nThe e key on my keyboard started to feel weird. After some attempts to clean it, I\u2019ve decided to remove it and noticed the membrane is the middle was loose. I\u2019ve only noticed this is atypical because the instructions I found on removing keys mentioned it should be held in place.\n\nAfter cleaning the key, it\u2019s (considerably) better but not perfect, and I wonder if the loose membrane is to blame. Is there a safe way to fix it?\nBy \u201csafe\u201d I mean a method that is unlikely to break it. The key isn\u2019t perfect but it is usable, so I won\u2019t follow a method that risks breaking it, as I wouldn\u2019t have the money to send it in for repairs.\nThis is an older retina Macbook Pro (late 2015 15-inch) with the scissors (not butterfly) switches.\n\nA:\n\nThere's a good chance the loose membrane is to blame and affixing it in place would solve the issue. Before continuing, you can verify if the membrane is the issue or it's something else by powering the laptop on with the key and membrane removed, opening some kind of document on the computer, then using a toothpick or other small (non-sharp) object to push down the center location. If that regularly causes an e character (or whatever key is at issue) to be input in to the document, the keyboard electronics are in good shape.\nWith that done, try holding the membrane down (by its edges) in place over the switch location, while using your fingertip to depress the membrane in the center. You should see e characters being emitted as before. This is the location you want to affix the membrane.\nAdditionally, double-check that the scissor-spring part of the key is in good shape. Grit or broken plastic in that part would also explain the key feeling off, so verify that it's in good shape before proceeding. (If it's not obvious, remove a working, known-good key and compare them.)\nPutting the Membrane in Place\nYou might not love this suggestion because of its permanence, but I think your best bet is using cyanoacrylate (super glue). I can't absolutely guarantee it won't harm the membrane, but I think it's very unlikely.\n\nPower off the laptop.\nClean the area that you'll affix the membrane to: isopropyl (rubbing) alcohol or acetone on a Q-tip should do the trick. You likely also want to clean the rubber membrane.\nRun a small bead of cyanoacrylate around the outer edge of the membrane.\nCarefully place the membrane in the centered location you found above when testing the keyboard. Gently hold in place for a minute or so until the super glue has set.\nWait for it to fully cure. Overnight should be enough, a day should be absolutely safe. This might be overkill, but it would really suck to bump it out of alignment by rushing this part. \nPower the laptop on, test it out by gently depressing on center of membrane: it should register keystrokes like before when you tested the keyboard.\nReassemble the key, you're done!\n\nThe upside to the above approach is that it (should) result in a permanent fix. But that also makes it feel risky, because if something goes wrong, it's extremely difficult to undo. A modified approach would be to put the membrane down in place without cyanoacrylate on it, then carefully put a bead around the edge, touching the outer edge of membrane and the metal where you're affixing it. If it turns out things went bad, acetone (nail polish remover) can break down cyanoacrylate, so you could carefully undo the process with some Q-tips and patience. But I think this approach would be less strong and easier to mess up, even if it has the upside of being (semi-)reversible.\nAlso, be careful when you're using the cyanoacrylate that it doesn't drip down off the metal (I think it's metal, not 100% sure, whatever the cross bar the membrane/switch sits on) and into the area below. Keep some acetone and Q-tips handy in case you need to clean up any accidents quickly.\nFinally, I can't guarantee this will work and won't have an impact on the membrane -- I just don't know the exact chemical interaction. But I'm pretty sure you'll be okay and solidly affixing the membrane in place is the best chance of solving the issues you're seeing. But, you know, you follow instructions at your own risk, etc, etc.\nGood luck!\n\n"} +{"text": "Q:\n\nSQL - Adding a blank row\n\nI'm dealing with software that will use the query I'm building to get data from the database. The problem is that the software doesn't have tools to determine the table size, so I need to add a blank row after the last row of data, so the software can recognize the end of the table.\nHere's an example of what the query would give:\n\nAnd here's an example of what I need to get from the query:\n\nI know it would be better to solve it in the application, but in this case I need to change my query. Is it possible?\nEdit: I'm using SQL Server 2014, the database name is Test and the table name is Table2.\n\nA:\n\nUse UNION ALL after your query to add the blank row:\nselect t.* from (\n select FieldA, FieldB\n from Table2\n ..........\n union all\n select null, null \n) t\norder by case when coalesce(t.FieldA, t.FieldB) is null then 1 else 0 end\n\nor:\nselect t.FieldA, t.FieldB from (\n select 0 as isblankrow, FieldA, FieldB\n from Table2\n ..........\n union all\n select 1, null, null \n) t\norder by isblankrow\n\n"} +{"text": "Q:\n\nSmaller operator gives error in javascript code\n\nI have a javascript code in my xhtml file. Here it is:\n\n \n \n\n\nThe problem ist, inside the for loop it gives error for \"<\" operator saying that \"The content of elements must consist of well-formed character data or markup.\". I think it sees \"<\" as an html element i.e. \"body, html etc. but i am not sure. How can i fix this?\nThanks\nEdit: I now tried this but still an error. Is there a syntax error you see?\n\n\nThe error says that:\nmyaccounts.xhtml:5:52 Expected ) but found ;\n for (var i = 0; i < el.length; i++) {\n ^\n\nmyaccounts.xhtml:5:57 Expected ; but found )\n for (var i = 0; i < el.length; i++) {\n ^\n\nA:\n\nTry using CDATA for the XML parser not to read the javascript content, your code would be like this:\n\n \n \n\n\n"} +{"text": "Q:\n\nReplacing selected shapes with symbols in Illustrator\n\nI have these rectangles placed at different places on the file to indicate bus stands. I want to now replace each one of these rectangles with a bus symbol.\nHow do I do that without dragging the symbol to each place, deleting the rectangle, and making sure that the symbol is in the \"bus stand\" sub layer?\nThanks.\n\nA:\n\nThere is a great script that does exactly what you want. \nIt was written by @Loic Aigon, it's called SymbolReplacement and will cost you only a Thank you Email ^^ \n\n"} +{"text": "Q:\n\nUses for volume form on a pseudo-Riemannian manifold\n\nI was thinking about a possible use for the volume form on pseudo-Riemannian manifold. In Riemannian context we can use it to define minimal surfaces. Is there some physical or geometric interpretation in pseudo-Riemannian context?\n\nA:\n\nOne can define the volume functional for a pseudo-Riemannian manifold, and prove that a non-degenerate submanifold is a critical point of the volume functional if and only if its mean curvature vector vanishes, $H = 0$. However, one loses the geometric interpretation from the Riemannian case, namely, that surfaces with $H=0$ locally minimize the volume, with respect to variations keeping the boundary fixed. For example, in Minkowski space $\\Bbb R^n_1$, spacelike hypersurfaces (i.e., hypersurfaces for which the restriction of the standard Lorentzian metric is actually Riemannian) maximize volume.\nThat said, one can study:\n\nWhat happens to non-degenerate submanifolds with $H = 0$, finding conditions for when does it in fact maximize of minimize volume -- see for example Minimal Submanifolds in Pseudo-riemannian Geometry by Henri Anciaux.\nwhen do we obtain some Calabi-Bernstein like results in the pseudo-Riemannian case (there are some results about that in Minkowski space, e.g. here.\nWhat can one say about submanifolds satisfying the closest purely pseudo-Riemannian condition to $H = 0$: just having $H$ be a lightlike vector ($H \\neq 0$ but $g(H,H)=0$). Such submanifolds are called marginally trapped, and can be used to represent surfaces of black holes in some $4d$ spacetime models, in physics (see relativity books, e.g. Hawking & Ellis, etc.).\n\n"} +{"text": "Q:\n\nHow to insert normal text right below a block of text in Windows?\n\nIn programs such as Microsoft Word, Wordpad or even Evernote, it is possible to insert tables, lists or code block. If that block appear on the last line of the document, how to insert a normal text below it?\nHere a document with a table in Microsoft Word, where the table is the last item on the document. If try to place my cursor at the furthermost possible place, I will end right after B. If I press enter, I may just insert a new row but I won't escape the table. \n.------.------.\n| A | B |\n'------'------' \n\nWhat I want to know, is how I can insert normal text right after the table like this: \n.------.------.\n| A | B |\n'------'------' \nNormal text here...\n\nWhat I usually do is:\n1. Select the whole table\n2. Cut\n3. Insert plenty of new lines\n4. Paste my table above empty lines\n5. Click on one empty line below the table\n6. Insert my normal text. \n\nI also encounter this issue with Evernote.\n\nA:\n\nIn Microsoft Word:\nClick somewhere in the last row of the table and press the right arrow on your keyboard until the cursor moves outside the table:\n \nNow, instead of pressing Enter, hold the Shift key and press Enter. This will create a line break below the table instead of a new table row.\n\n"} +{"text": "Q:\n\nUnemployed person applying for UK visa\n\nI live with my mom here in the Philippines. She owns a sari sari store and shes a pensioner. She pays me monthly. And I don't have a bank account as a proof of my financial status.My sister and her husband want me to visit them in the UK since she's going to have a baby and she really needs someone to be with her since my brother in law is working. My brother in law would like to sponsor my trip. What documents will I comply since I don't have a proof of employment? \nAnd what to do to prove that I'm going to the Philippines after my visit for 6 months in the UK. Surely, I have to return home since my 74 mom needs me. Will making a letter help to prove that I will go back home after my visit to the UK? \n\nA:\n\nYou have no official income, and would like to get a visa to come to UK to stay for six month, and asking which documents need to be submitted.\nUnfortunately, in my opinion, no document you can submit in those circumstances would qualify you for a 6 month stay (but see below). \nFirst, for UK it seems that good financial standing of a potential visitor is one of the most important criteria to receive the visa (unlike USA, where past travel history seems to be more important). You have no official income and can leave for six months, which means to ECO that you have really no real ties to Philippines. The logic is that people with ties to the country (family, job, weddings to attend, studies to finish) can't really leave for six months, and in your situation you are more likely to overstay. A promise from you not to overstay is unfortunately useless. Please read this excellent answer of why bank statements are asked for - it covers your case too.\nSecond, considering that you have no resources of your own and totally depend on sponsor family, the potential for you to end up being abused (for example forced to work illegally) is high. This is not taken lightly, and it is another concern you need to overcome.\nSo the only way I could see it possibly working is if your sister's husband is really, really rich (not just \"doing well\" - we're talking a millionaire here). In this case it would be relatively easy to overcome a presumption you're coming as a free babysitter - especially if he provides support document which confirms that he already retained a babysitter agency. Then he should be able to find a solicitor which would help to prepare your application - this is also expensive and thus would serve as further evidence you are not coming to earn money illegally. In this case you have some chances - but still no guarantee.\nUnless this is the case, I would recommend not to apply. This may sound harsh, but if you apply and are refused now, you will have more difficulty applying later, even if your circumstances improve.\n\n"} +{"text": "Q:\n\ncin keyword not working in text editor\n\nI'm using the scite text editor (I cannot make use of any IDE or compiler since I'm required to also utilize Makefiles which is only possible if I use some sort of text editor) for all of my coding in c++. However, I'm consistently facing the same challenge; the text editor (I've attempted this on multiple ones including codepad and sublime text) isn't reading any input from the keyboard. Here is the source code:\n#include \n#include \nusing namespace std;\n\nconst int SIZE_OF_ARRAY = 5;\n\nint main(){\nint x, y;\nint counter = 0;\nint elements[SIZE_OF_ARRAY];\ncout << \"Please enter a number \";\ncin >> x;\ncin.ignore();\ncout << \"Please enter a choice \";\ncin >> y;\nif(y == 1){\n for(int i = 0; i < SIZE_OF_ARRAY; i++)\n elements[i] = -1*SIZE_OF_ARRAY + x;\n\n for(int j = 0; j < SIZE_OF_ARRAY; j++)\n cout << elements[j] << \" \";\n}\n\n else if(y == 2){\n for(int i = 0; i < SIZE_OF_ARRAY; i++){\n if(i == 0)\n elements[i] = -1*x;\n else{\n elements[i] = elements[i-1] + 1;\n }\n}\n\nfor(int j = 0; j < SIZE_OF_ARRAY; j++)\n cout << elements[j] << \" \";\n}\n\nelse if(y == 3){\n for(int i = 0; i < SIZE_OF_ARRAY; i++){\n counter++;\n elements[i] = 7*x*counter;\n }\n\nfor(int j = 0; j < SIZE_OF_ARRAY; j++)\n cout << elements[j] << \" \";\n}\n}\n\nThe program is supposed to take as an input any number from the user and, depending on a numeric choice (between one and three) entered by the user, manipulate the value first entered somehow.\nChoice one (User picks first choice)\nThe program negates the size of the array and adds the number which the user first entered and fills the array with the resulting value.\nChoice Two (User picks second choice)\nThe program negates the number entered by the user, places this in the first array location then each successive element is added one unit more than the previous one.\nChoice Three (User picks third choice)\nFills the array with the first five multiples of seven. Then shifts each number by a factor equivalent to the number the user had first entered.\nI've ran it on an IDE (Codeblocks) and it works perfectly well. However, on any text editor, the 'cout' statements are printed with the variables x and y taken to each be equal to zero rather than being set to the value entered from the keyboard. It doesn't even allow any keyboard input. Any answer regarding how I can fix this would be immensely appreciated.\n\nA:\n\nHoosain, continuing from the comments above, when you use an IDE, you must configure the path to your compiler as well as all compiler options you wish to use, and the location for the resulting executable and object files, etc. When you used CodeBlocks on windows, you essentially got lucky that CodeBlocks will automatically detect whether MinGW is installed and set its compiler configuration to allow you to build and run your code without you having to configure the compiler details. Geany is another editor that does a good job auto-detecting and using MinGW.\nFor the remaining IDE's it is up to you to configure them to find and use the compiler you have installed (MinGW), as well as configuring all desired compiler options (at minimum enable compiler warning with -Wall -Wextra).\nThat is where new programmers who have only used an IDE configured for them run into problems... Before you can tell an IDE where your compiler is located and which compiler options you want to use, you have to know where you compiler is located and understand what minimum set of compiler options you should use. \nThe way you learn to use a compiler is with the good old command line. (yep, that's cmd.exe on windows, often labeled as the \"DOS Prompt\" in earlier versions) An IDE is just a front-end to your compiler that executes the same commands you can simply enter on the command line to compile your program.\nLearning how to use your compiler will save you an incredible amount of time when learning to code. You can simply open a command prompt and compile any file you wish, without setting up a project, etc.. When learning to code, trying to shoehorn small examples into an IDE is much more time consuming and often more trouble than it is worth. Rather than worry how to use an IDE, focus on \"how to use your compiler\" first.\nSince you have MinGW installed on windows, all you have to do to be able to compile from the command prompt is add the path to the MinGW bin directory to your User Environment. You do that by adding the PATH as an Environment Variable here:\nStart Menu-> (rt-click on Computer)-> Properties-> \nAdvanced System Settings-> (Advanced tab)-> Environment Variables\n\nIn the Top window (your user variables), click to add (or edit) the PATH \"Variable name\". Generally, if you installed MinGW in the default location, you simply add the path as the \"Variable value\":\nc:\\MinGW\\bin;c:\\MinGW\\mingw32\\bin\n\n(verify the path on your computer)\n(note: windows separates path components by the semi-colon, so if there is already a PATH variable set, just add a semi-colon between what is there and what you add. Also if you already have a command prompt open, you must close it and open it again for the new path to take effect) Just open Start Menu-> Accessories-> Command Prompt (you can rt-click on the icon (top-left) and choose Properties to set the font (recommend Lucida Console 12) and height/width)\nNow you have configured your command prompt to allow you to compile any file at any location within your filesystem. For example, I tested with the code you posted (I modified it to add prompts for the information). Compiling it is a piece of cake. I keep my executables in a bin directory to keep sources and binaries separate.\nI named your file array_get.cpp.\nCompile\nThen just enter the normal g++ compiler command, and at minimum use -Wall -Wextra options to enable compiler warnings (you can add -pedantic and whatever additional warnings you want, I would recommend at least adding -Wshadow so your compiler will warn on any variables you declare in multiple scopes that could conflict). The -o option allows you to specify the location of the executable (I just use a separate bin directory as explained above). So to compile and link your code into bin\\array_get.exe all I have to enter is:\nC:\\Users\\david\\Documents>g++ -Wall -Wextra -o bin\\array_get array_get.cpp\n\n(do not accept code until it compiles without warning -- read any warning (it gives line of problem), understand what it is telling you, and go fix it)\nExample Use/Output\nC:\\Users\\david\\Documents>bin\\array_get.exe\nPlease enter a number: 21\nPlease enter a choice (1-3): 3\n147 294 441 588 735\n\nThat's it. Since MinGW uses gcc, the compiler commands you use on windows are the exact same you would use in Linux, so learning to compile from the command line pays double-benefit.\nNow you have the luxury of using any text-editor to edit your code while you have the command prompt simply and easily re-compile as you wish until your code is correct. No project dialogs, no mess of a different folder for every file, just the freedom to compile any file you wish -- right from the command line. (I actually separate my sources in directory by type, e.g. c, cpp), you find what works best for your. I also use a simple bat file that takes the exename and source.cpp names as arguments and then compiles with the options I set -- it just cuts down on typing :)\nFurther, since you now where your compiler is located, and which options to use, you can open the Settings window on any IDE and set the appropriate compiler command and compiler options to allow the IDE compile your code for you. Give it a try, and let me know if you have further questions.\n\n"} +{"text": "Q:\n\nMultiple Language Website PHP\n\nI want to make my PHP website into a multiple language website, with exactly two languages (English, Turkish).\nAt the top of the web page, there are two icons, one for English and the other for Turkish. When a user clicks on Turkish icon how can I detect that Turkish is selected?\n
\n\n \n\n
\n\nHow can I do that?\nI have two files for languages, one for English language and then another one for Turkish. \n$arrLang['alert_admin_email_wrong']='kullanci email yanli\u015ft\u0131r ' \n$arrLang['alert_admin_email_wrong']='your email is wrong '\n\nI must use session or cookies for this problem \n\nA:\n\nThe easiest way to do that is to create an cookie when the user clicks on the wanted language.\nAs for the array i would split it per language\n$arrLang['en']['alert_admin_email_wrong'] = 'text here';\n$arrLang['tr']['alert_admin_email_wrong'] = 'text here turkish';\n\nAs for language selection would do this on the webpage\nEnglishTurkish\n\nOn the language selection page :\n$defaultLanguage = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en'; //default to english language\nif(isset($_GET['langSelect'])){\n //allow only 2 for now ( english / turkish)\n $langForSelection = \"\";\n switch($_GET['langSelect']){\n case 'en':\n $langForSelection = 'en';\n break;\n case 'tr':\n $langForSelection = 'tr';\n break;\n default:\n break;\n }\n if(isset($langForSelection)){\n setcookie('lang',$langForSelection,time()+24*7*60*60);//set cookie to expire in 7 days\n }\n}\n\nAfter to show the variables\necho $arrLang[$defaultLanguage]['alert_admin_email_wrong'];\n\n"} +{"text": "Q:\n\nAngular input event is not fired by setting the value with the model\n\nI use a input field which calls a method when the value in it changes. But when I set the value in the input field by the ngModel (not typed by hand) the \"value changed\" event of the input field will not be fired.\nInput field:\n
\n \n
\n\ncomponent:\npublic updateData(evt: any): void {\n .finally(() => {\n this.orderNumberFilterValue = \"test\"\n })\n .subscribe(\n //get data from backend\n });\n}\n\npublic updateOrderNumberFilter(evt: any): void {\n\n //do stuff with the event\n\n}\n\nA:\n\nAnd it will not be fired, because input event will be fired only during user interaction. \nYou can work with Reactive Forms instead of Template Driven Forms and using its valueChanges function you can listen to changes of the value of the controls.\nAnother answer about Reactive Form value changes you can read here \nUPDATED\nYou can declare your function to get the value of the input\npublic updateOrderNumberFilter(value: any): void {\n\n}\n\nIn the markup attach it with $event.target.value\n\n\nand also call it in the finally and pass the value.\n\n"} +{"text": "Q:\n\nHow do I fetch translated strings?\n\nI have a progressively decoupled Reactjs application running on top of Drupal. Its a multilingual application.\nI need to fetch the translated strings from the Drupal itself and handle the translations editor and everything in Drupal itself, rather than maintaining a separate translation system for react.\nHow is it possible? A simple Drupal.t() doesn't work. I checked.\nAny examples I can refer?\n\nA:\n\nDrupal.t() works in this case. Have to to compile the javascript and clear the Drupal cache in order for strings to appear.\nFor props way:\nOn get_sample_props():\nfunction getsampleprops() {\n return ['sampleval' => t('Hello World!!!')];\n}\n\nOn the controller,\n$build = [\n '#theme' => 'sample_react',\n '#props' => json_encode($this->get_sample_props()),\n];\n\nOn the template, I did:\n
\n\nOn the React side, I used\n$val = this.props.labels.sampleval;\n\nVolia, its done. Its bit inconvenient, but work gets done.\n\n"} +{"text": "Q:\n\nWhy there are so many tags without any question related to them?\n\nWhy do these tags exist if they have no associated questions?\nTags: reinterviewing, self-employment, singapore, supplies, untagged, visa, workers-compensation, workplace-routine, phone, quitting, promises, outside-of-workplace, paperwork, multicultural, mexico, masters, library, it-departments, it-industry, inmigration, job-title, jury-duty, customer-relations, demotion, departments, germany, hardware, health, illness, hours, exercise, exit-interview, charity, cliches, assessment, alertness, banking, batna, accommodations, complaint, boss, bosses, headhunter, recruiters and reference.\nIn my opinion, some of the tags seem like duplicates (like bosses and boss), some seem off topic (like hardware, mexico, singapore, germany), some too specific (like batna) and finally, google told me that inmigration should be immigration.\n\nA:\n\nLet's categorize these tags so that it's easier to identify areas that might need action...\nTags with just 1 question:\nIdeally, we should determine if these tags are needed. If they don't have any value, they can be removed and replaced with a better tag. But if the tag is something that could come up again or that could help people find this information, then the tag should remain.\n\nreinterviewing\nself-employment\nsingapore\nsupplies\nvisa\nworkers-compensation\nworkplace-routine\nphone\nquitting\npromises\noutside-of-workplace\npaperwork\nmulticultural\nmexico\nmasters\nlibrary\nit-departments\nit-industry\nimmigration (fixed spelling)\njury-duty\ncustomer-relations\ndemotion\ndepartments\ngermany\nhardware\nhealth\nhours\nexercise\nexit-interview\ncharity\ncliches\nassessment\nalertness\nbanking\nbatna (Possibly meaning Best Alternative to a Negotiated Agreement )\naccommodations\ncomplaint\n\nTags that are synonyms of other tags:\nThese tags are synonyms of other tags. This means that the question can be tagged with either tag and still show up in the same tag search. For instance, searching for the tag \"boss\" or \"bosses\" shows me the same 122 results as if I searched for the \"management\" tag.\nTag synonyms are often used when different people try to use different tags that really identify the same groups of questions.\n\nBoss and Bosses are a synonym of Management. 122 questions hold this tag.\njob-title is a synonym of title. There are 13 questions with these tags.\nillness and sickness are synonyms. There are 5 questions with these tags.\nheadhunter and recruiter are synonyms of recruitment. There are 58 questions with this tag.\nreference is a synonym of references. There are 22 questions with this tag.\n\nUntagged Questions:\n\n\"untagged\" is a special tag that is used on questions that do not have a tag. Ideally, we should find tags that apply to these posts. Currently, there is only 1 question that has no tags. \n\n"} +{"text": "Q:\n\nJQuery/Jscript string manipulation with varying lengths\n\nI wrote a very basic jquery script to obtain the src attribute from my img elements. Long story short, based on the number contained in the src attribute of my thumbnails, the code then uses that same id number to fetch the corresponding main image:\nsample thumb src value: catalog/p1-t1.png | where p = piece and 1 = id, t1 = thumb 1\nsample mainpic src value: catalog/p1-1.png | where p = piece and 1 = id, 2nd 1 = main pic for thumb 1\nIt all worked nicely up until single digit numbers became double digits and thus, using something like:\n$string = $string.substring(12,13);\n\nceased to work (obvious yes).\nI want to get from my thumb's 'catalog/p1-t1.png' src value the '1' after the 't', whether its t1 or t33 or t999.\nThanks in advance\nG.Campos\n\nA:\n\nA wild Regular Expression appears!\nvar string = 'catalog/p1-t666.png',\n re = /\\/p(\\d+)-t(\\d+)/\n result = re.exec(string),\n piece = result[1], // 1\n thumb = result[2]; // 666\n\nOh and later a slightly less wild demo appears, I guess.\n\n"} +{"text": "Q:\n\nObject Reference Handling in C#\n\nI was working on a c# program today and ended up having to chase a bug for quite some time. \nI was trying to make a copy of an object change a few fields and send it on as well as the original\nfor example\nFunction(Object A)\n{\n Object B = new Object();\n Object B = A;\n\n B.foo = \"bar\";\n\n Send(A);\n\n Send(B);\n}\n\nMy program started treating A and B as the same object meaning that any changes to A would also change B and vise versa.\nI know that the Object A and B are both referencing the same memory.\nIs there a short hand way to ensure the line Object B = A references new memory thus creating different objects. Or is the only way to create a copy constructor in my Object and create B with Object B = new Object(A)\neg: \nObject(Object a){\n foo = a.foo;\n ...\n}\n\nBasically i just what to know more about how C# handles object references and memory allocations. Big subject i know. \n\nA:\n\nYou can call the protected MemberwiseClone method, which will make a shallow copy of all the object. If you can modify the class of the object, you can even create a public Clone method that delegates to this. And if you're willing to use structs instead of classes, any assignment will create a copy. This is because structs are value types, and assigning one value type variable to another creates a copy.\nWith regard to MemberwiseClone, note the part where I said \"shallow.\" Value type fields will be copied, but reference type fields will still refer to the same underlying objects.\n\n"} +{"text": "Q:\n\nCqlEngine - sync_table() KeyError: 'cqlengine'\n\nI am just starting to work with Cassandra in python using cqlengine.\nI tried following this link and tried ran this script:\nfrom cqlengine import columns\nfrom cqlengine import Model\nfrom cqlengine import connection\n\nfrom cqlengine.management import sync_table\n\nimport uuid\n\nclass ExampleModel(Model):\n example_id = columns.UUID(primary_key=True, default=uuid.uuid4)\n example_type = columns.Integer(index=True)\n created_at = columns.DateTime()\n description = columns.Text(required=False)\n\nconnection.setup(['127.0.0.1'], 'cqlengine')\n\nsync_table(ExampleModel)\n\nBut it throws up this error:\nTraceback (most recent call last):\n File \"\", line 1, in \n File \"/home/zopper/Desktop/django-cassandra/local/lib/python2.7/site-packages/cqlengine/management.py\", line 92, in sync_table\n keyspace = cluster.metadata.keyspaces[ks_name]\nKeyError: 'cqlengine'\n\nMy pip freeze is:\nDjango==1.7.3\nargparse==1.2.1\nblist==1.3.6\ncassandra-driver==2.1.3\ncqlengine==0.21.0\ndjango-cassandra-engine==0.2.1\ndjangotoolbox==1.6.2\nfutures==2.2.0\nsix==1.9.0\nwsgiref==0.1.2\n\nPlease help me understand and solve this issue.\nThanks.\n\nA:\n\nThis was overlooked on my end - I'm fixing it now. create_missing_keyspace would rarely \"do the right thing\", and it's very difficult and time consuming to fix a keyspace created with the wrong parameters. You must now explicitly create a keyspace with the parameters you want.\n\n"} +{"text": "Q:\n\nHow to Make Separate Space in VB.Net\n\nHow to make a separate space?\nExample: I want make ASCII to Hex\n\nHello - 48656C6C6F\n\nBut I want it formatted like this\n\nHello - 48 65 6C 6C 6F\n\nA:\n\nYou can use Encoding.ASCII and the BitConverter class.\nDim asciiBytes = Encoding.ASCII.GetBytes(\"Hello\")\nDim hex = BitConverter.ToString(asciiBytes).Replace(\"-\", \" \")\n\nhex is now 48 65 6C 6C 6F\n\nA:\n\nOr on one line\nDim hex = String.Join(\" \", \"Hello\" _\n .Select(Function(c) Convert.ToByte(c).ToString(\"x2\")))\n\nwithout the Replace.\n\nIf you want to show the high bytes (because each Char is actually two Bytes because strings are Unicode)\nDim hex = String.Join(\" \", \"Hello\" _\n .SelectMany(Function(c) BitConvertor.GetBytes(c)) _\n .Select(Function(b) b.ToString(\"x2\")))\n\n"} +{"text": "Q:\n\nStash Merge 2 Repositories with complete History\n\nI want to merge 2 Repositories in the Same Project in Stash. The complete History should be merged too. Is there any way to do this? \n\nA:\n\nStash developer here. This is really a Git question. Depending on how you want/need the repository merged I would recommend you first check out Git Subtree:\nhttp://blogs.atlassian.com/2013/05/alternatives-to-git-submodule-git-subtree/\nAlternatively you can just run git pull ../other_git_dir in your first repository, and that will fetch all the commits on the default/current branch (eg. master) into your second repository. Note that this only works for one branch at at time. Some more reading:\nhttp://scottwb.com/blog/2012/07/14/merge-git-repositories-and-preseve-commit-history/\nIf you're actually talking about creating a pull request then you can't (currently) do this across two unrelated (eg. non forked) repositories in Stash. You could however pull the history from one repository into another (as above) and then create the pull request that way.\n\n"} +{"text": "Q:\n\nPlaying the man, not the board\n\nA recent thread used this term. Which notable GMs are known to have 'played the man'?\nThis is interesting because hindsight and computers are wonderful things. They should allow us to pick out \"blunders\" that didn't lead to losses.\nIs chess a game against a person? If so, why do we look down our noses when we hear \"playing the man\"?\n\nA:\n\nBeing the one who said that, it's probably fitting I answer.\nIt all depends on your definition of 'playing the man and not the board.' If by that you mean ignoring your opponent's moves and the demands of the position, gambling on an unsound attack, no good player does that, certainly no Grandmaster.\nOTOH, every player has preferences for typical positions, and in preparing for a game against a known opponent, most top players will 'slant' their work a little, aiming to get positions they're comfortable playing that might be uncomfortable for their opponents.\nThe classic case of this has got to be Kramnik's revival of the Berlin Defense against Kasparov in their world title match. Kramnik knew Kasparov well, knew he didn't like queenless middlegames with lots of maneuvering. So he added the Berlin to his arsenal for that match, and he won.\nNote the subtlety, though. Kramnik didn't play bad moves; the Berlin is a perfectly playable defense that only fell out of favor because it tended to draw far more than other lines.\nIn my coaching I've run into too many youths who use 'playing the player, not the board' as an excuse to play \"hope chess,\" making bad moves to generate a silly attack that in reality has no hope of succeeding against anyone with more than two synapses firing.\nMy advice to them has always been: \"Learn how to play the board, first. Then, when you're good enough to understand what positions you're comfortable in and how to tell when someone else isn't, and only then, start to consider playing the player. Because only then will you be able to do so with any real hope of success.\"\n\n"} +{"text": "Q:\n\nDropDownListFor() help please\n\nI've been farting around with this HTML Helper for awhile now, following all sorts of examples which in theory accomplish the same end result. However, I can't seem to produce the end result...\nMaybe someone can see what I'm doing wrong before I go back to iterating out select options with a foreach. It would be nice to lock in how this helper works, less code than a select with a foreach(). Thanks in advance.\nEdit controller;\npublic ActionResult Edit(string id)\n {\n if (id != \"\")\n {\n\n UserViewModel user = (from u in db.Users.Where(u => u.Id.Equals(id))\n from ur in u.Roles\n join r in db.Roles on ur.RoleId equals r.Id\n\n select new UserViewModel\n {\n UserId = u.Id,\n DisplayName = u.DisplayName,\n Role = r.Name,\n RoleId = r.Id\n\n }\n ).FirstOrDefault();\n\n //Select List items for select list\n var roles = db.Roles.Select(r => new SelectListItem { Value = r.Id, Text = r.Name });\n\n //select list with selected value\n user.Roles = new SelectList(roles,\"Value\", \"Text\", user.RoleId);\n\n return View(user);\n }\n return View();\n }\n\nView;\n
\n @Html.LabelFor(model => model.Role, htmlAttributes: new { @class = \"control-label col-md-2\" })\n\n
\n @Html.DropDownListFor(model => model.Role, Model.Roles, null, new { @class = \"form-control\" })\n\n @Html.ValidationMessageFor(model => model.Role, \"\", new { @class = \"text-danger\" })\n
\n
\n\nA:\n\nYour code\nvar roles = db.Roles.Select(r => new SelectListItem { Value = r.Id, Text = r.Name });\n\ncreates IEnumerable. \nuser.Roles = new SelectList(roles,\"Value\", \"Text\", user.RoleId);\n\njust creates another identical IEnumerable from it so its just pointless extra overhead and since your binding to a property in your model, the last paramater (user.RoleId) is ignored and also pointless\nIt should be just \nuser.Roles = db.Roles.Select(r => new SelectListItem { Value = r.Id, Text = r.Name });\n\nWhen your create this SelectList you setting the value to the Id property of Role but you then attempting to bind to the Role property of UserViewModel instead of the RoleId property. Because the value of Role will not match one of the option values the first option in the dropdownlist will always be selected (because something has to be).\nChange the code in your view to\n@Html.DropDownListFor(model => model.RoleId, Model.Roles, null, new { @class = \"form-control\" })\n\nIf the value of RoleId matches one of the option values, then it will be selected.\nSide note: your Role property in your view model seems unnecessary, as does the need to create a join to the Roles table in your query. \n\n"} +{"text": "Q:\n\nEmbedded C: Registers Access\n\nSuppose we want to write at address say 0xc000, we can define a macro in C as:\n#define LCDCW1_ADDR 0xc000\n#define READ_LCDCW1() (*(volatile uint32_t *)LCDCW1_ADDR)\n#define WRITE_LCDCW1(val) ((*(volatile uint32_t *)LCDCW1_ADDR) = (val))\n\nMy question is that when using any micro-controller, consider an example MSP430, P1OUT register address is 0x0021.\nBut when we use P1OUT=0xFFFF; // it assigns P1OUT a value 0xFFFF.\nMy question is how does it write to that address e.g. in this case 0x0021.\nThe IDE is IAR. I found in header msp430g2553.h below definition: \n#define P1OUT_ (0x0021u) /* Port 1 Output */\nDEFC( P1OUT , P1OUT_)\n\nI suppose it is defining the address, but where are the other macros to write or read.\nCould anyone please explain the flow that how P1OUT writes at that particular address location? Also do let me know what does u mean in 0x0021u ?\nThanks \n\nSo far the details I have found are :\nin msp430g2553.h\n#ifdef __IAR_SYSTEMS_ICC__\n#include \"in430.h\"\n#pragma language=extended\n\n#define DEFC(name, address) __no_init volatile unsigned char name @ address;\n#define DEFW(name, address) __no_init volatile unsigned short name @ address;\n#define DEFXC volatile unsigned char\n#define DEFXW volatile unsigned short\n\n#endif /* __IAR_SYSTEMS_ICC__ */\n\n#ifdef __IAR_SYSTEMS_ASM__\n#define DEFC(name, address) sfrb name = address;\n#define DEFW(name, address) sfrw name = address;\n\n#endif /* __IAR_SYSTEMS_ASM__*/\n\n#define P1OUT_ (0x0021u) /* Port 1 Output */\nDEFC( P1OUT , P1OUT_)\n\nThe io430g2553.h says\n__no_init volatile union\n{\n unsigned char P1OUT; /* Port 1 Output */\n\n struct\n {\n unsigned char P0 : 1; /* */\n unsigned char P1 : 1; /* */\n unsigned char P2 : 1; /* */\n unsigned char P3 : 1; /* */\n unsigned char P4 : 1; /* */\n unsigned char P5 : 1; /* */\n unsigned char P6 : 1; /* */\n unsigned char P7 : 1; /* */\n }P1OUT_bit;\n} @0x0021;\n\nCan some one explain what the above definition does? The details I found in MSP430 IAR C/C++ Compiler:\nExample of using __write and __read\nThe code in the following examples use memory-mapped I/O to write to an LCD\ndisplay:\n__no_init volatile unsigned char LCD_IO @ address;\nsize_t __write(int Handle, const unsigned char * Buf,\nsize_t Bufsize)\n{\nsize_t nChars = 0;\n/* Check for stdout and stderr\n(only necessary if file descriptors are enabled.) */\nif (Handle != 1 && Handle != 2)\n{\nreturn -1;\n}\nfor (/*Empty */; Bufsize > 0; --Bufsize)\n{\nLCD_IO = * Buf++;\n++nChars;\n}\nreturn nChars;\n}\nThe code in the following example uses memory-mapped I/O to read from a keyboard:\n__no_init volatile unsigned char KB_IO @ 0xD2;\nsize_t __read(int Handle, unsigned char *Buf, size_t BufSize)\n{\nsize_t nChars = 0;\n/* Check for stdin\n(only necessary if FILE descriptors are enabled) */\nif (Handle != 0)\n{\nreturn -1;\n}\nfor (/*Empty*/; BufSize > 0; --BufSize)\n{\nunsigned char c = KB_IO;\nif (c == 0)\nbreak;\n*Buf++ = c;\n++nChars;\n}\nreturn nChars;\n}\n\nDoes any one know?\n\nA:\n\nThis is \"how does the compiler generate the code from what I've written\", and only the compiler writers will actually be able to answer that for you. \nClearly, there are several non standard C components in the code above __no_init, the use of @, etc. In my reading of this, it tells the compiler that \"this is a HW port, that provides an unsigned char, and it's address is 0xd2\". The compiler will produce the right kind of instructions to read and write such a port - exactly how that works depends on the compiler, the processor that the compiler is producing code for, etc. \nThe P10out structure defines bitfields, which is part of the C standard. Google is your friend here. \n\n"} +{"text": "Q:\n\nHow do I apply a patch from gnus to a git repo?\n\nI've got an email with a dozen .patch files attached in gnus. I can save them to e.g. ~/Downloads and then apply them with magit-patch-apply-popup, but considering that I've got gnus open on the left (and I can open the patch in its own buffer by putting my cursor over it and pressing c) and the magit summary buffer on the right, I would think that I could just apply the patch right there. But I cannot figure out how to do this.\n\nA:\n\nFound the answer via this blog post: Use Gnus to apply patch sent by git send-email.\nBasically, I put point on the email in the gnus Summary buffer, then do O m and save the email somewhere. Then in magit I do w m and it will apply the patch.\nUnfortunately for me this lost some commit info because the patches were sent from Gmail which formats patches incorrectly. So I just saved all the attached patches into the root of the git repo, selected them all (C-SPC) in the magit buffer, then did w w to apply them all individually. Then deleted the .patch files.\n\n"} +{"text": "Q:\n\nCan an interface have more than one IPv6 link-local, ULA, public address?\n\nIn Contiki OS, \nCan a node have more than one IPv6 link-local address?\nCan a node have more than one IPv6 Unique Link Address (ULA)?\nCan a node have more than one public IPv6 address?\n\nA:\n\nYes, yes and yes.\nHaving multiple addresses on one interface is quite common with IPv6. When using SLAAC your device will probably configure multiple addresses per prefix. Multiple prefixes may be advertised in the Router Advertisement, for example both a normal prefix and a ULA prefix. You can of course also configure addresses manually.\nOperating system commonly configure one address per prefix that is stable and doesn't change over time, and then regularly add some temporary addresses that will expire after a while. Those temporary addresses are usually used for outgoing connections so the server you are connecting to can't trace you based on your address.\nAlthough usually an interface only has one link-local address, you can have multiple if you want.\nPS: to keep this relevant to StackOverflow, please indicate the programming issue you are trying to solve with this information.\n\n"} +{"text": "Q:\n\nWhen compiling the Linux Kernel, what is the purpose of `make randconfig`?\n\nIn what scenario would one want to use this tool? It would seem to make less work, but the upshot is, of course, that you don't know what configuration options will be used for your kernel, which could very well mess things up.\n\nA:\n\nThe messing things up is the point.\nIt's used for what's called \"fuzz testing\" - making sure the kernel config can't be put in a state where the kernel can't compile. Rather than rely on pure human ingenuity to break things, they enlist the help of entropy.\n\n"} +{"text": "Q:\n\nUi thread blocked but only on 1st call to Webclient asynch methods\n\nPer a client's request I have written a communication class that inherits from webclient. They want to be able to \"Pass in a custom windows form as a progress bar\" rather than that I created an interface that implements 3 properties. Anyway the problem I am having is the app starts and i click the start button so to speak and the first time i do this the ui thread is frozen, after a few seconds it unfreezes and the progress bar and data begin coming down.\nAfter this initial freeze though , any subsequent presses of the start button work perfectly and do not block the thread any ideas?\nHere are the relevant pieces of code from form 1\nprivate void btnSubmit_Click(object sender, EventArgs e)\n {\n txtResponse.Text = \"\";\n progressForm = new ProgressFormTest();\n myCommunication = new CommunicationClient(progressForm);\n myCommunication.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_RequestComplete);\n // myCommunication.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);\n myCommunication.Timeout += new EventHandler(wc_TimeOut);\n myCommunication.Cancelled += new EventHandler(myCommunication_Cancelled);\n\n progressForm.Show();\n myCommunication.TimeoutValue = (int)numConnectionTimeout.Value * 1000;\n\n myCommunication.DownloadStringAsync(new Uri(txtUrl.Text));\n\n }\n\nHere is the communication class\n public class CommunicationClient:WebClient\n {\n private int step = 1000;\n private long bytesReceived;\n private long bytesSent;\n private Status status;\n private System.Timers.Timer _timer;\n private IProgress myProgressForm;\n\n /// \n /// Sets the timeout value in milliseconds\n /// \n public int TimeoutValue { get; set; }\n public int TimeElapsed { get; set; }\n public long BytesReceived\n {\n get\n {\n return bytesReceived;\n }\n }\n public long BytesSent\n {\n get\n {\n return bytesSent;\n }\n }\n\n public event EventHandler Timeout;\n public event EventHandler Cancelled;\n\n public CommunicationClient(IProgress progressForm)\n {\n myProgressForm = progressForm;\n _timer = new System.Timers.Timer(step);\n _timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);\n }\n\n protected override void OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)\n {\n _timer.Stop();\n if (status == Status.Completed)\n {\n myProgressForm.PercentComplete = 100;\n base.OnDownloadStringCompleted(e);\n }\n }\n\n protected override void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e)\n {\n bytesReceived = e.BytesReceived;\n myProgressForm.BytesReceived = bytesReceived;\n if (e.TotalBytesToReceive == -1)\n myProgressForm.PercentComplete = calculateFakePercentage();\n else\n myProgressForm.PercentComplete = e.ProgressPercentage;\n base.OnDownloadProgressChanged(e);\n }\n\n protected virtual void OnTimeout(EventArgs e)\n {\n if (Timeout != null)\n {\n CancelAsync();\n this.Dispose();\n Timeout(this, e);\n }\n }\n\n protected virtual void OnCancelled(EventArgs e)\n {\n if (Cancelled != null)\n {\n this.Dispose();\n Cancelled(this, e);\n }\n }\n\n /// \n /// Cancels a pending asynchronous operation and raises the Cancelled Event\n /// \n /// Set to true to raise the event\n public void CancelAsync(bool Event)\n {\n CancelAsync();\n if (Event)\n {\n status = Status.Cancelled;\n OnCancelled(new EventArgs());\n }\n }\n\n private void initialize()\n {\n status = Status.Completed;\n TimeElapsed = 0;\n _timer.Start();\n }\n\n new public void DownloadStringAsync(Uri url)\n {\n initialize();\n base.DownloadStringAsync(url);\n }\n\n private void timer_Elapsed(object sender, ElapsedEventArgs e)\n {\n TimeElapsed += step;\n\n if (TimeElapsed >= TimeoutValue)\n {\n _timer.Stop();\n status = Status.Timeout;\n OnTimeout(e);\n }\n } \n\n //used when the website in question doesnt provide the content length\n private int calculateFakePercentage()\n {\n return (int)bytesReceived * 100 / 60000 ;\n } \n}\n\nAnd here is the simple Interface IProgressForm\npublic interface IProgress\n{\n int PercentComplete\n {\n get;\n set;\n }\n long BytesReceived\n {\n get;\n set;\n }\n long BytesSent\n {\n get;\n set;\n }\n}\n\nA:\n\nFixed it , I set the Proxy property from the webclient class to null and that seemed to fix it\n\n"} +{"text": "Q:\n\nSearch for field name in access table then update relevant fields names with values delphi 7\n\nI have an Access database table named ReceiptTable with the following field names: item name, buying price, selling price, goods total, cash, change. I am using an Adoquery and datasource to connect to the access database. When I want to update records to receiptTable, I use the following code to locate an item name from the database then update all the records with similar item name in the database with the values from edit box field values:\nprocedure TReceiptForm.BitBtn1Click(Sender: TObject);\nbegin\nwith ADOQuery1 do\nADOQuery1.Open;\nADOQuery1.Locate('item name',Edit1.Text,[]) ;\nADOQuery1.edit;\nADOQuery1.FieldValues['goods total']:=edit3.Text;\nADOQuery1.FieldValues['cash']:=edit4.Text;\nADOQuery1.FieldValues['change']:=edit5.Text;\nADOQuery1.Post;\nend;\n\nThe problem I have is that only one row with the item name is updated but the other rows with similar item name are not updated. What code should I add above so that all the rows which have similar item names are updated with values from edit boxes?\n\nA:\n\nThis simple code answers your question:\nprocedure TReceiptForm.BitBtn1Click(Sender: TObject);\nvar\n itemname, goodstotal, cash, change: string;\nbegin\n // Execute query\n try\n ADOQuery1.Open;\n except\n on E: Exception do begin\n ShowMessage(E.Message);\n Exit;\n end{on};\n end{try};\n // Values\n itemname := Edit1.Text;\n goodstotal := Edit3.Text;\n cash := Edit4.Text;\n change := Edit5.Text;\n // Find first matching record, then go to the end of resultset.\n try\n ADOQuery1.DisableControls;\n if ADOQuery1.Locate('item name', itemname, []) then begin\n while not ADOQuery1.Eof do begin\n if ADOQuery1.FieldByName('item name').AsString = itemname then begin\n ADOQuery1.Edit;\n ADOQuery1.FieldValues['goods total'] := goodstotal;\n ADOQuery1.FieldValues['cash'] := cash;\n ADOQuery1.FieldValues['change'] := change;\n ADOQuery1.Post;\n end{if}; \n ADOQuery1.Next;\n end{while};\n end{if};\n finally\n ADOQuery1.EnableControls;\n end{try};\nend;\n\nThis will work, but you can consider using one SQL statement for updating the table, or \nif it is possible order your query by 'item name' and use this:\n...\n// Find first matching record, then update while next record matches too.\nif ADOQuery1.Locate('item name', itemname, []) then begin\n while (not ADOQuery1.Eof) and \n (ADOQuery1.FieldByName('item name').AsString = itemname) do begin\n ADOQuery1.Edit;\n ADOQuery1.FieldValues['goods total'] := goodstotal;\n ADOQuery1.FieldValues['cash'] := cash;\n ADOQuery1.FieldValues['change'] := change;\n ADOQuery1.Post;\n ADOQuery1.Next;\n end{while};\nend{if};\n...\n\n"} +{"text": "Q:\n\nfield not saved when I change the name attribute of the field form in Yii\n\nwhen I add the name attribute to a field form in Yii , the field content is not saved in DB\nthe following works, \necho $form->textField($model,'country'); ?>\n\nit generates the html code\n\n\nthe following does not work,\necho $form->textField($model,'country', array('name'=>'country'); ?>\n\nit generates the html code\n\n\nAny idea?\n\nA:\n\nThe field name=\"RegistrationForm[country]\" is required if you are using\n$model->attributes = $_POST['RegistrationForm'];\n\nto set the attributes in the controller.\nIf you want to use a custom name like name=\"country\", you will have to manually set the value of the model yourself:\n$model->attributes = $_POST['RegistrationForm'];\n$model->country = $_POST['country'];\n\n"} +{"text": "Q:\n\nJavaScript, jQuery, XML - if statement not executing for unknown reason\n\nI have a 'for' loop which extracts data from an XML document and adds it into some JavaScript objects, each time the loop executes I want it to run a certain function depending on the value of the attribute 'typ' which is being retrieved from the xml.\nCurrently, the data from the XML is successfully being parsed, which is proven by the first 'alert' you can see which produces the correct value.\nHowever, neither of the 'alert' lines in the 'if' statement lower down are being executed and as a result I cannot test the 'ctyp3' function which is supposed to be called.\nWhere have I gone wrong?\n for (j=0; j_callObserverMethod(Object(Meigee_ThemeOptions_Controller_Observer), 'addLibrary', Object(Varien_Event_Observer))\n#2 /home/user/website.com/app/Mage.php(447): Mage_Core_Model_App->dispatchEvent('controller_acti...', Array)\n#3 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Action.php(351): Mage::dispatchEvent('controller_acti...', Array)\n#4 /home/user/website.com/app/code/core/Mage/Cms/Helper/Page.php(113): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()\n#5 /home/user/website.com/app/code/core/Mage/Cms/Helper/Page.php(52): Mage_Cms_Helper_Page->_renderPage(Object(Mage_Cms_IndexController), 'home')\n#6 /home/user/website.com/app/code/core/Mage/Cms/controllers/IndexController.php(45): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'home')\n#7 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Action.php(419): Mage_Cms_IndexController->indexAction()\n#8 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('index')\n#9 /home/user/website.com/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))\n#10 /home/user/website.com/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()\n#11 /home/user/website.com/app/Mage.php(683): Mage_Core_Model_App->run(Array)\n#12 /home/user/website.com/index.php(86): Mage::run('', 'store')\n#13 {main}\n\nObviously it is a theme issue, but what should I be looking at to fix it?\nEDIT: In response to the below answer, I can't access admin section either, I get the same error. Here is the relevant config.xml file in case that helps.\n\n\n \n \n 1.0.0\n \n \n \n \n \n \n \n \n \n Meigee_ThemeOptions_Model\n \n \n \n \n \n \n \n singleton\n \n Meigee_ThemeOptions_Controller_Observer\n overrideTheme\n \n \n \n \n \n \n singleton\n Meigee_ThemeOptions_Controller_Observer\n addLibrary\n \n \n \n \n \n \n Meigee_ThemeOptions_Helper\n \n \n \n \n \n Meigee_ThemeOptions_Block\n \n Meigee_ThemeOptions_Block\n Meigee_ThemeOptions_Block\n Meigee_ThemeOptions_Block\n \n Meigee_ThemeOptions_Block\n \n Meigee_ThemeOptions_Block_Bestsellers\n \n \n \n \n \n \n \n \n 0\n 1\n 14 \n 24\n 400\n pandora\n \n \n sidebar_right\n grid_standard\n cart_accordion\n \n \n menu_wide\n 1\n \n \n 1\n 1\n \n \n language_select\n \n \n \n currency_images\n \n \n \n 1\n 1\n 1\n \n \n \n \n prevnext\n moreviews_slider\n collateral_tabs\n related_slider\n \n \n \n \n 1\n \n 1\n \n \n 1\n \n 1\n \n \n 1\n \n \n 1\n \n \n 1\n \n \n 1\n \n \n \n 1\n \n \n 1\n \n \n \n\n\nEDIT 2: Tried disabling the module by the Meigee_ThemeOptions.xml file, still getting the same error:\n\n\n \n \n false\n local\n \n \n\n\nEDIT 3: Developer mode should be off. The index.php file has the below lines:\nif (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {\n Mage::setIsDeveloperMode(true);\n ini_set('display_errors', 1);\n}\nelse\n{\n Mage::setIsDeveloperMode(false);\n ini_set('display_errors', 0);\n}\n\nAnd .htaccess file has the line SetEnv MAGE_IS_DEVELOPER_MODE \"false\"\nI added the line to htaccess file because I did turn on developer mode (by commenting out the if statement) to get some error logs but don't think it has turned off correctly...Any help with that would be appreciated.\n\nA:\n\nThis error is only displayed when you have developer mode on. Leaving developer mode on a production server is really not recommended, since you run the risk of exposing your shop structure and could possibly lead to vulnerabilities, attacks, etc. Make sure you turn developer mode off by making sure the environment variable MAGE_IS_DEVELOPER_MODE is not set. \nPlease notice: not set means that the variable is not declared, since Magento is checking for its presence, not whethere it's true or false or any value.\n\n"} +{"text": "Q:\n\nIs it possible to format an USB external HD keeping intact some directories and files?\n\nMaybe it is a nonsense question, but I would like to format my external HD which contains plenty of files and directories, the HD format is NTFS, if it is possible I would like to format to ext4 but keeping one directory and its files intact. I know that I can backup it before formatting. Is it possible ? I'm running Xubuntu 16.04.5 and this external HD was originally recovered from an old netbook running Windows XP. Thanks, Vladi \n\nA:\n\nNope. If you format a partition that contains files, the operation will clear out all of the files.\nWhat you COULD do is use gparted to shrink the ntfs partition on the external drive, then create a new ext4 partition in the newly created free space (again using gparted), then move the files from the old NFTS partition to the new ext4 partition. Once you've done that, use gparted once again to remove the ntfs partition and to grow the new ext4 partition to fill all of the unused space.\n\n"} +{"text": "Q:\n\nApache Samza local storage - OrientDB / Neo4J graph instead of KV store\n\nApache Samza uses RocksDB as the storage engine for local storage. This allows for stateful stream processing and here's a very good overview.\nMy use case:\n\nI have multiple streams of events that I wish to process taken from a system such as Apache Kafka.\nThese events create state - the state I wish to track is based on previous messages received.\nI wish to generate new stream events based on the calculated state.\nThe input stream events are highly connected and a graph such as OrientDB / Neo4J is the ideal medium for querying the data to create the new stream events.\n\nMy question:\nIs it possible to use a non-KV store as the local storage for Samza? Has anyone ever done this with OrientDB / Neo4J and is anyone aware of an example?\n\nA:\n\nI've been evaluating Samza and I'm by no means an expert, but I'd recommend you to read the official documentation, and even read through the source code\u2014other than the fact that it's in Scala, it's remarkably approachable.\nIn this particular case, toward the bottom of the documentation's page on State Management you have this:\n\nOther storage engines\nSamza\u2019s fault-tolerance mechanism (sending a local store\u2019s writes to a replicated changelog) is completely decoupled from the storage engine\u2019s data structures and query APIs. While a key-value storage engine is good for general-purpose processing, you can easily add your own storage engines for other types of queries by implementing the StorageEngine interface. Samza\u2019s model is especially amenable to embedded storage engines, which run as a library in the same process as the stream task.\nSome ideas for other storage engines that could be useful: a persistent heap (for running top-N queries), approximate algorithms such as bloom filters and hyperloglog, or full-text indexes such as Lucene. (Patches accepted!)\n\nI actually read through the code for the default StorageEngine implementation about two weeks ago to gain a better sense of how it works. I definitely don't know enough to say much intelligently about it, but I can point you at it:\n\nhttps://github.com/apache/samza/tree/master/samza-kv-rocksdb/src/main/scala/org/apache/samza/storage/kv\nhttps://github.com/apache/samza/tree/master/samza-kv/src/main/scala/org/apache/samza/storage/kv\n\nThe major implementation concerns seem to be:\n\nLogging all changes to a topic so that the store's state can be restored if a task fails.\nRestoring the store's state in a performant manner\nBatching writes and caching frequent reads in order to save on trips to the raw store.\nReporting metrics about the use of the store.\n\n"} +{"text": "Q:\n\nhow to fix [Object: null prototype] { title: 'product' }\n\nI've started learning node.js with express framework , when I post a form like this :\nrouter.get('/add-product',(req,res,next)=>{\n res.send('
');\n});\n\nrouter.post('/product',(req,res,next)=>{\n console.log(req.body);\n res.redirect('/');\n});\n\nWhen I do console.log(req.body) it displays:\n[Object: null prototype] { title: 'product' }\n\ninstead of just { title: 'product' }\nI'm wondering if this actually is an error with express or just a propriety that its been added to express recently , cause i downloaded another project created last year and it used the same approach, when i console.log(req.body) it display the same output.\nThanks in advance for your help.\n\nA:\n\nThats actually good design. Objects by default inherit the Object.prototype that contains some helpers (.toString(), .valueOf()). Now if you use req.body and you pass no parameters to the HTTP request, then you'd expect req.body to be empty. If it would just be \"a regular object\" it wouldn't be:\n req.body.toString();\n\nThere is a way to create \"empty objects\", meaning objects without any properties / prototype, and that is Object.create(null). You are seeing one of those objects in the console.\nSo no, this is not a bug that needs to be fixed, thats just great use of JS' features.\n\nA:\n\nTry this,\nconst obj = JSON.parse(JSON.stringify(req.body)); // req.body = [Object: null prototype] { title: 'product' }\n\nconsole.log(obj); // { title: 'product' }\n\nHappy Coding..!\n\nA:\n\nI get some problem and my terminal showed me below explanation \nbody-parser deprecated undefined extended: provide extended option at express\nand i used this \napp.use(bodyParser.urlencoded({extended: false})) \nor\nyou are running a version of Express that is 4.16+ then type just\napp.use(express.urlencoded({extended: true})) \nI think it helps you\nTo find out more about the extended option, read the docs or someone here has answered it well - What does 'extended' mean in express 4.0?\n\n"} +{"text": "Q:\n\nConfigurationError: Server at 127.0.0.1:27017 reports wire version 0, but this version of PyMongo requires at least 2 (MongoDB 2.6)\n\nI am trying to build an application with mongoDB and Python Flask. While running the application, I am getting below error:\n\nConfigurationError: Server at 127.0.0.1:27017 reports wire version 0,\n but this version of PyMongo requires at least 2 (MongoDB 2.6).\n\nCan any one help me in this?\nThanks,\nBalwinder\n\nA:\n\nIt's pretty annoying and weird issue. \nBut this problem is solved with just downgrading pymongo library for me.\npip install pymongo==3.4.0\n\nFound answer in this : http://d-prototype.com/archives/10939\n\nA:\n\nI am having the same issue using version 2.4.10 on a Raspberry Pi 3. I found interesting information here: https://jira.mongodb.org/browse/SERVER-26715\nAccording to the above Jira task, it seems that this is a bug of MongoDB that was fixed in version 3.4. However, I found that comment stating that 3.4 is not supported on Raspbian because it is a 32-bits OS. This is confirmed here... we can only install 3.2 on Raspbian now apparently. \nAn alternative would be to install 64bits SuSE on the Pi or run MongoDB 3.4 in Docker.\nLet me know if you have found something else...\n\nA:\n\nFirst you change the server from ubuntu software center follow step\n1- Search Software & update in ubuntu software center\n2- Select Download from select Other then right side select Select best server it will take some time if it's complete \n\ntry to re install mongodb from this command\nStep 1\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5\n\nStep 2\nsudo apt-get update\n\nstep 3\nsudo apt-get install -y mongodb-org\n\n"} +{"text": "Q:\n\nScope in view laravel\n\nI have controller where I have the following code:\npublic function index()\n{\n $posts = Post::orderByDesc('id')->paginate(15);\n return view('home', compact('posts'));\n}\n\nThis return all posts in a page. On the page I have tabs: all posts, posts by time, posts by rating.\nIn model I have this scope:\npublic function scopeOfType($query, $type)\n{\n return $query->where('type', $status);\n}\n\nHow I can call this on the page where I have the tabs?\nWhen I try call scope with:\n@forelse($posts->ofType($type) as $post)\n\nI get error:\nMethod Illuminate\\Database\\Eloquent\\Collection::ofType does not exist. (View: \n\nHow I can fix this?\n\nA:\n\nIf you want to loop by type as you stated, you could use where on the collection already:\n@forelse($posts->where('type', $type) as $post)\n\nNote this is a collection and it filters it by the type you gave.\n\n"} +{"text": "Q:\n\nHow to get the name of child in Firebase with Kotlin\n\nI can`t get the only child-name on the firebase.\n mDatabase = FirebaseDatabase.getInstance().getReference(\"Diary_Subject\")\n if (user != null) {\n mDatabase.child(user.uid).addValueEventListener( object :\n ValueEventListener {\n override fun onCancelled(p0: DatabaseError) {\n TODO(\"not implemented\") //To change body of created functions use File ]| Settings | File Templates.\n }\n\n override fun onDataChange(snapshot: DataSnapshot) {\n\n if (snapshot!!.exists()){\n diarylist.clear()\n val subject = snapshot.toString()\n }\n})\n\nThis is my firebase\n\nI want my program show only the child name like be\ncgnyft\n\ndeveg\n\nbut it shows\n\nA:\n\nYou can use snapshot key:\noverride fun onDataChange(snapshot: DataSnapshot) {\n for (postSnapshot in snapshot.children) {\n val name = postSnapshot.getKey()\n Log.d(\"Name\",name)\n }\n}\n\nIf you want to use \"Diary_Subject\" you can do it like this:\noverride fun onDataChange(snapshot: DataSnapshot) {\n for (postSnapshot in snapshot.children) {\n val name = postSnapshot.child(\"Diary_Subject\").getValue(String.class)\n Log.d(\"Name\",name)\n }\n}\n\n"} +{"text": "Q:\n\nRelaxNG compact schema for either/both elements in either order\n\nI am writing a RelaxNG Compact schema for an XML file where the contents of the elements must be exactly one of:\n\n\n\n\n\nIn English, either or are allowed once each, or both in either order, but one of them is required to be present.\nIs there a better (more compact) definition of WrapElement than the following?\ngrammar {\n start = \n element wrap { WrapElement }\n\n WrapElement =\n (\n element a {empty}, \n element b {empty}?\n )|(\n element a {empty},\n element b {empty}?\n )\n}\n\nThe following is close. It's certainly more terse, it matches all the permitted variations, and disallows the elements from occurring more than once. However, it also incorrectly allows an empty element:\ngrammar {\n start = \n element wrap { WrapElement }\n\n WrapElement =\n element a {empty}?\n & element b {empty}?\n}\n\nA:\n\nThe following works for me:\ngrammar {\n start = \n element wrap { (a|b)|(a&b) }\n\n a = element a {empty}\n b = element b {empty}\n}\n\n"} +{"text": "Q:\n\nOSX HID Filter for Secondary Keyboard?\n\nI would like to filter keyboard input on a second keyboard, and prevent the key events for that second keyboard from reaching the OS (handle them myself). How can this be done?\n\nA:\n\nIt can be done by using IOKit and the HIDManager class.\nIf exclusive access to the keyboard is desired, the kIOHIDOptionsTypeSeizeDevice option can be used, but the program will have to be run with root privileges.\nA stub of the code required to obtain this result is shown below:\n// Create a manager instance\nIOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDManagerOptionNone);\n\nif (CFGetTypeID(manager) != IOHIDManagerGetTypeID()) {\n exit(1);\n}\n\n// Setup device filtering using IOHIDManagerSetDeviceMatching\n//matchingdict = ...\nIOHIDManagerSetDeviceMatching(manager, matchingdict);\n\n// Setup callbacks\nIOHIDManagerRegisterDeviceMatchingCallback(manager, Handle_DeviceMatchingCallback, null);\nIOHIDManagerRegisterDeviceRemovalCallback(manager, Handle_RemovalCallback, null);\nIOHIDManagerRegisterInputValueCallback(manager, Handle_InputCallback, null);\n\n// Open the manager and schedule it with the run loop\nIOHIDManagerOpen(manager, kIOHIDOptionsTypeSeizeDevice);\nIOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);\n\n// Start the run loop\n//...\n\nMore detailed information can be found in the Apple docs over here: http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/HID/new_api_10_5/tn2187.html\nThe complete code I used for my application can be found here:\nhttps://gist.github.com/3783042\n\n"} +{"text": "Q:\n\nSwift 3 URLSession Authentication on IBM Domino server\n\nI am a beginner in iOS development. I want to access some data from IBM Domino server with authentication. The code can only give back the server's login page. Anyone know what's wrong? (and sorry for my english)\nHere is my code to get data: \nclass URLSessionTest: NSObject, URLSessionDelegate {\n\nlet user = \"myUser\"\nlet password = \"myPwd\"\nlet url = URL.init(string: \"https://www.example.com/Test.nsf/0/91182C6C9EEE0414C12580A300312D1A?Opendocument\")\n\nfunc getData() {\n var request = URLRequest.init(url: url!)\n request.httpMethod = \"POST\"\n request.timeoutInterval = 30.0\n let parameters = [\"Username\": user, \"Password\": password] as Dictionary\n do {\n request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)\n } catch let error {\n print(\"request serialization error: \\(error.localizedDescription)\")\n }\n let configuration = URLSessionConfiguration.default\n let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)\n let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in\n if error != nil {\n print (\"dataTask error: \\(error!.localizedDescription)\")\n }\n if let myresponse = response as? HTTPURLResponse {\n print (\"dataTask response: \\(myresponse)\")\n myresponse.statusCode\n }\n let myval = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!\n print(\"dataTask data: \\(myval)\")\n })\n task.resume()\n}\n\nAnd the delegates:\nopen func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){\n print (\"challenge \\(challenge.protectionSpace.authenticationMethod)\")\n var disposition: URLSession.AuthChallengeDisposition = .useCredential\n var credential:URLCredential?\n let defaultCredential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.none)\n if challenge.previousFailureCount > 0 {\n print (\"cancel authentication challenge\")\n disposition = .cancelAuthenticationChallenge\n credential = nil\n } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {\n print (\"Server Trust\")\n credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)\n\n if (credential != nil) {\n print (\"Use credential\")\n disposition = .useCredential\n }\n else{\n print (\"perform default handling\")\n disposition = .performDefaultHandling\n credential = defaultCredential\n }\n }\n else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {\n print (\"client certificate\")\n }\n else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic {\n print (\"Basic authentication\")\n }\n else{\n disposition = .cancelAuthenticationChallenge\n credential = nil\n }\n if credential != nil { challenge.sender!.use(credential!, for: challenge)}\n completionHandler(disposition, credential);\n}\n\nfunc urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {\n print (\"URLSessionTask didReceive\")\n let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)\n challenge.sender?.use(credential, for: challenge)\n completionHandler(URLSession.AuthChallengeDisposition.useCredential,credential)\n}\n\nHere is the code's output:\nchallenge NSURLAuthenticationMethodServerTrust\nServer Trust\nUse credential\ndataTask response: { URL: https://www.example.com/Test.nsf/0/91182C6C9EEE0414C12580A300312D1A?Opendocument } { status code: 200, headers {\n\"Cache-Control\" = \"no-cache\";\n\"Content-Length\" = 5949;\n\"Content-Type\" = \"text/html; charset=UTF-8\";\nDate = \"Sun, 12 Feb 2017 19:14:19 GMT\";\nExpires = \"Tue, 01 Jan 1980 06:00:00 GMT\";\nServer = \"Lotus-Domino\";\n\"Strict-Transport-Security\" = \"max-age=0\";} }\n\nA:\n\nExpanding on @Per Henrik Lausten's comment, Domino servers provide a way to bypass session authentication and allow basic authentication for URLs that access a specific application. The method is described in this IBM technote. This is a better alternative than opening up the entire site to basic authentication. I see that you are using https, which is good, but the properties on the NSF file(s) that you are accessing should also be set to require https connections if they aren't already set that way.\n\n"} +{"text": "Q:\n\nReach to LAN device from a different subnet\n\nI have my network configured this way:\nThe ISP router giving internet access (192.168.1.1/24) through wifi (SSID wlan01).\nConnected to this wifi I have a Nanostation2 (192.168.0.20/24) in bridge mode. \nFinally I have a neutral router connected to the Nanostation2 in the WAN port.\nThe WAN port is configured as DHCP auto (so the ISP router gives the neutral router a 192.168.1.X/24 address).\nThis neutral router has a subnet (192.168.10.0/24), it's configured as a DHCP server (192.168.10.1/24) and provides another wifi connection (SSID wlan02).\nI need to connect with the Nanostation2 (192.168.0.20) while I am connected to the wlan02 SSID, which gives me an 192.168.10.X IP address to my computer's wireless interface...\nIs this possible through a static routing entry or with another method?\n\nA:\n\nI'm confused about where the 192.168.0.0/24 network is defined. If the Nanostation is in bridge mode it should have an IP address on the network 192.168.1.0/24.\nYour \"neutral router\" will have a default route to the ISP, and it will send anything from its LAN port to the default route. It doesn't know where the 192.168.0.0/24 network is. Conversely, the Nanostation should have a route to the 192.168.10.0/24 network is unless the \"neutral router\" is running NAT (giving you double-NAT which is probably not a good idea).\nYou can do this with static routes, which doesn't scale, or a routing protocol between routers.\n\n"} +{"text": "Q:\n\nDifference between Task and TaskFactory\n\nCan any one explain the difference between Task and Task Factory?\ntask :\n public Task(Func function);\n\nTask Factory:\npublic static TaskFactory Factory { get; }\n\nPlease explain with uses.\n\nA:\n\nSimply put Task.Run is a simplified version of TaskFactory and does exactly the same. With taskfactory you just have some more options(e.g. TaskCreationOptions)\n\n"} +{"text": "Q:\n\nDo you \"prevent somebody doing something\", or \"prevent somebody [from] doing something?\n\nIt seems to me that the \"from\" is unnecessary and perhaps redundant.\n\nA:\n\nI think unnecessary and redundant are somewhat \"loaded\" terms in this context. In fact, we usually do include the preposition \"from\"...\n\n...and I think only a pedant would argue for or against any of those three, in almost all contexts.\n\nComparing UK/US-only usage on that NGram suggests Brits may be slightly more likely to omit \"from\", but that hardly seems significant. The main factor affecting usage for all native speakers is that we're more likely to drop the preposition in simple constructions. Thus...\n\n\"You can't prevent me going!\"\n\n...is immediate and unambiguous (though many of us might prefer \"stop\"). On the other hand...\n\n\"You can't prevent an unemployed person watching daytime TV from drinking too much\"\n\n...is something of a garden path sentence. I highlighted the word \"from\" so you'd see it coming.\nIf I hadn't highlighted the word, you might well have assumed it before \"watching\". And then been forced to re-analyse later, when you finally came to the actual word explicitly stated. Which could have been even later - I could have written \"You can't prevent an unemployed person watching daytime TV drinking too much from dying young\" (forget the missing \"and's\" and commas).\n\n"} +{"text": "Q:\n\nEquilibrium points in lagrangian mechanics\n\nSuppose we have a one particle system with generalized coordinates $q_i$. In classical mechanics, the corresponding Lagrangian is $L = T - V$. Assume $V(q)$ is time-independent. What additional conditions on the system determine whether\n$$\\nabla V (q) = 0 \\iff q \\text{ is an equilibrium point} \\, .$$\nFor example, sometimes this condition holds only if $V$ is the effective potential.\n\nA:\n\nThe condition for equilibrium is actually best understood using the Hamiltonian. If the Lagrangian is time-independent, then the Hamiltonian is conserved (albeit not necessarily the energy) and the evolution must take place on a curve of $H=$ constant.\nGiven a Hamiltonian $H(p,q)$ (in one-dimension to keep it simple), then the condition for an equilibrium position is \n$$\n\\left(\\frac{\\partial H}{\\partial p},\\frac{\\partial H}{\\partial q}\\right)=0=(\\dot{q},-\\dot{p})\\, .\n$$\nGeometrically, the points that satisfy this are extrema in the $H$ landscape, i.e. when thinking of $H(p,q)$ as a surface in 3D. Mathematically, by Hamilton's equations, the momentum and position are exactly extremal at those points. \nMathematically, this formulation, which involves first derivatives, ties in with the rich topic of qualitative behaviour of coupled first order differential equations, which are applicable to a wide variety of systems: the study of predator-prey systems, Lanchester's model of warfare, etc (the list is very long).\nAn example for which this applies is the flyball governor. The Lagrangian for the system is \n$$\nL=\\ell^2(m_1+2m_2\\sin^2\\alpha)\\dot{\\alpha}^2+\nm_1\\ell^2\\Omega^2\\sin^2\\alpha\n+2(m_1+m_2)g\\ell\\cos\\alpha\\, .\n$$\nand it is difficult to identify a \"potential\" $V(\\alpha)$ since the coefficient of term in $\\dot{\\alpha}^2$ is actually a function of $\\alpha$.\n\nThe momentum $p_\\alpha=\\partial L/\\partial \\dot{\\alpha}=2\\ell^2(m_1+2m_2\\sin^2\\alpha)\\dot{\\alpha}$,\nso the Hamiltonian is found, after straightforward manipulations, to be\n\\begin{align}\nH&= \\frac{p^2_\\alpha}{4\\ell^2(m_1+2m_2\\sin^2\\alpha)}-m_1\\ell^2\\sin^2\\alpha\\,\\Omega^2\n-2(m_1+m_2)g\\ell\\cos\\alpha\\, .\n\\end{align}\nThe fixed points are easily obtained. \nClearly $\\partial H/\\partial p_\\alpha=0$ implies $p_\\alpha=0$. On the other hand:\n$$\n\\frac{\\partial H}{\\partial \\alpha}\\vert_{p=0}=\n2\\ell\\sin(\\alpha)\\left(m_1\\ell \\cos(\\alpha)\\Omega^2-(m_1+m_2)g\\right)=0\\, ,\n$$\nwhich gives $\\alpha=0$ but also a non-trivial equilibrium point if one can satisfy $m_1\\ell \\cos(\\alpha_0)\\Omega^2-(m_1+m_2)g=0$ for some angle $\\alpha_0$. See here for another example.\nIf the system is natural, so that \n$H=T+V_{\\hbox{eff}}$ with $T=p^2/(2m)$, this automatically reduces to a condition on the derivative of the effective potential.\n\n"} +{"text": "Q:\n\nSerialize to AMF exactly like NetConnection does\n\nI want to serialize an object to AMF, and I want the result to be exactly the same as if it is serialized by NetConnection.call(). So, I use ByteArray.writeObject(), and the output bytes are usually the same as bytes sent by NetConnection.call(), but sometimes couple of bytes are different.\nI found this in AMF3 spec: \"Note that ByteArray.writeObject uses one version of AMF to encode the entire object. Unlike NetConnection, ByteArray does not start out in AMF 0 and switch to AMF 3 (with the objectEncoding property set to AMF 3).\" It explains that differences. \nHow can I solve this problem?\n\nA:\n\nThe way that NetConnection.call works and how to construct valid requests and responses is documented in detail in the AMF0 specs in section 4. NetConnection.call has some additional functionality, like headers, the RPC method name, and whether or not the request was successful or ran into an error. This is why you can't just use writeObject to create a valid request.\nThe bit about switching from AMF0 to AMF3 is due to the fact that not every AS3 object can be written without a loss of data in AMF0, but original Flash Players all assumed that the body would be in AMF0. What happens is that during encoding, if you've specified that you want to use AMF3 for encoding, it writes out an AMF0-to-AMF3 marker (0x11) before calling writeObject in AMF3 mode.\n\n"} +{"text": "Q:\n\nIs subject omission allowed here? \"He was wrestling when [he] hurt his ankle\"\n\nWhat is the difference between the following sentences.\n\nHe was wrestling when he hurt his ankle.\nHe was wrestling when hurt his ankle.\n\nIs it okay not to repeat the same subject, he in this case, after the word when or is it necessary?\nWhich one is more idiomatic?\n\nA:\n\nThe word when can take finite clauses as a Complement (clauses with a tensed verb). When we have a finite clause, the Subject of that clause must be present:\n\n*He did this because was angry. (ungrammatical)\nHe did this because he was unhappy.\n*She laughed, although was sad. (ungrammatical)\nShe laughed although she was sad.\n\nThis is not true about non-finite clauses, which do not have any tense:\n\nBob was sacked from his job, due to always being late.\n\nIn the sentence above the non-finite verb being does not need a Subject. It has no tense, it is a participle, not a tensed verb. We understand the Subject of being to be the same as the Subject of the verb in the main clause, Bob.\nThe Original Poster's example\nThe conjunctive preposition when can take clauses with tensed verbs. When these clauses have tensed verbs (past or present tense), they must have their own Subject. \nAlthough the Subject of hurt is the same as the Subject of was wrestling, we need to use a full Subject for the second clause:\n\nHe was wrestling when he hurt his ankle.\nHe was wrestling when hurt his ankle. (ungrammatical)\n\nA:\n\nIf you leave out the second pronoun, you could write it like this:\n\nHe was wrestling and hurt his ankle.\n\ndictionary.com includes this definition of \"when\":\n\nupon or after which; and then:\nWe had just fallen asleep when the bell rang.\n\nIt needs a main clause after it because it is, in a way, joining two sentences. \"This happened\" when \"this happened\". Without the pronoun, \"hurt his ankle\" is just a fragment of a sentence.\n\n"} +{"text": "Q:\n\nSqlite query optimisation needed\n\nI'm using sqlite for a small validation application. I have a simple one table database with 4 varhchar columns and one integer primary key. There are close to 1 million rows in the table. I have optimised it and done a vacuum on it.\nI am using the following query to retrieve a presence count from the table. I have changed the fields and names for privacy.\n SELECT \n count(*) as 'test'\n FROM\n my_table\n WHERE\n LOWER(surname) = LOWER('Oliver')\n AND\n UPPER(address_line2) = UPPER('Somewhere over the rainbow') \n AND\n house_number IN ('3','4','5');\n\nThis query takes about 1.5-1.9 seconds to run. I have tried indexes and they make no difference really. This time may not sound bad but I have to run this test about 40,000 times on a read in csv file so as you may imagine it adds up pretty quickly. Any ideas on how to reduce the execution time. I normally develop in mssql or mysql so if there are some tricks I am missing in sqlite I would be happy to hear them.\nAll the best.\n\nA:\n\nWhen you use a function over an indexed column, SQLite cannot use the index, because the function may not preserve the ordering -- i.e. there can be functions such as 1>2, but F(1));\nSELECT count(*) as 'test'\nFROM my_table\nWHERE surname ='Oliver';\n\nYou can find more information about the = and LIKE operators here.\n\n"} +{"text": "Q:\n\nLocation change even when phone is kept on the table\n\nWhen getting location from the android location manager, I face an issue. Even when I am sitting at a place and not moving, the latitude and longitude I get in onLocationChange() listener are always changing. I have set the update time 500ms and update distance as 5 meters. Any idea on how to fix it?\n\nA:\n\nThe GPS offset is arround 8 meters for normal phones and about 15-20 meters for old ones. You can set the minimum distance for more than 15 meters and it should help.\nIn case you are using NETWORK provider, than it takes it's locations from WiFi routers and Cellolar towers. in that case, if the phone changes a cell tower or pick up a new WiFi, than the location might change by more than then 20 meters (20-70 meters for WiFi and 500-1500 meters for cell towers).\nAnother thing you can do is to take into account the accuracy parameter of the locations you are getting, it should give you a rough estimate on the provider error (E.G. GPS vs Network vs WiFi) and you can try to understand if the phone is moving or not by calculating:\nif (position_A.distanceTo(position_B) - position_B.getAcuracy() >0){\n do something. //location change.\n}\n\nUpdate\nsee that for clarification, while the blue dot is the location your device gives you, the actual location can be anywhere in the blue radius.\n\n"} +{"text": "Q:\n\n\"/\" after suggested address in google chrome while typing\n\nIn the latest release of Google Chrome, apart from removing the http:// (nonsense if you ask me :) ) they removed the / after the suggested address while you are typing.\nI find this VERY impractical when going to a specific subdirectory, to clarify, I used to type su then pressed the arrow pointing right and continued typing the subdirectory, now I have to hit -> key and then enter Shift+7 for / after the arrow.\nThis is not a life or death matter but I find it quite uncomfortable.\nJust in case I'll add some images for clarifications sake - when I type I have this:\n\nAnd I want this:\n\n(When I have typed only \"su\").\nSorry but I have no idea how to begin to solve this, or if there is any easy way.\nAnother problem I have is that I don't know how to Google it to see if others are having the same issue.\nAny ideas or workarounds are welcome!\n\nA:\n\nFrom Issue 54388: Address bar autocompletes go to \"google.com\" \u2014 please add the trailing slash to improve usability:\n\nWe had this behavior before Chrome was\n ever publicly released. It looked\n bizarre and caused user confusion.\nInline autocompletion is not designed\n as an accelerator for partial input,\n but as an accelerator for the complete\n address. \"google.com/search\" will\n become the inline autocompletion for\n \"goog\" if you type it significantly\n more than \"google.com\", or if you type\n \"google.com/\" and that's the\n most-typed URL with that prefix.\nWe will, indeed, do inline\n autocompletion to non-empty paths. \n The full URL needs to have a \"typed\"\n count that is at least 2, and\n noticeably larger than the typed count\n for any prefix of that URL.\n\nThis behavior is by design since version 6 and no hope of it being changed.\nMaybe one can find an extension that does it, but I, too, didn't have much luck googling for it.\nMaybe you could have a look at the extension Pop-up History.\n\n"} +{"text": "Q:\n\nhow can I calculate exponential fraction\n\nIf I want to calculate 5.24^3.2478. The base and exponential is fractional. \nIs there some function to realize it?\nthe base of frexp is 2.\n\nA:\n\nAs you mentioned C++ in the tag, try one of this method: \ndouble pow (double base , double exponent);\nfloat pow (float base , float exponent);\nlong double pow (long double base, long double exponent);\ndouble pow (Type1 base , Type2 exponent); // additional overloads\n\nReturns base raised to the power exponent.\nSee reference here.\n\n"} +{"text": "Q:\n\nHow can I parse from a line of text in Java?\n\nI have a Java program in which a line of text is received which is similar to the following\nclid=1 cid=2 client_database_id=1 client_nickname=Alessandro client_type=0|clid=2 cid=2 client_database_id=10 client_nickname=Braden client_type=1\n\nThe text is received from a Teamspeak query, and always has the same number of arguments. I need to parse it in a way with which I can receive the value of clid by knowing the value of client_nickname, for example, with something like clid.get(\"Alessandro\") to receive 1, and clid.get(\"Braden\") to receive 2, possibly with a HashMap.\nIs there a simple way to parse data in that format?\n\nA:\n\nYou could also do it like this.\nstatic HashMap> extractData(String str) {\n HashMap> data = new HashMap<>();\n for(String s: str.split(\"\\\\|\")) {\n HashMap entries = new HashMap<>();\n for(String s2: s.split(\" \")) {\n String[] entry = s2.split(\"=\");\n entries.put(entry[0], entry[1]);\n }\n data.put(entries.get(\"client_nickname\"), entries);\n }\n return data;\n}\n\npublic static void main(String[] args) {\n String str = \"clid=1 cid=2 client_database_id=1 client_nickname=Alessandro client_type=0|clid=2 cid=2 client_database_id=10 client_nickname=Braden client_type=1\";\n\n HashMap> data = extractData(str);\n System.out.println(data.get(\"Alessandro\").get(\"clid\"));\n}\n\n"} +{"text": "Q:\n\nMysql (doctrine) is duplicating count results probably due to grouping by but can't figure it out\n\nI'm using doctrine as an ORM layer but by putting a plain mysql query in my database tool i got the same results. So my problem:\nI have an invoices table, invoice_items and invoice_payments table and what i would like to get as an result is all invoices that are not paid or at least not fully paid yet. I know that the query should be almost correctly because its giving the correct amount of items back... the only thing is that it is multiplying the amount by a number of probably joined rows.\nSo the query that i have for now: \nselect invoice.*, sum(item.amount * item.quantity) as totalDue, \n sum(payment.amount) as totalPaid \nfrom invoices as invoice \n left join invoice_items as item on item.invoice_id = invoice.id \n left join invoice_payments as payment on payment.invoice_id = invoice.id \n and payment.status = 'successful' \nwhere invoice.invoice_number is not null \nand invoice.sent_at is not null \nand invoice.due_date >= '2018-05-15' \ngroup by invoice.id \nhaving count(payment.id) = 0 \n or sum(payment.amount) < sum(item.amount * item.quantity) \norder by invoice.issue_date desc, sum(payment.amount) desc;\n\nAs you can see i also have totalDue and totalPaid in my select (those are for reference only and should be removed if the query is correct).\nWhat i saw is that the amount is multiplied by six (because it has 6 items in the payments table).\nSo maybe someone could help me pointing in the right direction that it doesn't do the multiplying on the totalDue. I was thinking its probably because the group by but without my query is failing.\n\nA:\n\nBy simply using a distinct in my query i fixed the problem.\nselect invoice.*, sum(distinct(item.amount * item.quantity)) as totalDue, \n sum(payment.amount) as totalPaid \nfrom invoices as invoice \n left join invoice_items as item on item.invoice_id = invoice.id \n left join invoice_payments as payment on payment.invoice_id = invoice.id \n and payment.status = 'successful' \nwhere invoice.invoice_number is not null \nand invoice.sent_at is not null \nand invoice.due_date >= '2018-05-15' \ngroup by invoice.id \nhaving count(payment.id) = 0 \n or sum(payment.amount) < sum(distinct(item.amount * item.quantity)) \norder by invoice.issue_date desc, sum(payment.amount) desc;\n\nI would like to thank all the people who had taken the time to re-style my question ;-)\n\n"} +{"text": "Q:\n\nCakephp Input type radio. How to use Form helper for radio options having some description and paragraph of text.\n\nI want to use Cakephp Form helper for creating Radio buttons. But I've paragraphs of text and some design for each radio option.\nHow to Insert these type of radio buttons using Cakephp Form helper. I've seen before, after and separator options.\nThanks!!\n\nA:\n\nIf the form helper doesn't do what you need to do, you can either extend it using your own helper or simply create the markup by hand in your form.\nMake sure you name your fields correctly otherwise the form post won't be in the correct format for CakePHP to handle.\n\n"} +{"text": "Q:\n\n\u00bfCual es la diferencia entra HttpPost y HttpGet en MVC 5?\n\n\u00bfQu\u00e9 diferencia existe entre el uso de [HttpGet] y [HttPost], cu\u00e1ndo debe usarse uno y cuando el otro?\n\nA:\n\nBueno entendiendo tu pregunta, acerca del uso y la diferencia entre POST Y GET, que fue lo que vi desde un principio cuando vi tu pregunta.\nEn el caso del m\u00e9todo POST, el cual se usa para realizar una petici\u00f3n a un servidor enviando informaci\u00f3n, y sea para insertar o consultar algo y esperar una respuesta luego de finalizada la operaci\u00f3n recibir alg\u00fan tipo de mensaje o informaci\u00f3n. Por ejemplo yo utilizo el POST para poder iniciar sesion en una aplicacion m\u00f3vil, env\u00edo el usuario y la contrase\u00f1a a un servidor esperando la respuesta si existe el usuario y la contrase\u00f1a.\nEn el caso del GET se usa para obtener informaci\u00f3n, por ejemplo si lo que vas hacer es enviar una array de informaci\u00f3n luego de haber actualizado algo del lado del servidor, por ejemplo, cuando luego de conectarte a tu tel\u00e9fono te llegan mensajes sin necesidad de enviar alg\u00fan tipo de informacion.\n\n"} +{"text": "Q:\n\nHow can I get the column number in a SWT table in Eclipse RCP?\n\nMy question is How can we find the currently selected column number in the selected row of a SWT Table in Eclipse RCP? \n\nA:\n\nInside a Listener - e.g. for SWT.Selection - you can use viewer.getCell(...) as illustrated in the following example:\nmyTableViewer.getTable().addListener(SWT.Selection, new Listener() {\n @Override\n public void handleEvent(Event event) {\n Point p = new Point(event.x, event.y);\n ViewerCell cell = myTableViewer.getCell(p);\n int columnIndex = cell.getColumnIndex();\n //...\n }\n});\n\n"} +{"text": "Q:\n\nReturn a date based on criteria in excel\n\nI have a table of athlete names, training sessions and completion dates. \nFrom this table, I want to extract the most recent dates (excluding the current date) that a specific athlete completed a specific session. \nSo far my formula is as follows: \n= IF (MATCH ($AC27&$AD27\n ,'Data'!$A$2:$A$2000 & 'Data'!$BS$2:$BS$2000\n , 0\n )\n ,MAX(('Data'!$B$2:$B$2000 < $AE$1) * 'Data'!$B$2:$B$2000)\n ,\n )\n\nwhere \n'Data'! - Threshold Efforts Data Entry sheet\n$AC$27 - specific athlete name \nAD$27 - specific athlete session \n$A$2:$A$2000 - lookup array for athlete names\n$BS$2:$BS$2000 - look up array for sessions\n$B$2:$B$2000 - look up array for dates\n$AE$1 - the current date\n\nThe formula works, however it returns the most recent date, rather than the most recent date matched for the athlete name and session.\nWhere have I gone wrong ?\n\nA:\n\nThis works for me.\n=MAX(IF($A$5:$A$12=D5,IF($B$5:$B$12<$B$1,$B$5:$B$12)))\n\nIt's an array function, so click in the cell and press ctrl + shift + enter.\n\n"} +{"text": "Q:\n\nAre we doing randori properly?\n\nAt my judo club randori is usually 30-45mins at the end of the session. Some nights we just have randori for an hour and a half. The randori itself usually consists of 5min bouts with no break in between, everyone in the club gives maximum effort, there are no weight classes and most are exhausted after about the third partner change. Is this a good way to practice? I feel that the standard of judo just drops as soon as everyone gets tired and don't believe this is the best way to practice.\nIf you take a look at BJJ training for example, rolling is never really 100%. In fact it is encouraged not to go 100% so that you can get more out of the practice trying many different positions and techniques each practice until it all becomes muscle memory, rather that just getting stuck in someones full guard for 5mins. I believe judo could benefit with this approach to training for example have randori session were you just go with any attempt at a throw to help your partner work out when it is best to come in for a throw and to help them with their technique. Two people going hammer and tongs at each other for 5mins with terrible technique will not make a good judo player in my opinion.\n\nA:\n\nRandori of six to nine or more 5-minute rounds without a break sounds just about perfect. One can't get in solid judo shape without hard training like that.\nDegradation of technique should be examined as its own problem. Are students in poor shape? Are they not training frequently enough to get in good shape? Are students playing too competitively, and so excessively spending energy in early rounds? Or are only some students merely slowing down a bit towards the end, as is natural and not too problematic?\nNo weight classes is absolutely necessary and correct. Judoka should be able to train with everybody.\nThe part about \"maximum effort\" could be an issue. A dojo needs hard randori, but it needs loose randori too. Drills such as \"throw for throw\" are useful. So is what I've heard called \"French randori\", where each partner plays hard on attack, but attempts no defensive techniques other than footwork. If randori is like shiai in every workout, you're either already at the elite level and preparing for a major tournament or something is wrong. Judo practice should involve somewhat cooperative training sometimes. \nHard, almost-shiai-style randori is necessary, too. If randori is playful and cooperative all the time, you risk \"dulling the sword\" of your techniques. You need to practice against people going lightly and cooperatively to try new things you're not sure of, but you also need to practice with partners resisting hard in order to sharpen your waza into something that will work in shiai or in violent application.\nOne method that helped me turn down the intensity of my randori was to make sure I took ukemi for three throws with each partner before attempting my own throw. This can set a playful mood that encourages more back-and-forth rather than escalation towards shiai intensity.\n\nA:\n\nIn Canada, when you take the elite class at the national team ( the club is called Shidokan and regroup the people who are training for the Olympics, or trying to get there), the WHOLE CLASS was 5 minutes randori. 5 nights a week. 2 hours a day. \nThe coach was sitting in middle of the class, watching, sometimes giving hints or bits of advice. \nyou had a 30 seconds break in between to go drink water, and you could sit out once in a while if you were too tired ... but you couldn't refuse a fight, if you want to win the respect of the team's member, just give your 100%. Fighting pass exhaustion is a good way to push further and ask your body to give more ...\nand I think this is even more important now, considering international competitions now go in \"overtime\", so you can see 7 or 8 minutes fight.\nWhen I started over there, I was 15, and not strong enough to fight vs man, so I was doing randori against older person who where training once in a while with the team, or against woman, since physical strengh was less different between us. \nI was sooo in shape compare to the other kids my age, and beating them easily, that they started to realize I was training much harder than they did, and started to show up at the club too. \n\n"} +{"text": "Q:\n\nRemoving bullets from unordered list\n\nEdit\nThe html and css for the site I am working on can be found at http://http://new.oranaschool.com/\n/Edit\nI am trying to remove the bullets showing in the top horizontal menu (Home...Contact). I have tried the advice given in Removing \"bullets\" from unordered list